├── .gitignore
├── .sonar-ide.properties
├── LICENSE
├── README.md
├── atlassian-ide-plugin.xml
├── etc
├── CheckstyleSonar.xml
├── FindbugsSonar.xml
├── FindbugsSonarExclude.xml
├── PMDSonar.xml
├── check-style-suppressions.xml
├── sdsdb.formatter.eclipse.xml
└── sdsdb.formatter.intellij.prefs
├── pom.xml
├── spring-data-simpledb-impl
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── org
│ │ │ └── springframework
│ │ │ └── data
│ │ │ └── simpledb
│ │ │ ├── annotation
│ │ │ ├── Attributes.java
│ │ │ ├── DomainPrefix.java
│ │ │ └── Query.java
│ │ │ ├── attributeutil
│ │ │ ├── AmazonSimpleDBUtil.java
│ │ │ ├── AttributesKeySplitter.java
│ │ │ ├── SimpleDBAttributeConverter.java
│ │ │ └── SimpleDbAttributeValueSplitter.java
│ │ │ ├── config
│ │ │ ├── AWSCredentials.java
│ │ │ └── AbstractSimpleDBConfiguration.java
│ │ │ ├── core
│ │ │ ├── AbstractServiceUnavailableOperationRetrier.java
│ │ │ ├── AbstractSimpleDbTemplate.java
│ │ │ ├── DomainItemBuilder.java
│ │ │ ├── QueryBuilder.java
│ │ │ ├── SimpleDb.java
│ │ │ ├── SimpleDbDomain.java
│ │ │ ├── SimpleDbOperations.java
│ │ │ ├── SimpleDbRequestBuilder.java
│ │ │ ├── SimpleDbTemplate.java
│ │ │ ├── domain
│ │ │ │ ├── DomainManagementPolicy.java
│ │ │ │ └── DomainManager.java
│ │ │ └── entity
│ │ │ │ ├── AbstractFieldWrapper.java
│ │ │ │ ├── AbstractSimpleFieldWrapper.java
│ │ │ │ ├── EntityWrapper.java
│ │ │ │ ├── FieldWrapperFactory.java
│ │ │ │ ├── InstantiableFieldWrapper.java
│ │ │ │ ├── JSONFieldWrapper.java
│ │ │ │ ├── NestedEntityFieldWrapper.java
│ │ │ │ ├── ReferenceEntityFieldWrapper.java
│ │ │ │ ├── SimpleFieldWrapper.java
│ │ │ │ └── json
│ │ │ │ ├── JsonMarshaller.java
│ │ │ │ └── JsonUnknownPropertyHandler.java
│ │ │ ├── exception
│ │ │ ├── InvalidSimpleDBQueryException.java
│ │ │ ├── SimpleDbExceptionTranslator.java
│ │ │ └── UncategorizedSpringDaoException.java
│ │ │ ├── query
│ │ │ ├── PartTreeConverter.java
│ │ │ ├── QueryUtils.java
│ │ │ ├── SdbItemQuery.java
│ │ │ ├── SimpleDbPartTreeQueryMethod.java
│ │ │ ├── SimpleDbQueryLookupStrategy.java
│ │ │ ├── SimpleDbQueryMethod.java
│ │ │ ├── SimpleDbQueryRunner.java
│ │ │ ├── SimpleDbRepositoryQuery.java
│ │ │ ├── SimpleDbResultConverter.java
│ │ │ ├── executions
│ │ │ │ ├── AbstractSimpleDbQueryExecution.java
│ │ │ │ ├── MultipleResultExecution.java
│ │ │ │ ├── PagedResultExecution.java
│ │ │ │ └── SingleResultExecution.java
│ │ │ └── parser
│ │ │ │ └── QueryParserUtils.java
│ │ │ ├── reflection
│ │ │ ├── FieldType.java
│ │ │ ├── FieldTypeIdentifier.java
│ │ │ ├── MetadataParser.java
│ │ │ ├── ReflectionUtils.java
│ │ │ └── SupportedCoreTypes.java
│ │ │ ├── repository
│ │ │ ├── SimpleDbPagingAndSortingRepository.java
│ │ │ ├── config
│ │ │ │ ├── EnableSimpleDBRepositories.java
│ │ │ │ ├── SimpleDBRepositoriesRegistrar.java
│ │ │ │ ├── SimpleDbRepositoryConfigExtension.java
│ │ │ │ └── SimpleDbRepositoryNamespaceHandler.java
│ │ │ └── support
│ │ │ │ ├── EmptyResultDataAccessException.java
│ │ │ │ ├── SimpleDbRepositoryFactory.java
│ │ │ │ ├── SimpleDbRepositoryFactoryBean.java
│ │ │ │ ├── SimpleDbRepositoryImpl.java
│ │ │ │ └── entityinformation
│ │ │ │ ├── SimpleDBEntityMappingInformation.java
│ │ │ │ ├── SimpleDbEntityInformation.java
│ │ │ │ ├── SimpleDbEntityInformationSupport.java
│ │ │ │ └── SimpleDbMetamodelEntityInformation.java
│ │ │ └── util
│ │ │ ├── AlphanumStringComparator.java
│ │ │ ├── MapUtils.java
│ │ │ ├── RandomValueGenerator.java
│ │ │ └── StringUtil.java
│ └── resources
│ │ ├── META-INF
│ │ ├── spring.handlers
│ │ ├── spring.schemas
│ │ └── spring.tooling
│ │ └── org
│ │ └── springframework
│ │ └── data
│ │ └── simpledb
│ │ └── config
│ │ └── spring-simpledb.xsd
│ └── test
│ └── java
│ └── org
│ └── springframework
│ └── data
│ └── simpledb
│ ├── attributeutil
│ ├── SimpleDBAttributeConverterTest.java
│ └── SimpleDbAttributeValueSplitterTest.java
│ ├── core
│ ├── DomainItemBuilderTest.java
│ ├── NestedDomainEntitiesTest.java
│ ├── NestedReferencedDomainTest.java
│ ├── QueryBuilderTest.java
│ ├── SimpleDbOperationRetrierTest.java
│ ├── domain
│ │ ├── SimpleDbReferencesEntity.java
│ │ └── SimpleDbSampleEntity.java
│ └── entity
│ │ ├── CollectionWrapperTest.java
│ │ ├── CoreTypeWrapperTest.java
│ │ ├── EntityWrapperTest.java
│ │ ├── MapWrapperTest.java
│ │ ├── ObjectFieldWrapperTest.java
│ │ ├── PrimitiveArrayWrapperTest.java
│ │ ├── json
│ │ └── JsonMarshallerTest.java
│ │ └── util
│ │ └── AttributeUtil.java
│ ├── exception
│ └── SimpleDbExceptionTranslatorTest.java
│ ├── query
│ ├── PartTreeConverterTest.java
│ ├── QueryUtilsArrayTest.java
│ ├── QueryUtilsEscapeTest.java
│ ├── QueryUtilsIndexByQueryTest.java
│ ├── QueryUtilsNamedQueryTest.java
│ ├── QueryUtilsPartialFieldNamesTest.java
│ ├── SampleEntity.java
│ ├── SimpleDbIndexByQueryMethodBindedTest.java
│ ├── SimpleDbNamedQueryMethodBindedTest.java
│ ├── SimpleDbQueryMethodWithSelectAndWhereClauseTest.java
│ ├── SimpleDbQueryMethodWithSelectClauseTest.java
│ ├── SimpleDbQueryMethodWithWhereClauseTest.java
│ ├── SimpleDbQueryRunnerTest.java
│ ├── SimpleDbRepositoryQueryTest.java
│ ├── SimpleDbResultConverterTest.java
│ └── executions
│ │ ├── MultipleResultExecutionTest.java
│ │ └── PagedResultExecutionTest.java
│ └── util
│ ├── AlphanumStringComparatorTest.java
│ ├── EntityInformationSupport.java
│ ├── GetterAndSetterTest.java
│ ├── MapUtilsTest.java
│ ├── MetadataParserFieldDefinitionTest.java
│ └── MetadataParserTest.java
├── spring-data-simpledb-integration-tests
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── org
│ │ │ └── springframework
│ │ │ └── data
│ │ │ └── simpledb
│ │ │ ├── domain
│ │ │ ├── JSONCompatibleClass.java
│ │ │ ├── SimpleDbReferences.java
│ │ │ ├── SimpleDbUser.java
│ │ │ └── demo
│ │ │ │ ├── Source.java
│ │ │ │ └── UserJob.java
│ │ │ ├── logging
│ │ │ └── LoggingConfiguration.java
│ │ │ └── repository
│ │ │ ├── BasicSimpleDbUserRepository.java
│ │ │ ├── PagingAndSortingUserRepository.java
│ │ │ ├── SimpleDbReferencesRepository.java
│ │ │ ├── SimpleDbUserRepositoryConsistent.java
│ │ │ ├── demo
│ │ │ └── UserJobRepository.java
│ │ │ └── query
│ │ │ ├── AnnotatedQueryRepository.java
│ │ │ ├── AnnotatedSingleResultQueryRepository.java
│ │ │ ├── NamedQueryRepository.java
│ │ │ └── PagedAnnotatedQueryRepository.java
│ └── resources
│ │ ├── aws-keys.properties.sample
│ │ ├── log4j.properties
│ │ ├── simpledb-configured-template-context.xml
│ │ ├── simpledb-consistent-repository-context.xml
│ │ ├── simpledb-repository-context.xml
│ │ └── simpledb-with-templates-context.xml
│ └── test
│ └── java
│ └── org
│ └── springframework
│ └── data
│ └── simpledb
│ ├── config
│ ├── SampleConfiguration.java
│ ├── SampleConfigurationTest.java
│ └── SimpleDBJavaConfiguration.java
│ ├── core
│ ├── SimpleDBTemplateInjectionTest.java
│ ├── SimpleDbTemplateTest.java
│ └── domain
│ │ └── DomainManagerTest.java
│ └── repository
│ ├── BasicSimpleDbUserConsistentExtendedRepositoryTest.java
│ ├── BasicSimpleDbUserConsistentPropertyRepositoryTest.java
│ ├── BasicSimpleDbUserRepositoryTest.java
│ ├── PagingAndSortingSimpleDbUserRepositoryTest.java
│ ├── SimpleDBJavaConfigurationRepositoryTest.java
│ ├── SimpleDBLimitationsTest.java
│ ├── SimpleDbReferencesRepositoryTest.java
│ ├── config
│ └── EnableSimpleDBRepositoriesAnnotationTest.java
│ ├── demo
│ └── UserJobTest.java
│ ├── query
│ ├── AnnotatedQueryTest.java
│ ├── AnnotatedSingleResultQueryTest.java
│ ├── NamedQueryRepositoryTest.java
│ └── PagedAnnotatedQueryRepositoryTest.java
│ └── util
│ ├── IncrementalWait.java
│ └── SimpleDbUserBuilder.java
└── spring-data-simpledb-parser
├── pom.xml
└── src
├── main
├── java
│ └── org
│ │ └── springframework
│ │ └── data
│ │ └── simpledb
│ │ └── parser
│ │ ├── ParseException.java
│ │ ├── SimpleCharStream.java
│ │ ├── SimpleDBParser.java
│ │ ├── SimpleDBParserConstants.java
│ │ ├── SimpleDBParserTokenManager.java
│ │ ├── Token.java
│ │ └── TokenMgrError.java
└── javacc
│ └── SimpleDB.jj
└── test
└── java
└── org
└── springframework
└── data
└── simpledb
└── parser
├── SimpleDBParserFromTest.java
├── SimpleDBParserLimitTest.java
├── SimpleDBParserSelectTest.java
├── SimpleDBParserSortTest.java
└── SimpleDBParserWhereTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | .project
2 | .classpath
3 | .springBeans
4 | .settings/
5 | .idea
6 | .idea/
7 | *.iml
8 | target/
9 | generated/
10 |
11 | #Build
12 | target
13 | target-eclipse
14 | *.class
15 | #Misc
16 | *~
17 | *.info
18 |
19 | #Idea
20 | *.iml
21 | *.ipr
22 | *.iws
23 | .idea
24 |
25 | #Eclipse
26 | .classpath
27 | .project
28 | .settings
29 | .pmd*
30 |
31 | *.log
32 | *.log*
33 | logs
34 |
35 | *.pyc
36 | *.DS_Store
37 | *.swp
38 | *.vim
39 |
40 | *.orig
41 | aws-keys.properties
--------------------------------------------------------------------------------
/.sonar-ide.properties:
--------------------------------------------------------------------------------
1 | #Sonar Settings
2 | #Mon Feb 11 13:53:31 EET 2013
3 | password=
4 | host=
5 | username=
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 3Pillar Global, Inc.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/atlassian-ide-plugin.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 697c3756-35bb-4e9d-a503-299a491ba573
6 | SDSDB
7 | https://helpdesk.threepillar.net/jira
8 | false
9 |
10 |
11 | SDSDB
12 | 697c3756-35bb-4e9d-a503-299a491ba573
13 |
14 |
--------------------------------------------------------------------------------
/etc/FindbugsSonarExclude.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/etc/check-style-suppressions.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/annotation/Attributes.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2008-2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.springframework.data.simpledb.annotation;
17 |
18 | import java.lang.annotation.Documented;
19 | import java.lang.annotation.ElementType;
20 | import java.lang.annotation.Retention;
21 | import java.lang.annotation.RetentionPolicy;
22 | import java.lang.annotation.Target;
23 |
24 | /**
25 | * Should mark only Multimaps with Attribute keys, values
26 | */
27 | @Retention(RetentionPolicy.RUNTIME)
28 | @Target(ElementType.FIELD)
29 | @Documented
30 | public @interface Attributes {
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/annotation/DomainPrefix.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2008-2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.springframework.data.simpledb.annotation;
17 |
18 | import java.lang.annotation.Documented;
19 | import java.lang.annotation.ElementType;
20 | import java.lang.annotation.Retention;
21 | import java.lang.annotation.RetentionPolicy;
22 | import java.lang.annotation.Target;
23 |
24 | /**
25 | * Should mark only Multimaps with Attribute keys, values
26 | */
27 | @Retention(RetentionPolicy.RUNTIME)
28 | @Target(ElementType.TYPE)
29 | @Documented
30 | public @interface DomainPrefix {
31 |
32 | String value();
33 | }
34 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/annotation/Query.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.annotation;
2 |
3 | import java.lang.annotation.*;
4 |
5 | /**
6 | * Annotation to declare finder queries directly on repository methods.
7 | *
8 | *
9 | * Query Annotation used in Repository Metadata, can have three Types of Parameters
10 | *
11 | * value : if value annotation is present, query string should be correct and well formatted
12 | *
13 | *
14 | * select : contains selective attributes, can be independent of the "where" clause; the Domain is inferred at
15 | * runtime based on Repository-Metadata
16 | *
17 | *
18 | * where : contains the WHERE clause, might contain parameter placeholders
19 | *
20 | *
21 | */
22 | @Retention(RetentionPolicy.RUNTIME)
23 | @Target(ElementType.METHOD)
24 | @Documented
25 | public @interface Query {
26 |
27 | /**
28 | * Defines the SimpleDb query to be executed when the annotated method is called.
29 | */
30 | String value() default "";
31 |
32 | String where() default "";
33 |
34 | String[] select() default "";
35 |
36 | public enum QueryClause {
37 | SELECT("select"), VALUE("value"), WHERE("where");
38 |
39 | private String queryClause;
40 |
41 | private QueryClause(String newValue) {
42 | this.queryClause = newValue;
43 | }
44 |
45 | public String getQueryClause() {
46 | return this.queryClause;
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/attributeutil/AttributesKeySplitter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * To change this template, choose Tools | Templates
3 | * and open the template in the editor.
4 | */
5 | package org.springframework.data.simpledb.attributeutil;
6 |
7 | import java.util.HashMap;
8 | import java.util.LinkedHashMap;
9 | import java.util.Map;
10 |
11 | public final class AttributesKeySplitter {
12 |
13 | private AttributesKeySplitter() {
14 | /* utility class */
15 | }
16 |
17 | public static Map> splitNestedAttributeKeys(Map attributes) {
18 | final Map> nestedFieldAttributes = new HashMap>();
19 |
20 | for(final Map.Entry entry : attributes.entrySet()) {
21 | final String key = entry.getKey();
22 |
23 | if(key.contains(".")) {
24 | Map nestedFieldValues = new HashMap();
25 | int prefixIndex = key.indexOf('.');
26 | final String nestedFieldName = key.substring(0, prefixIndex);
27 | final String subField = key.substring(prefixIndex + 1);
28 |
29 | if(nestedFieldAttributes.containsKey(nestedFieldName)) {
30 | nestedFieldValues = nestedFieldAttributes.get(nestedFieldName);
31 | }
32 |
33 | nestedFieldValues.put(subField, entry.getValue());
34 |
35 | nestedFieldAttributes.put(nestedFieldName, nestedFieldValues);
36 | }
37 | }
38 | return nestedFieldAttributes;
39 | }
40 |
41 | public static Map splitSimpleAttributesKeys(Map attributes) {
42 |
43 | Map primitiveAttributes = new LinkedHashMap();
44 |
45 | for(final Map.Entry entry : attributes.entrySet()) {
46 | if(isSimpleKey(entry.getKey())) {
47 | primitiveAttributes.put(entry.getKey(), entry.getValue());
48 | }
49 | }
50 |
51 | return primitiveAttributes;
52 |
53 | }
54 |
55 | private static boolean isSimpleKey(final String key) {
56 | return !key.contains(".");
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/attributeutil/SimpleDbAttributeValueSplitter.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.attributeutil;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.HashMap;
6 | import java.util.LinkedHashMap;
7 | import java.util.LinkedList;
8 | import java.util.List;
9 | import java.util.Map;
10 | import java.util.Set;
11 | import java.util.regex.Matcher;
12 | import java.util.regex.Pattern;
13 |
14 | import org.springframework.dao.DataIntegrityViolationException;
15 | import org.springframework.data.simpledb.util.AlphanumStringComparator;
16 |
17 | /**
18 | * Used to split, combine attribute values exceeding Simple Db Length limitation: 1024
19 | */
20 | public final class SimpleDbAttributeValueSplitter {
21 |
22 | private static Pattern multiValueRexp = Pattern.compile("^\\d+@(.+?)$");
23 | private static AlphanumStringComparator multiValueComparator = new AlphanumStringComparator();
24 |
25 |
26 | private SimpleDbAttributeValueSplitter() {
27 | // utility class
28 | }
29 |
30 | public static final int MAX_ATTR_VALUE_LEN = 1024;
31 |
32 | public static Map> splitAttributeValuesWithExceedingLengths(Map rawAttributes) {
33 | Map> splitAttributes = new LinkedHashMap>();
34 |
35 | Set> rawEntries = rawAttributes.entrySet();
36 |
37 | for(Map.Entry rawEntry : rawEntries) {
38 | splitAttributes.put(rawEntry.getKey(), new ArrayList());
39 | if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) {
40 | splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue()));
41 | } else {
42 | splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue());
43 | }
44 | }
45 |
46 | return splitAttributes;
47 | }
48 |
49 | private static List splitExceedingValue(String attributeValue) {
50 | List splitValues = new LinkedList();
51 | int length = attributeValue.length();
52 | // calculate number of chunks correcting for added qualifiers
53 | int numChunks = (length <= MAX_ATTR_VALUE_LEN ? 1 : ((length / MAX_ATTR_VALUE_LEN) + 1));
54 | int maxChunkLength = MAX_ATTR_VALUE_LEN - String.format("%d@", numChunks).length();
55 | numChunks = (length <= maxChunkLength ? 1 : ((length / maxChunkLength) + 1));
56 | int chunkCount = 0;
57 | for(int i = 0; i < length; i += maxChunkLength) {
58 | String e = attributeValue.substring(i, Math.min(length, i + maxChunkLength));
59 | splitValues.add(String.format("%d@%s", chunkCount++, e));
60 | }
61 | return splitValues;
62 | }
63 |
64 | public static Map combineAttributeValuesWithExceedingLengths(Map> multiValueAttributes) {
65 | final Map attributes = new HashMap();
66 | for (Map.Entry> entry : multiValueAttributes.entrySet()) {
67 | List values = entry.getValue();
68 | if (values.size() == 1) {
69 | attributes.put(entry.getKey(), values.get(0));
70 | } else {
71 | Collections.sort(values, multiValueComparator);
72 | StringBuilder builder = new StringBuilder();
73 | for (String vwp : values) {
74 | Matcher m = multiValueRexp.matcher(vwp);
75 | if (m.find()) {
76 | builder.append(m.group(1));
77 | } else {
78 | throw new DataIntegrityViolationException("Multivalue attribute with digit@ pattern but no following value");
79 | }
80 | }
81 | attributes.put(entry.getKey(), builder.toString());
82 | }
83 | }
84 |
85 | return attributes;
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/config/AWSCredentials.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.config;
2 |
3 | public class AWSCredentials {
4 |
5 | private String accessID;
6 | private String secretKey;
7 |
8 |
9 | public AWSCredentials(String accessID, String secretKey){
10 | this.accessID = accessID;
11 | this.secretKey = secretKey;
12 | }
13 |
14 |
15 | public String getAccessID() {
16 | return accessID;
17 | }
18 |
19 | public String getSecretKey() {
20 | return secretKey;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/config/AbstractSimpleDBConfiguration.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.data.simpledb.core.SimpleDb;
6 | import org.springframework.data.simpledb.core.SimpleDbTemplate;
7 |
8 | /**
9 | * Base class for Spring Data SimpleDB configuration using JavaConfig.
10 | *
11 | *
12 | * support for useful bean injection
13 | * support for declaring SimpleDB configuration elements
14 | *
15 | */
16 | @Configuration
17 | public abstract class AbstractSimpleDBConfiguration {
18 |
19 |
20 | @Bean
21 | public SimpleDbTemplate simpleDBTemplate(){
22 | return new SimpleDbTemplate(simpleDb());
23 | }
24 |
25 |
26 | public abstract AWSCredentials getAWSCredentials();
27 |
28 | /**
29 | * Override this to configure non credential {@link org.springframework.data.simpledb.core.SimpleDb} properties
30 | */
31 | public void setExtraProperties(SimpleDb simpleDb){
32 | }
33 |
34 | @Bean
35 | public SimpleDb simpleDb(){
36 | AWSCredentials credentials = getAWSCredentials();
37 | SimpleDb simpleDb = new SimpleDb(credentials.getAccessID(), credentials.getSecretKey());
38 | setExtraProperties(simpleDb);
39 | return simpleDb;
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/AbstractServiceUnavailableOperationRetrier.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import com.amazonaws.AmazonClientException;
4 | import com.amazonaws.AmazonServiceException;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.dao.DataAccessResourceFailureException;
8 | import org.springframework.data.simpledb.exception.SimpleDbExceptionTranslator;
9 |
10 | /**
11 | * Enables callbacks on execute()
12 | */
13 | public abstract class AbstractServiceUnavailableOperationRetrier {
14 |
15 | private int serviceUnavailableRetries;
16 |
17 | public AbstractServiceUnavailableOperationRetrier(int serviceUnavailableRetries) {
18 | this.serviceUnavailableRetries = serviceUnavailableRetries;
19 | }
20 |
21 | private static final int RETRY_TIME = 400;
22 | private int currentRetry = 0;
23 | private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSimpleDbTemplate.class);
24 | public static final int SERVICE_UNAVAILABLE_STATUS_CODE = 503;
25 |
26 | /**
27 | * Override this method for specific operations that need retry for Amazon ServiceUnavailableException
28 | */
29 | public abstract void execute();
30 |
31 | public final void executeWithRetries() {
32 | try {
33 | AmazonClientException serviceUnavailableException = null;
34 | serviceUnavailableException = tryExecute();
35 |
36 | while ((serviceUnavailableException != null) && currentRetry < serviceUnavailableRetries) {
37 | try {
38 | Thread.sleep(RETRY_TIME);
39 | } catch (InterruptedException e) {
40 | LOGGER.debug(e.getLocalizedMessage());
41 | }
42 |
43 | LOGGER.debug("Retrying operation");
44 | currentRetry++;
45 | serviceUnavailableException = tryExecute();
46 | }
47 |
48 | if (currentRetry == serviceUnavailableRetries) {
49 | throw new DataAccessResourceFailureException(
50 | "SimpleDB operation failed for " + currentRetry + " times", serviceUnavailableException);
51 | }
52 | } catch (AmazonClientException exception) {
53 | throw SimpleDbExceptionTranslator.getTranslatorInstance().translateAmazonClientException(exception);
54 | }
55 |
56 | }
57 |
58 | /**
59 | * @return recognized exception or null, throws further not recognized exception
60 | */
61 | private AmazonClientException tryExecute() {
62 | try {
63 | execute();
64 | } catch (AmazonClientException clientException) {
65 | if (isServiceUnavailableException(clientException)) {
66 | return clientException;
67 | }
68 |
69 | throw clientException;
70 | }
71 |
72 | return null;
73 | }
74 |
75 | private boolean isServiceUnavailableException(AmazonClientException e) {
76 | return (((AmazonServiceException) e).getErrorType() == AmazonServiceException.ErrorType.Service
77 | && ((AmazonServiceException) e).getStatusCode() == AbstractServiceUnavailableOperationRetrier.SERVICE_UNAVAILABLE_STATUS_CODE);
78 |
79 | }
80 |
81 | public int getCurrentRetry() {
82 | return currentRetry;
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/DomainItemBuilder.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 | import java.util.HashMap;
6 | import java.util.List;
7 | import java.util.Map;
8 |
9 | import org.springframework.data.simpledb.attributeutil.SimpleDbAttributeValueSplitter;
10 | import org.springframework.data.simpledb.core.entity.EntityWrapper;
11 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformation;
12 |
13 | import com.amazonaws.services.simpledb.model.Attribute;
14 | import com.amazonaws.services.simpledb.model.Item;
15 | import com.amazonaws.services.simpledb.model.SelectResult;
16 |
17 | public class DomainItemBuilder {
18 |
19 | public List populateDomainItems(SimpleDbEntityInformation entityInformation, SelectResult selectResult) {
20 | final List allItems = new ArrayList();
21 |
22 | for(Item item : selectResult.getItems()) {
23 | allItems.add(populateDomainItem(entityInformation, item));
24 | }
25 |
26 | return allItems;
27 | }
28 |
29 | /**
30 | * Used during deserialization process, each item being populated based on attributes retrieved from DB
31 | * @param entityInformation
32 | * @param item
33 | * @return T the Item Instance
34 | */
35 | public T populateDomainItem(SimpleDbEntityInformation entityInformation, Item item) {
36 | return buildDomainItem(entityInformation, item);
37 | }
38 |
39 | private T buildDomainItem(SimpleDbEntityInformation entityInformation, Item item) {
40 | EntityWrapper entity = new EntityWrapper(entityInformation);
41 |
42 | entity.setId(item.getName());
43 | final Map attributes = convertSimpleDbAttributes(item.getAttributes());
44 | entity.deserialize(attributes);
45 |
46 | return entity.getItem();
47 | }
48 |
49 | private Map convertSimpleDbAttributes(List simpleDbAttributes) {
50 | final Map> multiValueAttributes = new HashMap>();
51 | for (Attribute attr : simpleDbAttributes) {
52 | if (!multiValueAttributes.containsKey(attr.getName())) {
53 | multiValueAttributes.put(attr.getName(), new ArrayList());
54 | }
55 | multiValueAttributes.get(attr.getName()).add(attr.getValue());
56 | }
57 |
58 | return SimpleDbAttributeValueSplitter.combineAttributeValuesWithExceedingLengths(multiValueAttributes);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/QueryBuilder.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import java.util.Iterator;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.data.domain.Pageable;
8 | import org.springframework.data.domain.Sort;
9 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformation;
10 |
11 | public class QueryBuilder {
12 |
13 | private static final Logger LOGGER = LoggerFactory.getLogger(QueryBuilder.class);
14 |
15 | private StringBuilder query;
16 |
17 | public QueryBuilder(SimpleDbEntityInformation, ?> entityInformation) {
18 | this(entityInformation, false);
19 | }
20 |
21 | public QueryBuilder(SimpleDbEntityInformation, ?> entityInformation, boolean shouldCount) {
22 | query = new StringBuilder();
23 | query.append("select");
24 |
25 | if(shouldCount) {
26 | query.append(" count(*) ");
27 | } else {
28 | query.append(" * ");
29 | }
30 |
31 | query.append("from ").append(quote(entityInformation.getDomain()));
32 | }
33 |
34 | public QueryBuilder(String customQuery) {
35 | this(customQuery, false);
36 | }
37 |
38 | public QueryBuilder(String customQuery, boolean shouldCount) {
39 | this.query = new StringBuilder();
40 |
41 | if(shouldCount) {
42 | query.append("select count(*) from ").append(customQuery.split("from")[1]);
43 | } else {
44 | query.append(customQuery);
45 | }
46 | }
47 |
48 | public QueryBuilder withLimit(final int limit) {
49 | query.append(" limit ").append(limit);
50 |
51 | return this;
52 | }
53 |
54 | public QueryBuilder withIds(Iterable> iterable) {
55 | Iterator> iterator = iterable.iterator();
56 | appendWhereOrEndClause(query);
57 |
58 | query.append("(");
59 | while(iterator.hasNext()) {
60 | query.append("itemName()='").append(iterator.next().toString()).append("'");
61 | if(iterator.hasNext()) {
62 | query.append(" or ");
63 | }
64 | }
65 | query.append(")");
66 | return this;
67 | }
68 |
69 | public QueryBuilder with(Sort sort) {
70 | if(sort != null) {
71 | Iterator sortIt = sort.iterator();
72 | if(sortIt.hasNext()) {
73 | Sort.Order order = sortIt.next();
74 | appendWhereOrEndClause(query);
75 | query.append(order.getProperty()).append(" is not null order by ");
76 | query.append(order.getProperty()).append(" ").append(order.getDirection().name().toLowerCase());
77 | }
78 | if(sortIt.hasNext()) {
79 | throw new IllegalArgumentException("SimpleDb does not support multiple sorting");
80 | }
81 | }
82 |
83 | return this;
84 | }
85 |
86 | public QueryBuilder with(Pageable pageable) {
87 | Sort sort = pageable.getSort();
88 | if(sort != null) {
89 | with(sort);
90 | }
91 |
92 | if(pageable.getPageSize() > 0) {
93 | withLimit(pageable.getPageSize());
94 | }
95 |
96 | return this;
97 | }
98 |
99 | @Override
100 | public String toString() {
101 | // TODO change itemName() to ID field from domain object
102 | String result = query.toString();
103 | LOGGER.debug("Created query: {}", result);
104 | return result;
105 | }
106 |
107 | private void appendWhereOrEndClause(StringBuilder query) {
108 | if(query.indexOf("where") > 0) {
109 | query.append(" and ");
110 | } else {
111 | query.append(" where ");
112 | }
113 | }
114 |
115 | private String quote(String simpleDbName) {
116 | return "`" + simpleDbName + "`";
117 | }
118 |
119 | }
120 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/SimpleDbDomain.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import org.springframework.data.simpledb.annotation.DomainPrefix;
4 | import org.springframework.data.simpledb.util.StringUtil;
5 |
6 | public class SimpleDbDomain {
7 |
8 | private String domainPrefix;
9 |
10 | public SimpleDbDomain() {
11 |
12 | }
13 |
14 | public SimpleDbDomain(final String domainPrefix) {
15 | this.domainPrefix = domainPrefix;
16 | }
17 |
18 | /**
19 | * Domain name are computed based on class names: UserJob -> user_job
20 | *
21 | * @param clazz
22 | * @return
23 | */
24 | public String getDomain(Class> clazz) {
25 | StringBuilder ret = new StringBuilder();
26 |
27 | String computedDomainPrefix = getDomainPrefix(clazz);
28 | if(computedDomainPrefix != null) {
29 | ret.append(computedDomainPrefix);
30 | ret.append(".");
31 | }
32 |
33 | String camelCaseString = clazz.getSimpleName();
34 |
35 | ret.append(StringUtil.toLowerFirstChar(camelCaseString));
36 |
37 | return ret.toString();
38 | }
39 |
40 | private String getDomainPrefix(Class> clazz) {
41 | String prefix = null;
42 | DomainPrefix annotatedDomainPrefix = clazz.getAnnotation(DomainPrefix.class);
43 | if (annotatedDomainPrefix != null) {
44 | prefix = annotatedDomainPrefix.value();
45 | } else {
46 | prefix = this.domainPrefix;
47 | }
48 |
49 | return prefix;
50 | }
51 |
52 | }
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/SimpleDbRequestBuilder.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import java.util.ArrayList;
4 | import java.util.LinkedList;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | import org.springframework.data.simpledb.util.MapUtils;
9 |
10 | import com.amazonaws.services.simpledb.model.PutAttributesRequest;
11 | import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
12 |
13 | /**
14 | * Taking into account SimpleDb limitations, constructs requests that comply.
15 | */
16 | public final class SimpleDbRequestBuilder {
17 |
18 | private SimpleDbRequestBuilder() {
19 | // utility class
20 | }
21 |
22 | private static final int MAX_NUMBER_OF_ATTRIBUTES_PER_SIMPLE_DB_REQUEST = 256;
23 |
24 | public static List createPutAttributesRequests(String domain, String itemName,
25 | Map> rawAttributes) {
26 | List putAttributesRequests = new LinkedList();
27 |
28 | List>> attributeChunks = MapUtils.splitToChunksOfSize(rawAttributes,
29 | MAX_NUMBER_OF_ATTRIBUTES_PER_SIMPLE_DB_REQUEST);
30 |
31 | for(Map> chunk : attributeChunks) {
32 | PutAttributesRequest request = createPutAttributesRequest(domain, itemName, chunk);
33 | putAttributesRequests.add(request);
34 | }
35 |
36 | return putAttributesRequests;
37 | }
38 |
39 | private static PutAttributesRequest createPutAttributesRequest(String domain, String itemName,
40 | Map> chunk) {
41 | final PutAttributesRequest putRequest = new PutAttributesRequest();
42 | putRequest.setDomainName(domain);
43 | putRequest.setItemName(itemName);
44 |
45 | List simpleDbAttributes = toReplaceableAttributeList(chunk);
46 | putRequest.setAttributes(simpleDbAttributes);
47 | return putRequest;
48 | }
49 |
50 | private static List toReplaceableAttributeList(Map> attributes) {
51 | boolean replace = true;
52 | final List result = new ArrayList();
53 |
54 | for(final Map.Entry> entry : attributes.entrySet()) {
55 | replace = true;
56 | for (final String value : entry.getValue()) {
57 | result.add(new ReplaceableAttribute(entry.getKey(), value, replace));
58 | replace = false;
59 | }
60 | }
61 |
62 | return result;
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/domain/DomainManagementPolicy.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.domain;
2 |
3 | /**
4 | * Use DROP_CREATE - to drop the existing domain and create a new one UPDATE - to create the domain if not existing in
5 | * simpledb NON - if you prefer to create domains manually
6 | */
7 | public enum DomainManagementPolicy {
8 | DROP_CREATE, UPDATE, NONE
9 | }
10 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/AbstractFieldWrapper.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity;
2 |
3 | import java.io.Serializable;
4 | import java.lang.reflect.Field;
5 | import java.util.Map;
6 |
7 | import org.springframework.data.simpledb.reflection.ReflectionUtils;
8 | import org.springframework.util.Assert;
9 |
10 | public abstract class AbstractFieldWrapper {
11 |
12 | /* field metadata */
13 | private final Field field;
14 | private final EntityWrapper parentWrapper;
15 | private final boolean isNewParent;
16 |
17 | protected AbstractFieldWrapper(final Field field, final EntityWrapper parentWrapper,
18 | final boolean isNewParent) {
19 | Assert.notNull(field);
20 | Assert.notNull(parentWrapper);
21 |
22 | this.field = field;
23 | this.parentWrapper = parentWrapper;
24 |
25 | this.field.setAccessible(Boolean.TRUE);
26 |
27 | this.isNewParent = isNewParent;
28 | }
29 |
30 | protected boolean isNewParent() {
31 | return isNewParent;
32 | }
33 |
34 | public abstract Map serialize(String prefix);
35 |
36 | public abstract Object deserialize(final Map attributes);
37 |
38 | /**
39 | * Template method.
40 | *
41 | * Create an instance of the field and set it on the parentWrapper instance.
42 | */
43 | public abstract void createInstance();
44 |
45 | public Field getField() {
46 | return this.field;
47 | }
48 |
49 | @SuppressWarnings("unchecked")
50 | public Class getFieldType() {
51 | return (Class) getField().getType();
52 | }
53 |
54 | /**
55 | * Sets value via setter
56 | */
57 | public void setFieldValue(Object fieldValue) {
58 | ReflectionUtils.callSetter(parentWrapper.getItem(), field.getName(), fieldValue);
59 | }
60 |
61 | /**
62 | * Retrieves value via getter
63 | */
64 | public Object getFieldValue() {
65 | return ReflectionUtils.callGetter(parentWrapper.getItem(), field.getName());
66 | }
67 |
68 | public T getParentEntity() {
69 | return this.parentWrapper.getItem();
70 | }
71 |
72 | String getFieldName() {
73 | return field.getName();
74 | }
75 |
76 | EntityWrapper getParentWrapper() {
77 | return this.parentWrapper;
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/AbstractSimpleFieldWrapper.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity;
2 |
3 | import java.io.Serializable;
4 | import java.lang.reflect.Field;
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | import org.springframework.util.Assert;
9 |
10 | public abstract class AbstractSimpleFieldWrapper extends AbstractFieldWrapper {
11 |
12 | protected AbstractSimpleFieldWrapper(Field field, EntityWrapper parentWrapper, boolean isNewParent) {
13 | super(field, parentWrapper, isNewParent);
14 | }
15 |
16 | @Override
17 | public final Map serialize(String prefix) {
18 | final Map result = new HashMap();
19 | result.put(prefix.isEmpty() ? getFieldName() : prefix + "." + getFieldName(), serializeValue());
20 |
21 | return result;
22 | }
23 |
24 | public abstract String serializeValue();
25 |
26 | @Override
27 | public final Object deserialize(final Map attributes) {
28 | Assert.isTrue(attributes.size() == 1);
29 |
30 | String attributeValue = attributes.values().iterator().next();
31 | Assert.notNull(attributeValue);
32 |
33 | return deserializeValue(attributeValue);
34 | }
35 |
36 | public abstract Object deserializeValue(final String value);
37 |
38 | @Override
39 | public final void createInstance() {
40 | // Only applies to NestedEntities
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/FieldWrapperFactory.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity;
2 |
3 | import org.springframework.data.simpledb.reflection.FieldType;
4 | import org.springframework.data.simpledb.reflection.FieldTypeIdentifier;
5 |
6 | import java.io.Serializable;
7 | import java.lang.reflect.Field;
8 |
9 | public final class FieldWrapperFactory {
10 |
11 | private FieldWrapperFactory() {
12 | /* utility class */
13 | }
14 |
15 | public static AbstractFieldWrapper createFieldWrapper(final Field field,
16 | final EntityWrapper parent, final boolean isNewParent) {
17 | if(FieldTypeIdentifier.isOfType(field, FieldType.PRIMITIVE)) {
18 | return createSimpleFieldWrapper(field, parent, isNewParent);
19 | } else if(FieldTypeIdentifier.isOfType(field, FieldType.CORE_TYPE)) {
20 | return createSimpleFieldWrapper(field, parent, isNewParent);
21 | } else if(FieldTypeIdentifier.isOfType(field, FieldType.COLLECTION)) {
22 | return createCollectionFieldWrapper(field, parent, isNewParent);
23 | } else if(FieldTypeIdentifier.isOfType(field, FieldType.ARRAY)) {
24 | return createArrayFieldWrapper(field, parent, isNewParent);
25 | } else if(FieldTypeIdentifier.isOfType(field, FieldType.NESTED_ENTITY)) {
26 | return createNestedEntityFieldWrapper(field, parent, isNewParent);
27 | } else if(FieldTypeIdentifier.isOfType(field, FieldType.REFERENCE_ENTITY)) {
28 | return createReferenceEntityFieldWrapper(field, parent, isNewParent);
29 | } else if(FieldTypeIdentifier.isOfType(field, FieldType.MAP)) {
30 | return createMapFieldWrapper(field, parent, isNewParent);
31 | }
32 |
33 | return createObjectFieldWrapper(field, parent, isNewParent);
34 | }
35 |
36 | private static AbstractFieldWrapper createSimpleFieldWrapper(
37 | final Field field, final EntityWrapper parent, final boolean isNewParent) {
38 | return new SimpleFieldWrapper(field, parent, isNewParent);
39 | }
40 |
41 |
42 | private static AbstractFieldWrapper createArrayFieldWrapper(
43 | final Field field, final EntityWrapper parent, final boolean isNewParent) {
44 | return new JSONFieldWrapper(field, parent, isNewParent);
45 | }
46 |
47 | private static AbstractFieldWrapper createCollectionFieldWrapper(
48 | final Field field, final EntityWrapper parent, final boolean isNewParent) {
49 | return new JSONFieldWrapper(field, parent, isNewParent);
50 | }
51 |
52 | private static AbstractFieldWrapper createNestedEntityFieldWrapper(
53 | final Field field, final EntityWrapper parent, final boolean isNewParent) {
54 | return new NestedEntityFieldWrapper(field, parent, isNewParent);
55 | }
56 |
57 | private static AbstractFieldWrapper createReferenceEntityFieldWrapper(
58 | final Field field, final EntityWrapper parent, final boolean isNewParent) {
59 | return new ReferenceEntityFieldWrapper(field, parent, isNewParent);
60 | }
61 |
62 | private static AbstractFieldWrapper createMapFieldWrapper(final Field field,
63 | final EntityWrapper parent, final boolean isNewParent) {
64 | return new JSONFieldWrapper(field, parent, isNewParent);
65 | }
66 |
67 | private static AbstractFieldWrapper createObjectFieldWrapper(
68 | final Field field, final EntityWrapper parent, final boolean isNewParent) {
69 | return new JSONFieldWrapper(field, parent, isNewParent);
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/InstantiableFieldWrapper.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity;
2 |
3 | import java.io.Serializable;
4 | import java.lang.reflect.Field;
5 |
6 | import org.springframework.data.mapping.model.MappingException;
7 |
8 | public abstract class InstantiableFieldWrapper extends AbstractFieldWrapper {
9 |
10 | protected InstantiableFieldWrapper(Field field, EntityWrapper parent, final boolean isNewParent) {
11 | super(field, parent, isNewParent);
12 | }
13 |
14 | @Override
15 | public void createInstance() {
16 | Object newInstance;
17 | try {
18 | newInstance = getField().getType().newInstance();
19 | getField().set(getParentEntity(), newInstance);
20 | } catch(InstantiationException e) {
21 | throw new MappingException("Could not instantiate object", e);
22 | } catch(IllegalAccessException e) {
23 | throw new MappingException("Could not instantiate object", e);
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/JSONFieldWrapper.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity;
2 |
3 | import org.springframework.data.simpledb.core.entity.json.JsonMarshaller;
4 |
5 | import java.io.Serializable;
6 | import java.lang.reflect.Field;
7 |
8 | public class JSONFieldWrapper extends AbstractSimpleFieldWrapper {
9 |
10 | public JSONFieldWrapper(Field field, EntityWrapper parent, final boolean isNewParent) {
11 | super(field, parent, isNewParent);
12 | }
13 |
14 | @Override
15 | public String serializeValue() {
16 | if(getFieldValue() != null) {
17 | return JsonMarshaller.getInstance().marshall(getFieldValue());
18 | }
19 |
20 | return null;
21 | }
22 |
23 | @Override
24 | public Object deserializeValue(String value) {
25 | Object ret = null;
26 |
27 | if(value != null) {
28 | ret = JsonMarshaller.getInstance().unmarshall(value, getField().getType());
29 | }
30 |
31 | return ret;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/NestedEntityFieldWrapper.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity;
2 |
3 | import java.io.Serializable;
4 | import java.lang.reflect.Field;
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | import org.springframework.data.mapping.model.MappingException;
9 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformation;
10 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformationSupport;
11 |
12 | public class NestedEntityFieldWrapper extends AbstractFieldWrapper {
13 |
14 | private EntityWrapper wrappedNestedEntity;
15 |
16 | @SuppressWarnings({ "rawtypes", "unchecked" })
17 | public NestedEntityFieldWrapper(Field field, EntityWrapper parent, final boolean isNewParent) {
18 | super(field, parent, isNewParent);
19 |
20 | final SimpleDbEntityInformation entityMetadata = SimpleDbEntityInformationSupport.getMetadata(getField()
21 | .getType(), getParentWrapper().getDomain());
22 |
23 | /* if it was already created in createNewInstance */
24 | if(!isNewParent) {
25 | /* recursive call */
26 | wrappedNestedEntity = new EntityWrapper(entityMetadata, getFieldValue(), true);
27 | }
28 | }
29 |
30 | @Override
31 | public Map serialize(String prefix) {
32 | final Map result = new HashMap();
33 |
34 | final String nestedEntityFieldName = getFieldName();
35 | final String nestedEntityAttributePrefix = prefix.isEmpty() ? nestedEntityFieldName : prefix + "."
36 | + nestedEntityFieldName;
37 |
38 | /* recursive call */
39 | final Map serializedNestedEntity = wrappedNestedEntity.serialize(nestedEntityAttributePrefix);
40 |
41 | result.putAll(serializedNestedEntity);
42 |
43 | return result;
44 | }
45 |
46 | @Override
47 | public Object deserialize(Map values) {
48 | /* recursive call */
49 | if (isNewParent() && wrappedNestedEntity == null) {
50 | createInstance();
51 | }
52 | return wrappedNestedEntity.deserialize(values);
53 | }
54 |
55 | @Override
56 | public void createInstance() {
57 | /* instantiation is on demand during de-serialization */
58 | final SimpleDbEntityInformation entityMetadata = SimpleDbEntityInformationSupport.getMetadata(
59 | getFieldType(), getParentWrapper().getDomain());
60 | wrappedNestedEntity = new EntityWrapper(entityMetadata, true);
61 |
62 | try {
63 | getField().set(getParentEntity(), wrappedNestedEntity.getItem());
64 | } catch(IllegalArgumentException e) {
65 | throw new MappingException("Could not instantiate object", e);
66 | } catch(IllegalAccessException e) {
67 | throw new MappingException("Could not instantiate object", e);
68 | }
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/ReferenceEntityFieldWrapper.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity;
2 |
3 | import org.springframework.data.annotation.Reference;
4 | import org.springframework.data.simpledb.core.SimpleDbTemplate;
5 | import org.springframework.data.simpledb.reflection.FieldType;
6 | import org.springframework.data.simpledb.reflection.MetadataParser;
7 |
8 | import java.io.Serializable;
9 | import java.lang.reflect.Field;
10 |
11 | /**
12 | * Wraps {@link FieldType#REFERENCE_ENTITY} fields. A reference field is annotated with {@link Reference}
13 | */
14 | public class ReferenceEntityFieldWrapper extends AbstractSimpleFieldWrapper {
15 |
16 | public ReferenceEntityFieldWrapper(Field field, EntityWrapper parent, final boolean isNewParent) {
17 | super(field, parent, isNewParent);
18 | }
19 |
20 | @Override
21 | public String serializeValue() {
22 | final Object fieldValue = getFieldValue();
23 |
24 | return MetadataParser.getItemName(fieldValue);
25 | }
26 |
27 | /**
28 | * Deserialization for nested reference fields is handled by {@link SimpleDbTemplate}
29 | */
30 | @Override
31 | public Object deserializeValue(String value) {
32 | return null;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/SimpleFieldWrapper.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity;
2 |
3 | import org.springframework.data.mapping.model.MappingException;
4 | import org.springframework.data.simpledb.attributeutil.SimpleDBAttributeConverter;
5 |
6 | import java.io.Serializable;
7 | import java.lang.reflect.Field;
8 | import java.text.ParseException;
9 |
10 | public class SimpleFieldWrapper extends AbstractSimpleFieldWrapper {
11 |
12 | public SimpleFieldWrapper(Field field, EntityWrapper parent, final boolean isNewParent) {
13 | super(field, parent, isNewParent);
14 | }
15 |
16 | @Override
17 | public String serializeValue() {
18 | return SimpleDBAttributeConverter.encode(this.getFieldValue());
19 | }
20 |
21 | @Override
22 | public Object deserializeValue(String value) {
23 | try {
24 | return SimpleDBAttributeConverter.decodeToFieldOfType(value, getField().getType());
25 | } catch(IllegalArgumentException e) {
26 | throw new MappingException("Could not map attributes", e);
27 | } catch(ParseException e) {
28 | throw new MappingException("Could not map attributes", e);
29 | }
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/json/JsonMarshaller.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity.json;
2 |
3 | import java.io.IOException;
4 |
5 | import org.codehaus.jackson.JsonFactory;
6 | import org.codehaus.jackson.annotate.JsonAutoDetect;
7 | import org.codehaus.jackson.annotate.JsonMethod;
8 | import org.codehaus.jackson.map.ObjectMapper;
9 | import org.codehaus.jackson.mrbean.MrBeanModule;
10 | import org.springframework.data.mapping.model.MappingException;
11 | import org.springframework.util.Assert;
12 |
13 | /**
14 | * Marshall and unmarshall objects, collections and map field wrappers
15 | */
16 | public final class JsonMarshaller {
17 |
18 | static class JsonMarshallerHolder {
19 |
20 | private static JsonMarshaller instance = new JsonMarshaller();
21 | }
22 |
23 | private ObjectMapper jsonMapper;
24 |
25 | private JsonMarshaller() {
26 | JsonFactory factory = new JsonFactory();
27 | jsonMapper = new ObjectMapper(factory);
28 | jsonMapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.NON_FINAL, "@class");
29 | JsonUnknownPropertyHandler jsonUnknownPropertyHandler = new JsonUnknownPropertyHandler();
30 | jsonMapper.getDeserializationConfig().addHandler(jsonUnknownPropertyHandler);
31 | jsonMapper.registerModule(new MrBeanModule());
32 | }
33 |
34 | public static JsonMarshaller getInstance() {
35 | return JsonMarshallerHolder.instance;
36 | }
37 |
38 | static JsonMarshaller createNew(){
39 | return new JsonMarshaller();
40 | }
41 |
42 | public T unmarshall(String jsonString, Class> objectType) {
43 | Assert.notNull(jsonString);
44 | try {
45 | return (T) jsonMapper.readValue(jsonString, objectType);
46 | } catch(IOException e) {
47 | throw new MappingException("Could not unmarshall object : " + jsonString, e);
48 | }
49 | }
50 |
51 | public String marshall(T input) {
52 | Assert.notNull(input);
53 | jsonMapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
54 | jsonMapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.NON_FINAL, "@class");
55 | try {
56 | return jsonMapper.writeValueAsString(input);
57 | } catch(Exception e) {
58 | throw new MappingException(e.getMessage(), e);
59 | }
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/entity/json/JsonUnknownPropertyHandler.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity.json;
2 |
3 | import org.codehaus.jackson.JsonParser;
4 | import org.codehaus.jackson.map.DeserializationContext;
5 | import org.codehaus.jackson.map.DeserializationProblemHandler;
6 | import org.codehaus.jackson.map.JsonDeserializer;
7 | import org.slf4j.Logger;
8 | import org.slf4j.LoggerFactory;
9 |
10 | import java.io.IOException;
11 |
12 | public class JsonUnknownPropertyHandler extends DeserializationProblemHandler {
13 |
14 | private static final Logger LOG = LoggerFactory.getLogger(JsonUnknownPropertyHandler.class);
15 |
16 | @Override
17 | public boolean handleUnknownProperty(DeserializationContext ctxt, JsonDeserializer> deserializer,
18 | Object beanOrClass, String propertyName) throws IOException {
19 | JsonParser jsonParser = ctxt.getParser();
20 | LOG.warn("Unknown Json property: " + propertyName);
21 | jsonParser.skipChildren();
22 |
23 | return true;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/exception/InvalidSimpleDBQueryException.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.exception;
2 |
3 | import org.springframework.dao.UncategorizedDataAccessException;
4 |
5 | public class InvalidSimpleDBQueryException extends UncategorizedDataAccessException{
6 |
7 | private static final long serialVersionUID = 1L;
8 |
9 | public InvalidSimpleDBQueryException(String message, Throwable e) {
10 | super(message, e);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/exception/SimpleDbExceptionTranslator.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.exception;
2 |
3 | import org.springframework.dao.*;
4 | import org.springframework.dao.support.PersistenceExceptionTranslator;
5 |
6 | import com.amazonaws.AmazonClientException;
7 | import com.amazonaws.AmazonServiceException;
8 | import com.amazonaws.services.cloudwatch.model.ResourceNotFoundException;
9 | import com.amazonaws.services.simpledb.model.*;
10 |
11 | /**
12 | * Simple {@link PersistenceExceptionTranslator} for SimpleDB. Translated the runtime exception to an appropriate
13 | * {@code org.springframework.dao} exception
14 | *
15 | */
16 | public final class SimpleDbExceptionTranslator implements PersistenceExceptionTranslator {
17 |
18 | private static SimpleDbExceptionTranslator instance;
19 |
20 | private SimpleDbExceptionTranslator() { }
21 |
22 | public static synchronized SimpleDbExceptionTranslator getTranslatorInstance() {
23 | if(instance == null) {
24 | instance = new SimpleDbExceptionTranslator();
25 | }
26 |
27 | return instance;
28 | }
29 |
30 | public RuntimeException translateAmazonClientException(AmazonClientException e) {
31 | RuntimeException translatedException = getTranslatorInstance().translateExceptionIfPossible(e);
32 | if(translatedException == null) {
33 | translatedException = e;
34 | }
35 |
36 | return translatedException;
37 | }
38 |
39 | @Override
40 | public DataAccessException translateExceptionIfPossible(RuntimeException e) {
41 | final String errorMessage = e.getLocalizedMessage();
42 |
43 | if(e instanceof DuplicateItemNameException) {
44 | return new DuplicateKeyException(errorMessage, e);
45 | }
46 |
47 | // The specified attribute does not exist.
48 | if(e instanceof AttributeDoesNotExistException) {
49 | return new EmptyResultDataAccessException(errorMessage, -1);
50 | }
51 |
52 | if(e instanceof ResourceNotFoundException) {
53 | return new DataRetrievalFailureException(errorMessage, e);
54 | }
55 |
56 |
57 | if(e instanceof InvalidParameterValueException) {
58 | return new InvalidDataAccessResourceUsageException(errorMessage, e);
59 | }
60 |
61 | if(e instanceof NoSuchDomainException) {
62 | return new EmptyResultDataAccessException(errorMessage, -1);
63 | }
64 |
65 | if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) {
66 | return new DataIntegrityViolationException(errorMessage, e);
67 | }
68 |
69 | if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException)
70 | || (e instanceof MissingParameterException) ) {
71 | return new InvalidDataAccessApiUsageException(errorMessage, e);
72 | }
73 |
74 | if(e instanceof AmazonServiceException) {
75 | return new DataAccessResourceFailureException(errorMessage, e);
76 | }
77 |
78 | // Amazon Internal Exception
79 | if(e instanceof AmazonClientException) {
80 | return new UncategorizedSpringDaoException(errorMessage, e);
81 | }
82 |
83 | // this line means that spring-data exceptions will not be translated to DataAccessException, being interpreted
84 | // as they are from the SimpleDB Template
85 | return null;
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/exception/UncategorizedSpringDaoException.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.exception;
2 |
3 | import org.springframework.dao.UncategorizedDataAccessException;
4 |
5 | public class UncategorizedSpringDaoException extends UncategorizedDataAccessException {
6 |
7 | private static final long serialVersionUID = 1L;
8 |
9 | public UncategorizedSpringDaoException(String msg, Throwable cause) {
10 | super(msg, cause);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/PartTreeConverter.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.springframework.data.mapping.model.MappingException;
4 | import org.springframework.data.repository.query.parser.Part;
5 | import org.springframework.data.repository.query.parser.PartTree;
6 | import org.springframework.data.repository.query.parser.PartTree.OrPart;
7 | import org.springframework.data.simpledb.annotation.Query;
8 | import org.springframework.data.simpledb.util.StringUtil;
9 |
10 | import java.util.Iterator;
11 |
12 | public final class PartTreeConverter {
13 |
14 | private PartTreeConverter() {
15 | /* utility class */
16 | }
17 |
18 | /**
19 | * Convert a {@link PartTree} into a where query alike to the one present in the
20 | * {@link Query}'s where property.
21 | */
22 | public static String toIndexedQuery(final PartTree tree) {
23 | final StringBuilder result = new StringBuilder();
24 |
25 | final Iterator orIt = tree.iterator();
26 | while(orIt.hasNext()) {
27 |
28 | final OrPart orPart = orIt.next();
29 |
30 | final Iterator partIt = orPart.iterator();
31 | while(partIt.hasNext()) {
32 | final Part part = partIt.next();
33 |
34 | result.append(" " + part.getProperty().getSegment() + " ");
35 | result.append(convertOperator(part.getType()));
36 |
37 | if(partIt.hasNext()) {
38 | result.append(" AND ");
39 | }
40 | }
41 |
42 | if(orIt.hasNext()) {
43 | result.append(" OR ");
44 | }
45 | }
46 |
47 | return StringUtil.removeExtraSpaces(result.toString());
48 | }
49 |
50 | private static String convertOperator(final Part.Type type) {
51 | String result = "";
52 |
53 | switch(type) {
54 | case SIMPLE_PROPERTY: {
55 | result = " = ? ";
56 | break;
57 | }
58 |
59 | case NEGATING_SIMPLE_PROPERTY: {
60 | result = " != ? ";
61 | break;
62 | }
63 |
64 | case GREATER_THAN: {
65 | result = " > ? ";
66 | break;
67 | }
68 |
69 | case GREATER_THAN_EQUAL: {
70 | result = " >= ? ";
71 | break;
72 | }
73 |
74 | case LESS_THAN: {
75 | result = " < ? ";
76 | break;
77 | }
78 |
79 | case LESS_THAN_EQUAL: {
80 | result = " <= ? ";
81 | break;
82 | }
83 |
84 | case LIKE: {
85 | result = " LIKE ? ";
86 | break;
87 | }
88 |
89 | case NOT_LIKE: {
90 | result = " NOT LIKE ? ";
91 | break;
92 | }
93 |
94 | case BETWEEN: {
95 | result = " BETWEEN ? and ? ";
96 | break;
97 | }
98 |
99 | case IS_NOT_NULL: {
100 | result = " IS NOT NULL ";
101 | break;
102 | }
103 |
104 | case IS_NULL: {
105 | result = " IS NULL ";
106 | break;
107 | }
108 |
109 | case IN: {
110 | result = " IN ? ";
111 | break;
112 | }
113 |
114 | default: {
115 | throw new MappingException("No matching simpleDB operator for " + type);
116 | }
117 | }
118 |
119 | return result;
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/SdbItemQuery.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.domain.Page;
6 | import org.springframework.data.domain.Pageable;
7 | import org.springframework.data.simpledb.core.SimpleDbOperations;
8 |
9 | /**
10 | * Convenience type for access to finder methods of enclosing
11 | * {@link SimpleDbOperations} object.
12 | *
13 | * @author Sayantam Dey
14 | *
15 | */
16 | public class SdbItemQuery {
17 |
18 | private final SimpleDbOperations simpleDbOps;
19 | private final String query;
20 | private final Class entityClass;
21 | private final boolean defaultConsistentRead;
22 |
23 | public SdbItemQuery(Class entityClass, String query, SimpleDbOperations simpleDbOps) {
24 | this.simpleDbOps = simpleDbOps;
25 | this.query = query;
26 | this.entityClass = entityClass;
27 | this.defaultConsistentRead = simpleDbOps.getSimpleDb().isConsistentRead();
28 | }
29 |
30 | public List find() {
31 | return find(defaultConsistentRead);
32 | }
33 |
34 | public List find(boolean consistentRead) {
35 | return simpleDbOps.find(entityClass, query, consistentRead);
36 | }
37 |
38 | public Page executePagedQuery(Pageable pageable) {
39 | return executePagedQuery(pageable, defaultConsistentRead);
40 | }
41 |
42 | public Page executePagedQuery(Pageable pageable, boolean consistentRead) {
43 | return simpleDbOps.executePagedQuery(entityClass, query, pageable, consistentRead);
44 | }
45 |
46 | public long count() {
47 | return count(defaultConsistentRead);
48 | }
49 |
50 | public long count(boolean consistentRead) {
51 | return simpleDbOps.count(query, entityClass, consistentRead);
52 | }
53 |
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/SimpleDbPartTreeQueryMethod.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.springframework.data.repository.core.RepositoryMetadata;
4 | import org.springframework.data.repository.query.parser.PartTree;
5 | import org.springframework.data.simpledb.core.SimpleDbDomain;
6 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformation;
7 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformationSupport;
8 |
9 | import java.lang.reflect.Method;
10 |
11 | /**
12 | *
13 | * An extension of {@link SimpleDbQueryMethod} which determines the whereParameters from the method name.
14 | * This is a preliminary implementation of the named query!
15 | *
16 | */
17 | public class SimpleDbPartTreeQueryMethod extends SimpleDbQueryMethod {
18 |
19 | private final String whereExpression;
20 |
21 | public SimpleDbPartTreeQueryMethod(Method method, RepositoryMetadata metadata, SimpleDbDomain simpleDbDomain) {
22 | super(method, metadata, simpleDbDomain);
23 |
24 | final String domainName = simpleDbDomain.getDomain(metadata.getDomainType());
25 | final SimpleDbEntityInformation, ?> entityInformation = SimpleDbEntityInformationSupport.getMetadata(metadata.getDomainType(), domainName);
26 |
27 | whereExpression = PartTreeConverter.toIndexedQuery(new PartTree(method.getName(), entityInformation.getJavaType()));
28 | }
29 |
30 | @Override
31 | protected String getWhereParameters() {
32 | return whereExpression;
33 | }
34 |
35 | @Override
36 | protected String[] getSelectParameters() {
37 | return new String[] { "" };
38 | }
39 |
40 | @Override
41 | protected String getValueParameters() {
42 | return "";
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/SimpleDbQueryLookupStrategy.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.springframework.data.repository.core.NamedQueries;
4 | import org.springframework.data.repository.core.RepositoryMetadata;
5 | import org.springframework.data.repository.query.QueryLookupStrategy;
6 | import org.springframework.data.repository.query.RepositoryQuery;
7 | import org.springframework.data.simpledb.annotation.Query;
8 | import org.springframework.data.simpledb.core.SimpleDbOperations;
9 |
10 | import java.lang.reflect.Method;
11 |
12 | /**
13 | * Query lookup strategy to execute custom interface query methods
14 | * Multiple query lookup strategies can be created and combined here:
15 | *
16 | * create query from method name
17 | * from custom query annotations
18 | *
19 | *
20 | * {@link QueryLookupStrategy} that tries to detect a declared query declared via simple db custom {@link Query}
21 | * annotation .
22 | */
23 | public final class SimpleDbQueryLookupStrategy implements QueryLookupStrategy {
24 |
25 | private SimpleDbOperations simpleDbOperations;
26 |
27 | public SimpleDbQueryLookupStrategy(SimpleDbOperations simpleDbOperations) {
28 | this.simpleDbOperations = simpleDbOperations;
29 | }
30 |
31 | @Override
32 | public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) {
33 | SimpleDbQueryMethod queryMethod;
34 |
35 | if(SimpleDbQueryMethod.isAnnotatedQuery(method)) {
36 | queryMethod = new SimpleDbQueryMethod(method, metadata, simpleDbOperations.getSimpleDb()
37 | .getSimpleDbDomain());
38 | } else {
39 | queryMethod = new SimpleDbPartTreeQueryMethod(method, metadata, simpleDbOperations.getSimpleDb()
40 | .getSimpleDbDomain());
41 | }
42 |
43 | return SimpleDbRepositoryQuery.fromQueryAnnotation(queryMethod, simpleDbOperations);
44 | }
45 |
46 | public static QueryLookupStrategy create(SimpleDbOperations simpleDbOperations, QueryLookupStrategy.Key key) {
47 | // TODO check in Spring data core key switching and their semantics (look in spring-data-jpa)
48 | return new SimpleDbQueryLookupStrategy(simpleDbOperations);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/SimpleDbQueryRunner.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.domain.Page;
6 | import org.springframework.data.domain.Pageable;
7 | import org.springframework.data.simpledb.core.SimpleDbOperations;
8 | import org.springframework.util.Assert;
9 |
10 | /**
11 | * This class is used to get information about query field names and execute queries
12 | */
13 | public class SimpleDbQueryRunner {
14 |
15 | private final SimpleDbOperations simpledbOperations;
16 | private final Class> domainClass;
17 | private final String query;
18 | private Pageable pageable;
19 |
20 | public SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class> domainClass, String query) {
21 | this.simpledbOperations = simpledbOperations;
22 | this.domainClass = domainClass;
23 | this.query = query;
24 | }
25 |
26 | public SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class> domainClass, String query,
27 | Pageable pageable) {
28 | this(simpledbOperations, domainClass, query);
29 |
30 | Assert.notNull(pageable);
31 | Assert.isTrue(pageable.getPageNumber() >= 0);
32 | Assert.isTrue(pageable.getPageSize() > 0);
33 |
34 | this.pageable = pageable;
35 | }
36 |
37 | public List> executeQuery() {
38 | return simpledbOperations.find(domainClass, query);
39 | }
40 |
41 | public Object executeSingleResultQuery() {
42 | List> returnListFromDb = executeQuery();
43 |
44 | return getSingleResult(returnListFromDb);
45 | }
46 |
47 | Object getSingleResult(List> returnListFromDb) {
48 | Assert.isTrue(returnListFromDb.size() <= 1,
49 | "Select statement should return only one entity from database, returned elements size="
50 | + returnListFromDb.size() + ", for Query=" + query);
51 |
52 | return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null;
53 | }
54 |
55 | public long executeCount() {
56 | return simpledbOperations.count(query, domainClass);
57 | }
58 |
59 | public List getRequestedQueryFieldNames() {
60 | return QueryUtils.getQueryPartialFieldNames(query);
61 | }
62 |
63 | public String getSingleQueryFieldName() {
64 | List queryFieldNames = getRequestedQueryFieldNames();
65 | Assert.isTrue(queryFieldNames.size() == 1);
66 | return queryFieldNames.get(0);
67 | }
68 |
69 | public Page> executePagedQuery() {
70 | return simpledbOperations.executePagedQuery(domainClass, query, pageable);
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/SimpleDbResultConverter.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.springframework.data.simpledb.reflection.ReflectionUtils;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * This class convert the list of entities retrieved from db to the returned type needed by the query method
9 | */
10 | public final class SimpleDbResultConverter {
11 |
12 | private SimpleDbResultConverter() {
13 | /* utility class */
14 | }
15 |
16 | public static List filterNamedAttributesAsList(List> domainObjects, String attributeName) {
17 | List ret = new ArrayList();
18 | for(Object object : domainObjects) {
19 | ret.add(ReflectionUtils.callGetter(object, attributeName));
20 | }
21 | return ret;
22 | }
23 |
24 | public static Set filterNamedAttributesAsSet(List> domainObjects, String attributeName) {
25 | Set ret = new LinkedHashSet();
26 | for(Object object : domainObjects) {
27 | ret.add(ReflectionUtils.callGetter(object, attributeName));
28 | }
29 | return ret;
30 | }
31 |
32 | public static List> toListOfListOfObject(List> entityList, List requestedQueryFieldNames) {
33 | if(entityList.size() > 0) {
34 | List> rows = new ArrayList>();
35 | for(Object entity : entityList) {
36 | List cols = new ArrayList();
37 | for(String fieldName : requestedQueryFieldNames) {
38 | Object value = ReflectionUtils.callGetter(entity, fieldName);
39 | cols.add(value);
40 | }
41 | rows.add(cols);
42 | }
43 | return rows;
44 | } else {
45 | return Collections.emptyList();
46 | }
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/executions/AbstractSimpleDbQueryExecution.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query.executions;
2 |
3 | import org.springframework.data.domain.Pageable;
4 | import org.springframework.data.simpledb.core.SimpleDbOperations;
5 | import org.springframework.data.simpledb.query.QueryUtils;
6 | import org.springframework.data.simpledb.query.SimpleDbQueryMethod;
7 | import org.springframework.data.simpledb.query.SimpleDbQueryRunner;
8 | import org.springframework.util.Assert;
9 |
10 | /**
11 | * Set of classes to contain query execution strategies. Depending (mostly) on the return type of a
12 | * {@link org.springframework.data.repository.query.QueryMethod}
13 | */
14 | public abstract class AbstractSimpleDbQueryExecution {
15 |
16 | private final SimpleDbOperations simpledbOperations;
17 |
18 | public AbstractSimpleDbQueryExecution(SimpleDbOperations simpleDbOperations) {
19 | this.simpledbOperations = simpleDbOperations;
20 | }
21 |
22 | public Object execute(SimpleDbQueryMethod queryMethod, Object[] parameterValues) {
23 | Assert.notNull(queryMethod);
24 | Assert.notNull(parameterValues);
25 |
26 | // Demeter's Law
27 | QueryUtils.validateBindParametersCount(queryMethod.getParameters(), parameterValues);
28 | QueryUtils.validateBindParametersTypes(queryMethod.getParameters());
29 |
30 | Class> domainClass = queryMethod.getDomainClazz();
31 | String query = QueryUtils.bindQueryParameters(queryMethod, parameterValues);
32 |
33 | SimpleDbQueryRunner queryRunner;
34 |
35 | if(queryMethod.isPagedQuery()) {
36 | final Pageable pageable = getPageableParamValue(parameterValues);
37 |
38 | queryRunner = new SimpleDbQueryRunner(simpledbOperations, domainClass, query, pageable);
39 | } else {
40 | queryRunner = new SimpleDbQueryRunner(simpledbOperations, domainClass, query);
41 | }
42 |
43 | return doExecute(queryMethod, queryRunner);
44 | }
45 |
46 | private Pageable getPageableParamValue(Object[] values) {
47 | Pageable pageable = null;
48 |
49 | for(Object value : values) {
50 | if(Pageable.class.isAssignableFrom(value.getClass())) {
51 | pageable = (Pageable) value;
52 | }
53 | }
54 |
55 | return pageable;
56 | }
57 |
58 | protected abstract Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner);
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/executions/PagedResultExecution.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query.executions;
2 |
3 | import org.springframework.data.domain.Page;
4 | import org.springframework.data.simpledb.core.SimpleDbOperations;
5 | import org.springframework.data.simpledb.query.SimpleDbQueryMethod;
6 | import org.springframework.data.simpledb.query.SimpleDbQueryRunner;
7 |
8 | import java.util.List;
9 |
10 | /**
11 | * Execute a paged query. A paged query may have as a result a {@link Page} or a {@link List}, depending on the method's
12 | * signature in the repository.
13 | */
14 | public class PagedResultExecution extends AbstractSimpleDbQueryExecution {
15 |
16 | public PagedResultExecution(SimpleDbOperations simpleDbOperations) {
17 | super(simpleDbOperations);
18 | }
19 |
20 | @Override
21 | protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) {
22 | final Page> pagedResult = queryRunner.executePagedQuery();
23 |
24 | if(queryMethod.isPageQuery()) {
25 | return pagedResult;
26 | }
27 |
28 | return pagedResult.getContent();
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/executions/SingleResultExecution.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query.executions;
2 |
3 | import org.springframework.data.simpledb.core.SimpleDbOperations;
4 | import org.springframework.data.simpledb.query.QueryUtils;
5 | import org.springframework.data.simpledb.query.SimpleDbQueryMethod;
6 | import org.springframework.data.simpledb.query.SimpleDbQueryRunner;
7 | import org.springframework.data.simpledb.reflection.ReflectionUtils;
8 | import org.springframework.util.Assert;
9 |
10 | public class SingleResultExecution extends AbstractSimpleDbQueryExecution {
11 |
12 | /**
13 | * The following single result types can be requested:
14 | *
15 | * SINGLE_FIELD_RESULT - Any Core Type or Primitive Field as returned type for query:
16 | *
17 | *
18 | * {@code SELECT field FROM entity}
19 | *
20 | *
21 | * COUNT_RESULT - Boxed Long or Primitive long Field as returned type for query:
22 | *
23 | *
24 | * {@code SELECT count(*) FROM entity}
25 | *
26 | *
27 | * ENTITY_RESULT - Entity as returned type for query:
28 | *
29 | *
30 | * {@code SELECT * FROM entity where itemName()="1"}
31 | *
32 | *
33 | *
34 | */
35 | public enum SingleResultType {
36 |
37 | SINGLE_FIELD_RESULT, COUNT_RESULT, ENTITY_RESULT;
38 | }
39 |
40 | public SingleResultExecution(SimpleDbOperations simpleDbOperations) {
41 | super(simpleDbOperations);
42 | }
43 |
44 | @Override
45 | protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) {
46 |
47 | SingleResultType resultType = detectResultType(queryMethod);
48 |
49 | switch(resultType) {
50 | case COUNT_RESULT: {
51 | Class> methodReturnedType = queryMethod.getReturnedObjectType();
52 | boolean isLongClass = Long.class.isAssignableFrom(methodReturnedType);
53 | boolean islongClass = long.class.isAssignableFrom(methodReturnedType);
54 | Assert.isTrue(isLongClass || islongClass,
55 | "Method declared in repository should return type long or Long");
56 | return queryRunner.executeCount();
57 | }
58 |
59 | case SINGLE_FIELD_RESULT: {
60 | String attributeName = queryRunner.getSingleQueryFieldName();
61 | Object returnedEntity = queryRunner.executeSingleResultQuery();
62 | return ReflectionUtils.callGetter(returnedEntity, attributeName);
63 | }
64 |
65 | case ENTITY_RESULT: {
66 | return queryRunner.executeSingleResultQuery();
67 | }
68 |
69 | default:
70 | throw new IllegalArgumentException("Unrecognized Single result type");
71 | }
72 | }
73 |
74 | private SingleResultType detectResultType(SimpleDbQueryMethod method) {
75 | String query = method.getAnnotatedQuery();
76 |
77 | if(QueryUtils.isCountQuery(query)) {
78 | return SingleResultType.COUNT_RESULT;
79 | } else if(method.isQueryForEntity()) {
80 | return SingleResultType.ENTITY_RESULT;
81 | } else if(QueryUtils.getQueryPartialFieldNames(query).size() == 1) {
82 | return SingleResultType.SINGLE_FIELD_RESULT;
83 | } else {
84 | throw new IllegalArgumentException("Wrong return type for query: " + query);
85 | }
86 | }
87 | }
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/parser/QueryParserUtils.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query.parser;
2 |
3 | import org.springframework.data.simpledb.annotation.Query;
4 | import org.springframework.util.StringUtils;
5 |
6 | /**
7 | * Acts as a Parser for Building the Custom Query based on the given {@link Query} parameters
8 | *
9 | */
10 | public final class QueryParserUtils {
11 |
12 | private QueryParserUtils() {
13 | }
14 |
15 | public static String buildQueryFromQueryParameters(String valueParameter, String[] rawSelectParameters,
16 | String rawWhereParameters, String domainName) {
17 |
18 | if(StringUtils.hasText(valueParameter)) {
19 | return valueParameter;
20 | }
21 |
22 | StringBuilder stringBuilder = new StringBuilder();
23 |
24 | appendSelectClause(stringBuilder, rawSelectParameters);
25 | appendFromClause(stringBuilder, domainName);
26 | appendWhereClauseIfPresent(stringBuilder, rawWhereParameters);
27 |
28 | return stringBuilder.toString();
29 | }
30 |
31 | public static String createQueryClause(String clause, String[] rawParameters, String delimiter) {
32 | StringBuilder query = new StringBuilder(clause);
33 | int idx = 1;
34 |
35 | for(String rawParameter : rawParameters) {
36 | query.append(rawParameter);
37 |
38 | if(idx++ != rawParameters.length) {
39 | query.append(delimiter);
40 | }
41 | }
42 |
43 | return query.toString();
44 | }
45 |
46 | private static void appendWhereClauseIfPresent(StringBuilder stringBuilder, String rawWhereParameters) {
47 | if(StringUtils.hasText(rawWhereParameters)) {
48 | stringBuilder.append(" where " + rawWhereParameters);
49 | }
50 | }
51 |
52 | private static void appendFromClause(StringBuilder stringBuilder, String domainName) {
53 | stringBuilder.append(" from `" + domainName + "`");
54 | }
55 |
56 | private static void appendSelectClause(StringBuilder stringBuilder, String[] rawSelectParameters) {
57 | if(StringUtils.hasText(rawSelectParameters[0])) {
58 | stringBuilder.append(createQueryClause("select ", rawSelectParameters, ", "));
59 | } else {
60 | stringBuilder.append("select *");
61 | }
62 | }
63 |
64 | }
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/reflection/FieldType.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.reflection;
2 |
3 | import java.lang.reflect.Field;
4 | import java.util.Collection;
5 | import java.util.Map;
6 | import java.util.Set;
7 |
8 | import org.springframework.data.annotation.Id;
9 | import org.springframework.data.simpledb.annotation.Attributes;
10 | import org.springframework.util.Assert;
11 |
12 | public enum FieldType {
13 |
14 | ID {
15 |
16 | private static final String FIELD_NAME_DEFAULT_ID = "id";
17 |
18 | @Override
19 | boolean isOfType(Field field) {
20 | Assert.notNull(field);
21 | return field.getName().equals(FIELD_NAME_DEFAULT_ID) || field.getAnnotation(Id.class) != null;
22 | }
23 | },
24 |
25 | ATTRIBUTES {
26 |
27 | @Override
28 | boolean isOfType(Field field) {
29 | Assert.notNull(field);
30 | return field.getAnnotation(Attributes.class) != null;
31 | }
32 | },
33 |
34 | PRIMITIVE {
35 |
36 | @Override
37 | boolean isOfType(Field field) {
38 | Assert.notNull(field);
39 | return SupportedCoreTypes.PRIMITIVE_TYPES.isOfType(field.getType());
40 | }
41 | },
42 |
43 | CORE_TYPE {
44 |
45 | @Override
46 | boolean isOfType(Field field) {
47 | final boolean isCoreType = SupportedCoreTypes.CORE_TYPES.isOfType(field.getType());
48 |
49 | return isCoreType;
50 | }
51 | },
52 |
53 | COLLECTION {
54 |
55 | @Override
56 | boolean isOfType(Field field) {
57 | Assert.notNull(field);
58 | return Collection.class.isAssignableFrom(field.getType());
59 | }
60 | },
61 |
62 | ARRAY {
63 |
64 | @Override
65 | boolean isOfType(Field field) {
66 | final boolean isArrayType = SupportedCoreTypes.ARRAYS.isOfType(field.getType());
67 |
68 | return isArrayType;
69 | }
70 | },
71 |
72 | MAP {
73 |
74 | @Override
75 | boolean isOfType(Field field) {
76 | Assert.notNull(field);
77 | return Map.class.isAssignableFrom(field.getType());
78 | }
79 | },
80 |
81 | OBJECT {
82 |
83 | @Override
84 | boolean isOfType(Field field) {
85 | Assert.notNull(field);
86 | return field.getType().equals(Object.class);
87 | }
88 | },
89 |
90 | NESTED_ENTITY {
91 |
92 | @Override
93 | boolean isOfType(Field field) {
94 | Assert.notNull(field);
95 | return !(field.getType().equals(Class.class) || field.getType().isEnum() ||
96 | isOfType(field, ID, ATTRIBUTES, PRIMITIVE, CORE_TYPE,
97 | COLLECTION, ARRAY, MAP, OBJECT, REFERENCE_ENTITY));
98 | }
99 | },
100 |
101 | REFERENCE_ENTITY {
102 |
103 | @Override
104 | boolean isOfType(Field field) {
105 | Assert.notNull(field);
106 |
107 | return ReflectionUtils.isReference(field);
108 | }
109 | };
110 |
111 | abstract boolean isOfType(Field field);
112 |
113 | static boolean isOfType(final Class> fieldType, final Set> supportedTypes) {
114 | Assert.notNull(fieldType);
115 |
116 | for(Class> clazz : supportedTypes) {
117 | if(fieldType == clazz || clazz.isAssignableFrom(fieldType)) {
118 | return true;
119 | }
120 | }
121 |
122 | return false;
123 |
124 | }
125 |
126 | static boolean isOfType(final Field field, final FieldType... fieldTypes) {
127 | for(final FieldType fieldType : fieldTypes) {
128 | if(fieldType.isOfType(field)) {
129 | return true;
130 | }
131 | }
132 |
133 | return false;
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/reflection/FieldTypeIdentifier.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.reflection;
2 |
3 | import java.lang.reflect.Field;
4 |
5 | public class FieldTypeIdentifier {
6 |
7 | protected FieldTypeIdentifier() {
8 | /* utility class */
9 | }
10 |
11 | public static boolean isOfType(final Field field, FieldType... fieldTypes) {
12 | for(final FieldType fieldType : fieldTypes) {
13 | if(fieldType.isOfType(field)) {
14 | return true;
15 | }
16 | }
17 |
18 | return false;
19 | }
20 |
21 | public static FieldType getFieldType(final Field field) {
22 | if(FieldType.ID.isOfType(field)) {
23 | return FieldType.ID;
24 | } else if(FieldType.ATTRIBUTES.isOfType(field)) {
25 | return FieldType.ATTRIBUTES;
26 | } else if(FieldType.PRIMITIVE.isOfType(field)) {
27 | return FieldType.PRIMITIVE;
28 | } else if(FieldType.CORE_TYPE.isOfType(field)) {
29 | return FieldType.CORE_TYPE;
30 | } else if(FieldType.COLLECTION.isOfType(field)) {
31 | return FieldType.COLLECTION;
32 | } else if(FieldType.ARRAY.isOfType(field)) {
33 | return FieldType.ARRAY;
34 | } else if(FieldType.MAP.isOfType(field)) {
35 | return FieldType.MAP;
36 | } else if(FieldType.NESTED_ENTITY.isOfType(field)) {
37 | return FieldType.NESTED_ENTITY;
38 | } else if(FieldType.REFERENCE_ENTITY.isOfType(field)) {
39 | return FieldType.REFERENCE_ENTITY;
40 | }
41 |
42 | return FieldType.OBJECT;
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/reflection/SupportedCoreTypes.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.reflection;
2 |
3 | import org.springframework.util.Assert;
4 |
5 | import java.util.Date;
6 | import java.util.HashSet;
7 | import java.util.Set;
8 |
9 | public enum SupportedCoreTypes {
10 |
11 | PRIMITIVE_TYPES {
12 |
13 | @Override
14 | public boolean isOfType(Class> clazz) {
15 | return clazz.isPrimitive();
16 | }
17 | },
18 | CORE_TYPES {
19 |
20 | @Override
21 | public boolean isOfType(Class> clazz) {
22 | return isOfType(clazz, SUPPORTED_CORE_TYPES);
23 | }
24 | },
25 | ARRAYS {
26 |
27 | @Override
28 | public boolean isOfType(Class> clazz) {
29 | return isOfType(clazz, SUPPORTED_ARRAYS);
30 | }
31 | };
32 |
33 | public abstract boolean isOfType(final Class> clazz);
34 |
35 | public static boolean isSupported(final Class> clazz) {
36 | return PRIMITIVE_TYPES.isOfType(clazz) || CORE_TYPES.isOfType(clazz) || ARRAYS.isOfType(clazz);
37 | }
38 |
39 | static boolean isOfType(final Class> clazz, final Set> supportedTypes) {
40 | Assert.notNull(clazz);
41 |
42 | for(Class> supportedClazz : supportedTypes) {
43 | if(clazz == supportedClazz || supportedClazz.isAssignableFrom(clazz)) {
44 | return true;
45 | }
46 | }
47 |
48 | return false;
49 | }
50 |
51 | private static final Set> SUPPORTED_CORE_TYPES = new HashSet>();
52 | static {
53 | SUPPORTED_CORE_TYPES.add(Boolean.class);
54 | SUPPORTED_CORE_TYPES.add(Number.class);
55 | SUPPORTED_CORE_TYPES.add(Character.class);
56 | SUPPORTED_CORE_TYPES.add(String.class);
57 | SUPPORTED_CORE_TYPES.add(Date.class);
58 | }
59 |
60 | private static final Set> SUPPORTED_ARRAYS = new HashSet>();
61 | static {
62 | SUPPORTED_ARRAYS.add(boolean[].class);
63 | SUPPORTED_ARRAYS.add(long[].class);
64 | SUPPORTED_ARRAYS.add(short[].class);
65 | SUPPORTED_ARRAYS.add(int[].class);
66 | SUPPORTED_ARRAYS.add(byte[].class);
67 | SUPPORTED_ARRAYS.add(float[].class);
68 | SUPPORTED_ARRAYS.add(double[].class);
69 | SUPPORTED_ARRAYS.add(char[].class);
70 | SUPPORTED_ARRAYS.add(Boolean[].class);
71 | SUPPORTED_ARRAYS.add(Character[].class);
72 | SUPPORTED_ARRAYS.add(Date[].class);
73 | SUPPORTED_ARRAYS.add(String[].class);
74 | SUPPORTED_ARRAYS.add(Number[].class);
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/config/SimpleDBRepositoriesRegistrar.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.repository.config;
2 |
3 | import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport;
4 | import org.springframework.data.repository.config.RepositoryConfigurationExtension;
5 |
6 | import java.lang.annotation.Annotation;
7 |
8 | /**
9 | * SimpleDB-specific {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar}.
10 | */
11 | public class SimpleDBRepositoriesRegistrar extends RepositoryBeanDefinitionRegistrarSupport {
12 |
13 | /*
14 | * (non-Javadoc)
15 | * @see org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport#getAnnotation()
16 | */
17 | @Override
18 | protected Class extends Annotation> getAnnotation() {
19 | return EnableSimpleDBRepositories.class;
20 | }
21 |
22 | /*
23 | * (non-Javadoc)
24 | * @see org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport#getExtension()
25 | */
26 | @Override
27 | protected RepositoryConfigurationExtension getExtension() {
28 | return new SimpleDbRepositoryConfigExtension();
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/config/SimpleDbRepositoryConfigExtension.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.springframework.data.simpledb.repository.config;
17 |
18 | import org.springframework.beans.factory.support.BeanDefinitionBuilder;
19 | import org.springframework.core.annotation.AnnotationAttributes;
20 | import org.springframework.data.config.ParsingUtils;
21 | import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource;
22 | import org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport;
23 | import org.springframework.data.repository.config.XmlRepositoryConfigurationSource;
24 | import org.springframework.data.simpledb.repository.support.SimpleDbRepositoryFactoryBean;
25 | import org.w3c.dom.Element;
26 |
27 | /**
28 | * Responsibilities - provide repository factory bean - read additional properties - create root beans to be used by all
29 | * instantiated repositories
30 | *
31 | * See JpaRepositoryConfigExtension
32 | */
33 | public class SimpleDbRepositoryConfigExtension extends RepositoryConfigurationExtensionSupport {
34 |
35 | private static final String SIMPLEDB_TEMPLATE_REF = "simpledb-template-ref";
36 |
37 | /*
38 | * (non-Javadoc)
39 | *
40 | * @see org.springframework.data.repository.config14.RepositoryConfigurationExtension#getRepositoryInterface()
41 | */
42 | @Override
43 | public String getRepositoryFactoryClassName() {
44 | return SimpleDbRepositoryFactoryBean.class.getName();
45 | }
46 |
47 | /*
48 | * (non-Javadoc)
49 | *
50 | * @see org.springframework.data.repository.config14.RepositoryConfigurationExtensionSupport#getModulePrefix()
51 | */
52 | @Override
53 | protected String getModulePrefix() {
54 | // not for now. used for named queries
55 | return "simpleDb";
56 | }
57 |
58 | /*
59 | * (non-Javadoc)
60 | *
61 | * @see
62 | * org.springframework.data.repository.config14.RepositoryConfigurationExtensionSupport#postProcess(org.springframework
63 | * .beans.factory.support.BeanDefinitionBuilder,
64 | * org.springframework.data.repository.config14.XmlRepositoryConfigurationSource)
65 | */
66 | @Override
67 | public void postProcess(BeanDefinitionBuilder builder, XmlRepositoryConfigurationSource config) {
68 | Element element = config.getElement();
69 | ParsingUtils.setPropertyReference(builder, element, SIMPLEDB_TEMPLATE_REF, "simpleDbOperations");
70 | }
71 |
72 | /**
73 | * We bind here the provided SimpleDB template bean specified by "simpleDbTemplateRef" annotation property
74 | * to our internally used bean simpleDbOperations of class
75 | * {@link org.springframework.data.simpledb.repository.support.SimpleDbRepositoryFactoryBean}.
76 | * The bean will be used to construct repository implementations.
77 | */
78 | @Override
79 | public void postProcess(BeanDefinitionBuilder builder, AnnotationRepositoryConfigurationSource config) {
80 | AnnotationAttributes attributes = config.getAttributes();
81 | builder.addPropertyReference("simpleDbOperations", attributes.getString("simpleDbTemplateRef"));
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/config/SimpleDbRepositoryNamespaceHandler.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.repository.config;
2 |
3 | import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
4 | import org.springframework.data.repository.config.RepositoryBeanDefinitionParser;
5 | import org.springframework.data.repository.config.RepositoryConfigurationExtension;
6 |
7 | public class SimpleDbRepositoryNamespaceHandler extends NamespaceHandlerSupport {
8 |
9 | /*
10 | * (non-Javadoc)
11 | *
12 | * @see org.springframework.beans.factory.xml.NamespaceHandler#init()
13 | */
14 | @Override
15 | public void init() {
16 | RepositoryConfigurationExtension extension = new SimpleDbRepositoryConfigExtension();
17 | RepositoryBeanDefinitionParser repositoryBeanDefinitionParser = new RepositoryBeanDefinitionParser(extension);
18 |
19 | registerBeanDefinitionParser("repositories", repositoryBeanDefinitionParser);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/EmptyResultDataAccessException.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.repository.support;
2 |
3 | // TODO: use defined simpledb exceptions
4 | public class EmptyResultDataAccessException extends RuntimeException {
5 |
6 | private static final long serialVersionUID = 1L;
7 |
8 | public EmptyResultDataAccessException(String message) {
9 | super(message);
10 | }
11 |
12 | public EmptyResultDataAccessException(String message, Throwable cause) {
13 | super(message, cause);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/SimpleDbRepositoryFactory.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.repository.support;
2 |
3 | import java.io.Serializable;
4 |
5 | import org.springframework.data.repository.core.RepositoryMetadata;
6 | import org.springframework.data.repository.core.support.RepositoryFactorySupport;
7 | import org.springframework.data.repository.query.QueryLookupStrategy;
8 | import org.springframework.data.simpledb.core.SimpleDbOperations;
9 | import org.springframework.data.simpledb.core.SimpleDbTemplate;
10 | import org.springframework.data.simpledb.query.SimpleDbQueryLookupStrategy;
11 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformation;
12 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformationSupport;
13 |
14 | /**
15 | * SimpleDB specific generic repository factory.
16 | *
17 | */
18 | public class SimpleDbRepositoryFactory extends RepositoryFactorySupport {
19 |
20 | private SimpleDbOperations simpleDbOperations;
21 |
22 | public SimpleDbRepositoryFactory(SimpleDbOperations simpleDbOperations) {
23 | this.simpleDbOperations = new SimpleDbTemplate(simpleDbOperations.getSimpleDb());
24 |
25 | }
26 |
27 | /*
28 | * (non-Javadoc)
29 | *
30 | * @see
31 | * org.springframework.data.repository.core.support.RepositoryFactorySupport#getTargetRepository(org.springframework
32 | * .data.repository.core.RepositoryMetadata)
33 | */
34 | @SuppressWarnings( { "unchecked", "rawtypes" })
35 | @Override
36 | protected Object getTargetRepository(RepositoryMetadata metadata) {
37 | SimpleDbEntityInformation, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());
38 |
39 | SimpleDbRepositoryImpl, ?> repo = new SimpleDbRepositoryImpl(entityInformation, simpleDbOperations);
40 |
41 | return repo;
42 | }
43 |
44 | /*
45 | * (non-Javadoc)
46 | *
47 | * @see org.springframework.data.repository.support.RepositoryFactorySupport# getRepositoryBaseClass()
48 | */
49 | @Override
50 | protected Class> getRepositoryBaseClass(RepositoryMetadata metadata) {
51 | return SimpleDbRepositoryImpl.class;
52 | }
53 |
54 | /*
55 | * (non-Javadoc)
56 | *
57 | * @see org.springframework.data.repository.support.RepositoryFactorySupport# getQueryLookupStrategy
58 | * (org.springframework.data.repository.query.QueryLookupStrategy.Key)
59 | */
60 | @Override
61 | protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) {
62 | return SimpleDbQueryLookupStrategy.create(simpleDbOperations, key);
63 | }
64 |
65 | /*
66 | * (non-Javadoc)
67 | *
68 | * @see org.springframework.data.repository.support.RepositoryFactorySupport# getEntityInformation(java.lang.Class)
69 | */
70 | @Override
71 | @SuppressWarnings("unchecked")
72 | public SimpleDbEntityInformation getEntityInformation(Class domainClass) {
73 | String simpleDbDomain = simpleDbOperations.getSimpleDb().getSimpleDbDomain().getDomain(domainClass);
74 | return (SimpleDbEntityInformation) SimpleDbEntityInformationSupport.getMetadata(domainClass,
75 | simpleDbDomain);
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/SimpleDbRepositoryFactoryBean.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.repository.support;
2 |
3 | import java.io.Serializable;
4 |
5 | import org.springframework.data.repository.Repository;
6 | import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
7 | import org.springframework.data.repository.core.support.RepositoryFactorySupport;
8 | import org.springframework.data.simpledb.core.SimpleDbOperations;
9 | import org.springframework.util.Assert;
10 |
11 | /**
12 | * Constructs additional elements needed by the repository factory i.e. EntityManager for JPA, Some
13 | * SimpleDbOperationsImpl client class Returns repository creation factory.
14 | */
15 | public class SimpleDbRepositoryFactoryBean, S, ID extends Serializable> extends
16 | RepositoryFactoryBeanSupport {
17 |
18 | private SimpleDbOperations simpleDbOperations;
19 |
20 | @Override
21 | protected RepositoryFactorySupport createRepositoryFactory() {
22 | Assert.notNull(simpleDbOperations);
23 |
24 | return new SimpleDbRepositoryFactory(simpleDbOperations);
25 | }
26 |
27 | /**
28 | * Needed by spring data core to inject operations
29 | *
30 | * @param simpleDbOperations
31 | */
32 | public void setSimpleDbOperations(SimpleDbOperations simpleDbOperations) {
33 | this.simpleDbOperations = simpleDbOperations;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/entityinformation/SimpleDBEntityMappingInformation.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.repository.support.entityinformation;
2 |
3 | /**
4 | * Define methods for accessing information related to the entity definition ( e.g. id field name)
5 | */
6 | public interface SimpleDBEntityMappingInformation {
7 |
8 | String getItemNameFieldName(T entity);
9 |
10 | String getAttributesFieldName(T entity);
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/entityinformation/SimpleDbEntityInformation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.springframework.data.simpledb.repository.support.entityinformation;
17 |
18 | import org.springframework.data.repository.core.EntityInformation;
19 |
20 | import java.io.Serializable;
21 | import java.lang.reflect.Field;
22 | import java.util.List;
23 | import java.util.Map;
24 |
25 | /**
26 | * Extension of {@link org.springframework.data.repository.core.EntityInformation} to capture aditional JPA specific
27 | * information about entities.
28 | *
29 | */
30 | public interface SimpleDbEntityInformation extends EntityInformation,
31 | SimpleDBEntityMappingInformation {
32 |
33 | String getDomain();
34 |
35 | String getItemName(T entity);
36 |
37 | Map getAttributes(T entity);
38 |
39 | void validateReferenceFields(List referenceFields);
40 | }
41 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/entityinformation/SimpleDbEntityInformationSupport.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.springframework.data.simpledb.repository.support.entityinformation;
17 |
18 | import java.io.Serializable;
19 |
20 | import org.springframework.data.repository.core.support.AbstractEntityInformation;
21 | import org.springframework.util.Assert;
22 |
23 | /**
24 | * Base class for {@link SimpleDbEntityInformation} implementations to share common method implementations.
25 | *
26 | */
27 | public abstract class SimpleDbEntityInformationSupport extends
28 | AbstractEntityInformation implements SimpleDbEntityInformation {
29 |
30 | /**
31 | * Creates a new {@link SimpleDbEntityInformationSupport} with the given domain class.
32 | *
33 | * @param domainClass
34 | * must not be {@literal null}.
35 | */
36 | public SimpleDbEntityInformationSupport(Class domainClass) {
37 |
38 | super(domainClass);
39 | }
40 |
41 | /**
42 | * Creates a {@link SimpleDbEntityInformation} for the given domain class.
43 | *
44 | * @param domainClass
45 | * must not be {@literal null}.
46 | * @return
47 | */
48 | @SuppressWarnings({ "rawtypes", "unchecked" })
49 | public static SimpleDbEntityInformation getMetadata(Class domainClass, String simpleDbDomain) {
50 | Assert.notNull(domainClass);
51 | Assert.notNull(simpleDbDomain);
52 |
53 | return new SimpleDbMetamodelEntityInformation(domainClass, simpleDbDomain);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/entityinformation/SimpleDbMetamodelEntityInformation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2011-2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.springframework.data.simpledb.repository.support.entityinformation;
17 |
18 | import java.io.Serializable;
19 | import java.lang.reflect.Field;
20 | import java.util.List;
21 | import java.util.Map;
22 |
23 | import org.springframework.data.simpledb.reflection.MetadataParser;
24 |
25 | public class SimpleDbMetamodelEntityInformation extends
26 | SimpleDbEntityInformationSupport {
27 |
28 | private final String simpleDbDomain;
29 |
30 | /**
31 | * @param domainClass
32 | * must not be {@literal null}.
33 | */
34 | public SimpleDbMetamodelEntityInformation(Class domainClass, String simpleDbDomain) {
35 |
36 | super(domainClass);
37 | this.simpleDbDomain = simpleDbDomain;
38 |
39 | }
40 |
41 | /*
42 | * (non-Javadoc)
43 | *
44 | * @see org.springframework.data.repository.core.EntityInformation#getId(java.lang.Object)
45 | */
46 | @SuppressWarnings("unchecked")
47 | @Override
48 | public ID getId(T entity) {
49 | return (ID) MetadataParser.getItemName(entity);
50 | }
51 |
52 | /*
53 | * (non-Javadoc)
54 | *
55 | * @see org.springframework.data.repository.support.EntityInformation#getIdType()
56 | */
57 | @SuppressWarnings("unchecked")
58 | @Override
59 | public Class getIdType() {
60 | Field idField = MetadataParser.getIdField(getJavaType());
61 | return (Class) idField.getType();
62 | }
63 |
64 | @Override
65 | public String getDomain() {
66 | return simpleDbDomain;
67 | }
68 |
69 | @Override
70 | public String getItemName(T entity) {
71 | return MetadataParser.getItemName(entity);
72 | }
73 |
74 | @Override
75 | public Map getAttributes(T entity) {
76 | return MetadataParser.getAttributes(entity);
77 | }
78 |
79 | @Override
80 | public void validateReferenceFields(List referenceFields) {
81 | for(Field eachReferencedField : referenceFields) {
82 | MetadataParser.validateReferenceAnnotation(eachReferencedField);
83 | }
84 | }
85 |
86 | @Override
87 | public String getItemNameFieldName(T entity) {
88 | return MetadataParser.getIdField(entity).getName();
89 | }
90 |
91 | @Override
92 | public String getAttributesFieldName(T entity) {
93 | return MetadataParser.getAttributesField(entity).getName();
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/util/AlphanumStringComparator.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.util;
2 |
3 | import java.util.Comparator;
4 | import java.util.regex.Matcher;
5 | import java.util.regex.Pattern;
6 |
7 | /**
8 | * Used to compare Strings starting numbers and delimited with @ .
9 | *
10 | * "10@attr" should be bigger than "2@attr" with this comparator
11 | */
12 | public class AlphanumStringComparator implements Comparator {
13 |
14 | private static Pattern prefixRexp = Pattern.compile("^(\\d+)@");
15 |
16 | @Override
17 | public int compare(String s1, String s2) {
18 | int c = 0;
19 | Matcher m1 = prefixRexp.matcher(s1);
20 | Matcher m2 = prefixRexp.matcher(s2);
21 | if (m1.find() && m2.find()) {
22 | Integer i1 = Integer.valueOf(m1.group(1));
23 | Integer i2 = Integer.valueOf(m2.group(1));
24 | c = i1.compareTo(i2);
25 | } else {
26 | throw new IllegalArgumentException("Can not compare strings missing 'digit@' pattern");
27 | }
28 | return c;
29 | }
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/util/MapUtils.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.util;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.LinkedList;
5 | import java.util.List;
6 | import java.util.Map;
7 | import java.util.Set;
8 |
9 | public final class MapUtils {
10 |
11 | private MapUtils() {
12 | // utility class
13 | }
14 |
15 | /**
16 | * Splits rawMap's entries into a number of chunk maps of max chunkSize elements
17 | *
18 | * @param rawMap
19 | * @param chunkSize
20 | * @return
21 | */
22 | public static List>> splitToChunksOfSize(Map> rawMap, int chunkSize) {
23 | List>> mapChunks = new LinkedList>>();
24 |
25 | Set>> rawEntries = rawMap.entrySet();
26 |
27 | Map> currentChunk = new LinkedHashMap>();
28 | int rawEntryIndex = 0;
29 | for(Map.Entry> rawEntry : rawEntries) {
30 |
31 | if(rawEntryIndex % chunkSize == 0) {
32 | if(currentChunk.size() > 0) {
33 | mapChunks.add(currentChunk);
34 | }
35 | currentChunk = new LinkedHashMap>();
36 | }
37 |
38 | currentChunk.put(rawEntry.getKey(), rawEntry.getValue());
39 |
40 | rawEntryIndex++;
41 |
42 | if(rawEntryIndex == rawMap.size()) {
43 | // finished iterating
44 | mapChunks.add(currentChunk);
45 | }
46 | }
47 |
48 | return mapChunks;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/util/RandomValueGenerator.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.util;
2 |
3 | public final class RandomValueGenerator {
4 |
5 | private RandomValueGenerator() {
6 | // utility class
7 | }
8 |
9 | public static String generateStringOfLength(int length) {
10 | final StringBuilder sb = new StringBuilder();
11 | while(sb.length() < length) {
12 | sb.append("a");
13 | }
14 | return sb.toString();
15 | }
16 |
17 | public static long[] generateArrayOfSize(int size) {
18 | final long[] longPrimitiveArray = new long[size];
19 | for(int i = 0; i < size; i++) {
20 | longPrimitiveArray[i] = i;
21 | }
22 | return longPrimitiveArray;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/util/StringUtil.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.util;
2 |
3 | public final class StringUtil {
4 |
5 | private StringUtil() {
6 | // utility class
7 | }
8 |
9 | public static String toLowerFirstChar(String source) {
10 | if(source == null) {
11 | return null;
12 | }
13 |
14 | if(source.length() == 1) {
15 | return source.toLowerCase();
16 | } else {
17 | String rest = source.substring(1);
18 | String start = String.valueOf(source.charAt(0));
19 | return start.toLowerCase() + rest;
20 | }
21 | }
22 |
23 | public static String removeExtraSpaces(final String source) {
24 | return source.replaceAll(" +", " ");
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/resources/META-INF/spring.handlers:
--------------------------------------------------------------------------------
1 | http\://www.springframework.org/schema/data/simpledb=org.springframework.data.simpledb.repository.config.SimpleDbRepositoryNamespaceHandler
2 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/resources/META-INF/spring.schemas:
--------------------------------------------------------------------------------
1 | http\://www.springframework.org/schema/data/simpledb/spring-simpledb.xsd=org/springframework/data/simpledb/config/spring-simpledb.xsd
2 |
3 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/resources/META-INF/spring.tooling:
--------------------------------------------------------------------------------
1 | http\://www.springframework.org/schema/data/simpledb@name=SimpleDb Namespace
2 | http\://www.springframework.org/schema/data/simpledb@prefix=simpledb
3 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/main/resources/org/springframework/data/simpledb/config/spring-simpledb.xsd:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
13 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | The reference to a SimpleDbTemplate. Will default to 'simpleDbTemplate'.
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/attributeutil/SimpleDbAttributeValueSplitterTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.attributeutil;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import java.util.Iterator;
6 | import java.util.LinkedHashMap;
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 | import org.junit.Test;
11 |
12 | public class SimpleDbAttributeValueSplitterTest {
13 |
14 | static String STRING_OF_MAX_SIMPLE_DB_LENGTH = null;
15 | private static final String SAMPLE_ATT_NAME = "sampleAttName";
16 |
17 | static {
18 | StringBuilder builder = new StringBuilder();
19 | for(int i = 0; i < SimpleDbAttributeValueSplitter.MAX_ATTR_VALUE_LEN; i++) {
20 | builder.append("x");
21 | }
22 |
23 | STRING_OF_MAX_SIMPLE_DB_LENGTH = builder.toString();
24 | }
25 |
26 | @Test
27 | public void splitAttributeValuesWithExceedingLengths_should_detect_long_attributes() throws Exception {
28 | Map rawAttributes = new LinkedHashMap();
29 | rawAttributes.put(SAMPLE_ATT_NAME, STRING_OF_MAX_SIMPLE_DB_LENGTH + "c");
30 |
31 | Map> splitAttributes = SimpleDbAttributeValueSplitter
32 | .splitAttributeValuesWithExceedingLengths(rawAttributes);
33 | assertEquals("count(keys) == 1", 1, splitAttributes.keySet().size());
34 | Iterator> iterator = splitAttributes.values().iterator();
35 | List next = null;
36 | if (iterator.hasNext()) {
37 | next = iterator.next();
38 | }
39 | assertNotNull(next);
40 | assertEquals("count(values) == 2", 2, next.size());
41 | }
42 |
43 | @Test
44 | public void splitAttributeValuesWithExceedingLengths_should_not_split_short_attributes() throws Exception {
45 | Map rawAttributes = new LinkedHashMap();
46 | rawAttributes.put(SAMPLE_ATT_NAME, "shortValue");
47 |
48 | Map> splitAttributes = SimpleDbAttributeValueSplitter
49 | .splitAttributeValuesWithExceedingLengths(rawAttributes);
50 | assertEquals(1, splitAttributes.keySet().size());
51 |
52 | List firstSplitAttribute = splitAttributes.values().iterator().next();
53 | assertEquals("shortValue", firstSplitAttribute.get(0));
54 | }
55 |
56 | @Test
57 | public void splitAttributeValues_should_be_recombined() throws Exception {
58 | Map rawAttributes = new LinkedHashMap();
59 | rawAttributes.put(SAMPLE_ATT_NAME, STRING_OF_MAX_SIMPLE_DB_LENGTH + "c");
60 |
61 | Map> splitAttributes = SimpleDbAttributeValueSplitter
62 | .splitAttributeValuesWithExceedingLengths(rawAttributes);
63 |
64 | Map recombinedAtts = SimpleDbAttributeValueSplitter
65 | .combineAttributeValuesWithExceedingLengths(splitAttributes);
66 |
67 | assertEquals(recombinedAtts.size(), rawAttributes.size());
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/core/DomainItemBuilderTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import com.amazonaws.services.simpledb.model.Attribute;
4 | import com.amazonaws.services.simpledb.model.Item;
5 | import org.junit.Test;
6 | import org.springframework.data.simpledb.core.domain.SimpleDbSampleEntity;
7 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformation;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | import static org.junit.Assert.*;
13 |
14 | public class DomainItemBuilderTest {
15 |
16 | public static final String SAMPLE_ITEM_NAME = "SAMPLE_ITEM_NAME";
17 | private static final Boolean SAMPLE_BOOLEAN_ATT_VALUE = Boolean.TRUE;
18 | private DomainItemBuilder domainItemBuilder;
19 |
20 | @Test
21 | public void populateDomainItem_should_convert_item_name() {
22 |
23 | Item sampleItem = new Item(SAMPLE_ITEM_NAME, new ArrayList());
24 | SimpleDbEntityInformation entityInformation = SimpleDbSampleEntity
25 | .entityInformation();
26 |
27 | domainItemBuilder = new DomainItemBuilder();
28 | SimpleDbSampleEntity returnedDomainEntity = domainItemBuilder.populateDomainItem(entityInformation, sampleItem);
29 |
30 | assertEquals(SAMPLE_ITEM_NAME, returnedDomainEntity.getItemName());
31 | }
32 |
33 | @Test
34 | public void populateDomainItem_should_convert_attributes() {
35 | List attributeList = new ArrayList();
36 | attributeList.add(new Attribute("booleanField", "" + SAMPLE_BOOLEAN_ATT_VALUE));
37 |
38 | Item sampleItem = new Item(SAMPLE_ITEM_NAME, attributeList);
39 | SimpleDbEntityInformation entityInformation = SimpleDbSampleEntity
40 | .entityInformation();
41 |
42 | domainItemBuilder = new DomainItemBuilder();
43 | SimpleDbSampleEntity returnedDomainEntity = domainItemBuilder.populateDomainItem(entityInformation, sampleItem);
44 |
45 | assertTrue(returnedDomainEntity.getBooleanField() == SAMPLE_BOOLEAN_ATT_VALUE);
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/core/NestedDomainEntitiesTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import org.junit.Test;
4 | import org.springframework.data.annotation.Id;
5 | import org.springframework.data.simpledb.core.NestedDomainEntitiesTest.AClass.BClass;
6 | import org.springframework.data.simpledb.reflection.MetadataParser;
7 |
8 | import java.lang.reflect.Field;
9 | import java.util.List;
10 |
11 | import static org.junit.Assert.assertEquals;
12 | import static org.junit.Assert.assertTrue;
13 |
14 | public class NestedDomainEntitiesTest {
15 |
16 | @SuppressWarnings("unused")
17 | static class AClass {
18 |
19 | @Id
20 | private String id;
21 |
22 | private int intField;
23 | private BClass nestedB;
24 |
25 | private Integer integerField;
26 | private List floatList;
27 |
28 | static class BClass {
29 |
30 | private int intField;
31 | }
32 | }
33 |
34 | @Test
35 | public void should_parse_only_valid_nested_domain_entities() {
36 | final List parsedNestedEntities = MetadataParser.getNestedDomainFields(new AClass());
37 |
38 | assertTrue(parsedNestedEntities.size() == 1);
39 | assertEquals(BClass.class, parsedNestedEntities.get(0).getType());
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/core/NestedReferencedDomainTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import org.junit.Test;
4 | import org.springframework.data.simpledb.core.domain.SimpleDbReferencesEntity;
5 | import org.springframework.data.simpledb.reflection.MetadataParser;
6 | import org.springframework.data.simpledb.reflection.ReflectionUtils;
7 |
8 | import java.lang.reflect.Field;
9 | import java.util.List;
10 |
11 | import static org.hamcrest.MatcherAssert.assertThat;
12 | import static org.hamcrest.Matchers.is;
13 |
14 | public class NestedReferencedDomainTest {
15 |
16 | @Test
17 | public void getReferencedAttributes_should_build_recursively_referenced_nested_domain_names() {
18 |
19 | List referencedFields = ReflectionUtils.getReferenceAttributesList(SimpleDbReferencesEntity.class);
20 |
21 | assertThat(referencedFields.size(), is(3));
22 |
23 | assertThat(referencedFields.get(0).getName(), is("notNestedDouble"));
24 | assertThat(referencedFields.get(1).getName(), is("firstNestedEntity"));
25 | assertThat(referencedFields.get(2).getName(), is("secondNestedEntity"));
26 | }
27 |
28 | @Test(expected = IllegalStateException.class)
29 | public void validateReferenceAnnotation_should_fail_for_missing_Id() {
30 |
31 | List referencedFields = ReflectionUtils.getReferenceAttributesList(SimpleDbReferencesEntity.class);
32 | MetadataParser.validateReferenceAnnotation(referencedFields.get(2));
33 | }
34 |
35 | @Test(expected = IllegalStateException.class)
36 | public void validateReferenceAnnotation_should_fail_for_not_nested_field_type() {
37 |
38 | List referencedFields = ReflectionUtils.getReferenceAttributesList(SimpleDbReferencesEntity.class);
39 | MetadataParser.validateReferenceAnnotation(referencedFields.get(0));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/core/QueryBuilderTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import static org.hamcrest.CoreMatchers.containsString;
4 | import static org.junit.Assert.assertEquals;
5 | import static org.junit.Assert.assertThat;
6 |
7 | import java.util.Arrays;
8 |
9 | import org.junit.Test;
10 | import org.springframework.data.domain.Sort;
11 | import org.springframework.data.simpledb.core.domain.SimpleDbSampleEntity;
12 |
13 | public class QueryBuilderTest {
14 |
15 | @Test
16 | public void should_create_correct_queries_if_no_other_clauses_are_specified() throws Exception {
17 | QueryBuilder builder = new QueryBuilder(SimpleDbSampleEntity.entityInformation());
18 |
19 | String returnedQuery = builder.toString();
20 |
21 | assertEquals("select * from `simpleDbSampleEntity`", returnedQuery);
22 |
23 | }
24 |
25 | @Test
26 | public void should_include_sort_clause_if_requested() throws Exception {
27 | Sort sort = new Sort(Sort.Direction.ASC, "testField");
28 |
29 | QueryBuilder builder = new QueryBuilder(SimpleDbSampleEntity.entityInformation());
30 | builder.with(sort);
31 |
32 | String returnedQuery = builder.toString();
33 |
34 | assertThat(returnedQuery, containsString("where testField is not null order by testField asc"));
35 |
36 | }
37 |
38 | @Test
39 | public void should_include_count_clause_if_requested() throws Exception {
40 |
41 | QueryBuilder builder = new QueryBuilder(SimpleDbSampleEntity.entityInformation(), true);
42 |
43 | String returnedQuery = builder.toString();
44 |
45 | assertThat(returnedQuery, containsString("select count(*) from"));
46 |
47 | }
48 |
49 | @Test
50 | public void should_include_limited_items_if_requested() throws Exception {
51 |
52 | QueryBuilder builder = new QueryBuilder(SimpleDbSampleEntity.entityInformation());
53 | builder.withIds(Arrays.asList(new String[] { "id1", "id2" }));
54 |
55 | String returnedQuery = builder.toString();
56 |
57 | assertThat(returnedQuery, containsString("where (itemName()='id1' or itemName()='id2')"));
58 |
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/core/SimpleDbOperationRetrierTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core;
2 |
3 | import com.amazonaws.AmazonServiceException;
4 | import com.amazonaws.services.cloudwatch.model.ResourceNotFoundException;
5 | import org.hamcrest.core.StringContains;
6 | import org.junit.Assert;
7 | import org.junit.Test;
8 | import org.springframework.dao.DataAccessResourceFailureException;
9 | import org.springframework.dao.DataRetrievalFailureException;
10 |
11 | import static org.hamcrest.MatcherAssert.assertThat;
12 | import static org.hamcrest.Matchers.is;
13 | import static org.junit.Assert.fail;
14 |
15 | public class SimpleDbOperationRetrierTest {
16 |
17 | private static final int SERVICE_UNAVAILABLE_RETRIES = 3;
18 |
19 | @Test
20 | public void executeWithRetries_should_fail_for_exceeded_retries() throws Exception {
21 |
22 | AbstractServiceUnavailableOperationRetrier retrier = new AbstractServiceUnavailableOperationRetrier(SERVICE_UNAVAILABLE_RETRIES) {
23 |
24 | @Override
25 | public void execute() {
26 | AmazonServiceException serviceException = new AmazonServiceException("Test message");
27 | serviceException.setStatusCode(SERVICE_UNAVAILABLE_STATUS_CODE);
28 | serviceException.setErrorType(AmazonServiceException.ErrorType.Service);
29 | throw serviceException;
30 | }
31 | };
32 |
33 | try {
34 | retrier.executeWithRetries();
35 | fail("Number of retries should be exceeded");
36 | } catch(DataAccessResourceFailureException e) {
37 | // Our Exception -- ...times
38 | assertThat(e.getMessage(), StringContains.containsString("times"));
39 | }
40 | }
41 |
42 | @Test
43 | public void executeWithRetries_should_not_retry_if_no_exception_thrown() {
44 | AbstractServiceUnavailableOperationRetrier retrier = new AbstractServiceUnavailableOperationRetrier(SERVICE_UNAVAILABLE_RETRIES) {
45 |
46 | @Override
47 | public void execute() {
48 | // don't throw any exception
49 | }
50 | };
51 |
52 | retrier.executeWithRetries();
53 | Assert.assertThat(retrier.getCurrentRetry(), is(0));
54 | }
55 |
56 | @Test(expected = DataRetrievalFailureException.class)
57 | public void executeWithRetries_should_translate_unrecognized_exceptions() {
58 | AbstractServiceUnavailableOperationRetrier retrier = new AbstractServiceUnavailableOperationRetrier(SERVICE_UNAVAILABLE_RETRIES) {
59 |
60 | @Override
61 | public void execute() {
62 | throw new ResourceNotFoundException("Test Mapping");
63 | }
64 | };
65 | retrier.executeWithRetries();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/core/domain/SimpleDbReferencesEntity.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.domain;
2 |
3 | import org.springframework.data.annotation.Id;
4 | import org.springframework.data.annotation.Reference;
5 |
6 | public class SimpleDbReferencesEntity {
7 |
8 | @Id
9 | String itemName;
10 |
11 | @Reference
12 | Double notNestedDouble;
13 |
14 | @Reference
15 | FirstNestedEntity firstNestedEntity;
16 |
17 | public static class FirstNestedEntity {
18 |
19 | @Reference
20 | SecondNestedEntity secondNestedEntity;
21 | }
22 |
23 | public static class SecondNestedEntity {
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/core/domain/SimpleDbSampleEntity.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.domain;
2 |
3 | import org.springframework.data.annotation.Id;
4 | import org.springframework.data.simpledb.annotation.Attributes;
5 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformation;
6 | import org.springframework.data.simpledb.repository.support.entityinformation.SimpleDbEntityInformationSupport;
7 |
8 | import java.util.Map;
9 |
10 | public class SimpleDbSampleEntity {
11 |
12 | @Id
13 | private String itemName;
14 |
15 | private boolean booleanField;
16 |
17 | private int age;
18 |
19 | @Attributes
20 | private Map atts;
21 |
22 | public void setItemName(String itemName) {
23 | this.itemName = itemName;
24 | }
25 | public String getItemName() {
26 | return itemName;
27 | }
28 |
29 | public boolean getBooleanField() {
30 | return booleanField;
31 | }
32 | public void setBooleanField(boolean booleanField) {
33 | this.booleanField = booleanField;
34 | }
35 |
36 | public int getAge() {
37 | return age;
38 | }
39 | public void setAge(int age) {
40 | this.age = age;
41 | }
42 |
43 | public void setAtts(Map atts) {
44 | this.atts = atts;
45 | }
46 | public Map getAtts() {
47 | return atts;
48 | }
49 |
50 | @SuppressWarnings("unchecked")
51 | public static SimpleDbEntityInformation entityInformation() {
52 | return (SimpleDbEntityInformation) SimpleDbEntityInformationSupport.getMetadata(
53 | SimpleDbSampleEntity.class, "simpleDbSampleEntity");
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/core/entity/util/AttributeUtil.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.core.entity.util;
2 |
3 | import java.lang.reflect.Field;
4 | import java.util.ArrayList;
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | /**
9 | * @author cclaudiu
10 | *
11 | */
12 | public final class AttributeUtil {
13 |
14 | /* ----- Utility method to fetch AttributeNames of declared Properties from Parameter Class ------ */
15 | public static List getAttributeNamesThroughReflection(Class entityClazz) {
16 | List attributeNames = new ArrayList();
17 |
18 | for(Field eachDeclaredField : Arrays.asList(entityClazz.getDeclaredFields())) {
19 | attributeNames.add(eachDeclaredField.getName());
20 | }
21 |
22 | return attributeNames;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/PartTreeConverterTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.junit.Test;
4 | import org.springframework.data.mapping.model.MappingException;
5 | import org.springframework.data.repository.query.parser.PartTree;
6 | import org.springframework.data.simpledb.core.domain.SimpleDbSampleEntity;
7 |
8 | import static org.junit.Assert.assertEquals;
9 |
10 | public class PartTreeConverterTest {
11 |
12 | @Test
13 | public void should_create_corect_query_for_simple_property() {
14 | final String methodName = "findByItemName";
15 | final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
16 |
17 | final String query = PartTreeConverter.toIndexedQuery(tree);
18 |
19 | final String expected = " itemName = ? ";
20 |
21 | assertEquals(expected, query);
22 | }
23 |
24 | @Test
25 | public void should_create_corect_query_for_between() {
26 | final String methodName = "readByAgeBetween";
27 | final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
28 |
29 | final String query = PartTreeConverter.toIndexedQuery(tree);
30 |
31 | final String expected = " age BETWEEN ? and ? ";
32 |
33 | assertEquals(expected, query);
34 | }
35 |
36 | @Test
37 | public void should_create_corect_query_for_complex_operators() {
38 | final String methodName = "getByItemNameLikeOrAgeGreaterThanAndAgeLessThan";
39 | final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
40 |
41 | final String query = PartTreeConverter.toIndexedQuery(tree);
42 |
43 | final String expected = " itemName LIKE ? OR age > ? AND age < ? ";
44 |
45 | assertEquals(expected, query);
46 | }
47 |
48 | @Test(expected = MappingException.class)
49 | public void shoud_fail_for_unsupported_operator() {
50 | final String methodName = "readByAgeEndsWith";
51 | final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
52 |
53 | PartTreeConverter.toIndexedQuery(tree);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/QueryUtilsArrayTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.junit.Test;
4 | import org.mockito.Mockito;
5 | import org.springframework.data.domain.Pageable;
6 | import org.springframework.data.domain.Sort;
7 | import org.springframework.data.repository.query.Parameter;
8 | import org.springframework.data.repository.query.Parameters;
9 | import org.springframework.data.simpledb.attributeutil.SimpleDBAttributeConverter;
10 |
11 | import java.util.ArrayList;
12 | import java.util.Arrays;
13 | import java.util.List;
14 |
15 | import static org.hamcrest.CoreMatchers.is;
16 | import static org.junit.Assert.assertThat;
17 |
18 | public class QueryUtilsArrayTest {
19 |
20 | @Test
21 | public void buildQueryConditionsWithParameters_should_construct_correct_named_query_for_in_operator() {
22 | final String bind_query = "select * from customer_all WHERE age in :age and x= :name";
23 |
24 | final int firstAge = 23;
25 | final int secondAge = 25;
26 | final String convertedFirstAge = SimpleDBAttributeConverter.encode(firstAge);
27 | final String convertedSecondAge = SimpleDBAttributeConverter.encode(secondAge);
28 |
29 | String expectedQuery = "select * from customer_all WHERE age in ('" + convertedFirstAge + "','"+convertedSecondAge+"') and x= 'name'";
30 | final Parameters parameters = getMockParameters(new String[]{":name", ":age"}, new Class[]{String.class, int[].class});
31 |
32 | String resultedQuery = QueryUtils.buildQuery(bind_query, parameters, "name", new int[]{firstAge, secondAge});
33 |
34 | assertThat(resultedQuery, is(expectedQuery));
35 | }
36 |
37 | @Test
38 | public void buildQueryConditionsWithParameters_should_construct_correct_named_query_for_in_operator_with_no_space() {
39 | final String bind_query = "select * from customer_all WHERE age in:age";
40 |
41 | final int firstAge = 23;
42 | final int secondAge = 25;
43 | final String convertedFirstAge = SimpleDBAttributeConverter.encode(firstAge);
44 | final String convertedSecondAge = SimpleDBAttributeConverter.encode(secondAge);
45 |
46 | String expectedQuery = "select * from customer_all WHERE age in('" + convertedFirstAge + "','"+convertedSecondAge+"')";
47 | final Parameters parameters = getMockParameters(new String[]{":age"}, new Class[]{String.class});
48 |
49 | String resultedQuery = QueryUtils.buildQuery(bind_query, parameters, new int[]{firstAge, secondAge});
50 |
51 | assertThat(resultedQuery, is(expectedQuery));
52 | }
53 |
54 | static final List> TYPES = Arrays.>asList(Pageable.class, Sort.class);
55 |
56 | @SuppressWarnings({ "rawtypes", "unchecked" })
57 | private Parameter getMockParameter(String placeHolder, Integer idx, Class clazz) {
58 | Parameter mockParameter = Mockito.mock(Parameter.class);
59 |
60 | Mockito.when(mockParameter.getPlaceholder()).thenReturn(placeHolder);
61 | Mockito.when(mockParameter.isNamedParameter()).thenReturn(Boolean.TRUE);
62 | Mockito.when(mockParameter.getIndex()).thenReturn(idx);
63 | Mockito.when(mockParameter.getType()).thenReturn(clazz);
64 | Mockito.when(mockParameter.isSpecialParameter()).thenReturn(TYPES.contains(clazz));
65 |
66 | return mockParameter;
67 | }
68 |
69 | @SuppressWarnings({ "rawtypes" })
70 | private Parameters getMockParameters(String[] placeHolders, Class[] clazzes) {
71 | Parameters mockParameters = Mockito.mock(Parameters.class);
72 |
73 | List parameters = new ArrayList(placeHolders.length);
74 | for(int idx = 0; idx < placeHolders.length; ++idx) {
75 | parameters.add(getMockParameter(placeHolders[idx], idx, clazzes[idx]));
76 | }
77 |
78 | Mockito.when(mockParameters.iterator()).thenReturn(parameters.iterator());
79 | Mockito.when(mockParameters.getNumberOfParameters()).thenReturn(parameters.size());
80 |
81 | return mockParameters;
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/QueryUtilsEscapeTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import static org.hamcrest.CoreMatchers.*;
4 | import static org.junit.Assert.*;
5 |
6 | import org.junit.Test;
7 |
8 | public class QueryUtilsEscapeTest {
9 |
10 | @Test
11 | public void escapeQueryAttributes_should_convert_item_id() {
12 | final String convertedQuery = QueryUtils.escapeQueryAttributes("select customer_id from customers",
13 | "customer_id");
14 |
15 | assertThat(convertedQuery, is("select itemName() from customers"));
16 | }
17 |
18 | @Test
19 | public void escapeQueryAttributes_should_work_without_item_id() {
20 | final String convertedQuery = QueryUtils.escapeQueryAttributes("select * from customers", "customer_id");
21 |
22 | assertThat(convertedQuery, is("select * from customers"));
23 | }
24 |
25 | @Test
26 | public void escapeQueryAttributes_should_convert_item_id_for_complex_queries() {
27 | final String convertedQuery = QueryUtils.escapeQueryAttributes(
28 | "select customer_id from customers where customer_id > 4 and age = 3", "customer_id");
29 |
30 | assertThat(convertedQuery, is("select itemName() from customers where itemName() > 4 and age = 3"));
31 | }
32 |
33 | @Test
34 | public void escapeQueryAttributes_should_not_convert_overlapping_id_field_names() {
35 | final String convertedQuery = QueryUtils.escapeQueryAttributes("select itemName() from customers", "itemName");
36 |
37 | assertThat(convertedQuery, is("select itemName() from customers"));
38 |
39 | }
40 |
41 | @Test
42 | public void escapeQueryAttributes_should_convert_last_occurence_of_item_id() {
43 | final String convertedQuery = QueryUtils.escapeQueryAttributes("select * from customers order by itemName",
44 | "itemName");
45 |
46 | assertThat(convertedQuery, is("select * from customers order by itemName()"));
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/QueryUtilsPartialFieldNamesTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import static org.hamcrest.CoreMatchers.is;
4 | import static org.junit.Assert.assertThat;
5 |
6 | import java.util.List;
7 |
8 | import org.junit.Test;
9 |
10 | public class QueryUtilsPartialFieldNamesTest {
11 |
12 | @Test
13 | public void obtain_partial_field_names_from_query() {
14 | String query = "select primitiveField, coreField from `testDB.simpleDbUser`";
15 | List result = QueryUtils.getQueryPartialFieldNames(query);
16 | assertThat(result.size(), is(2));
17 | assertThat(result.get(0), is("primitiveField"));
18 | assertThat(result.get(1), is("coreField"));
19 | }
20 |
21 | @Test
22 | public void obtain_partial_field_names_from_query_edge_case() {
23 | String query = " Select \tprimitiveField\t,\ncoreField\t from `testDB.simpleDbUser`";
24 | List result = QueryUtils.getQueryPartialFieldNames(query);
25 | assertThat(result.size(), is(2));
26 | assertThat(result.get(0), is("primitiveField"));
27 | assertThat(result.get(1), is("coreField"));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/SampleEntity.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.springframework.data.annotation.Id;
4 | import org.springframework.data.simpledb.annotation.DomainPrefix;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | @DomainPrefix(value = "testDB")
10 | public class SampleEntity {
11 |
12 | @Id
13 | private String item_id;
14 | private int sampleAttribute;
15 | private ArrayList sampleList;
16 | private NestedClass sampleNestedAttribute;
17 | private List> listOfListOfInteger;
18 |
19 | public void setSampleAttribute(int sampleAttribute) {
20 |
21 | this.sampleAttribute = sampleAttribute;
22 | }
23 |
24 | public int getSampleAttribute() {
25 | return sampleAttribute;
26 | }
27 |
28 | public void setSampleList(ArrayList sampleList) {
29 |
30 | this.sampleList = sampleList;
31 | }
32 |
33 | public ArrayList getSampleList() {
34 | return sampleList;
35 | }
36 |
37 | public NestedClass getSampleNestedAttribute() {
38 | return sampleNestedAttribute;
39 | }
40 |
41 | public void setSampleNestedAttribute(NestedClass sampleNestedAttribute) {
42 | this.sampleNestedAttribute = sampleNestedAttribute;
43 | }
44 |
45 | public List> getListOfListOfInteger() {
46 | return listOfListOfInteger;
47 | }
48 |
49 | public void setListOfListOfInteger(List> listOfListOfInteger) {
50 | this.listOfListOfInteger = listOfListOfInteger;
51 | }
52 |
53 | public String getItem_id() {
54 | return item_id;
55 | }
56 |
57 | public void setItem_id(String item_id) {
58 | this.item_id = item_id;
59 | }
60 |
61 | static class NestedClass {
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/SimpleDbQueryMethodWithSelectClauseTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.mockito.Mockito.when;
5 |
6 | import java.lang.reflect.Method;
7 | import java.util.List;
8 |
9 | import org.junit.Test;
10 | import org.mockito.Mockito;
11 | import org.springframework.data.repository.core.RepositoryMetadata;
12 | import org.springframework.data.simpledb.annotation.Query;
13 | import org.springframework.data.simpledb.core.SimpleDbDomain;
14 |
15 | public class SimpleDbQueryMethodWithSelectClauseTest {
16 |
17 | @Test
18 | public void getAnnotatedQuery_should_returned_completed_select_clause_in_query() throws Exception {
19 | SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectPartialFields", SampleEntity.class);
20 | assertEquals("select sampleAttribute, sampleList from `testDB.sampleEntity`",
21 | repositoryMethod.getAnnotatedQuery());
22 | }
23 |
24 | @Test
25 | public void getAnnotatedQuery_should_convert_id() throws Exception {
26 | SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectById", SampleEntity.class);
27 | assertEquals("select item_id from `testDB.sampleEntity`", repositoryMethod.getAnnotatedQuery());
28 | }
29 |
30 | @Test
31 | public void getAnnotatedQuery_should_work_for_empty_select_statements_string() throws Exception {
32 | SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectByEmptyString", SampleEntity.class);
33 | assertEquals("select * from `testDB.sampleEntity`", repositoryMethod.getAnnotatedQuery());
34 | }
35 |
36 | public interface AnnotatedQueryRepository {
37 |
38 | @Query(select = { "sampleAttribute", "sampleList" })
39 | List selectPartialFields();
40 |
41 | @Query(select = "item_id")
42 | List selectById();
43 |
44 | @Query(select = "")
45 | List selectByEmptyString();
46 | }
47 |
48 | @SuppressWarnings({ "rawtypes", "unchecked" })
49 | private SimpleDbQueryMethod prepareQueryMethodToTest(String methodName, Class> entityClass) throws Exception {
50 | RepositoryMetadata repositoryMetadata = Mockito.mock(RepositoryMetadata.class);
51 | when(repositoryMetadata.getDomainType()).thenReturn((Class) entityClass);
52 |
53 | Method testMethod = AnnotatedQueryRepository.class.getMethod(methodName);
54 | when(repositoryMetadata.getReturnedDomainClass(testMethod)).thenReturn((Class) entityClass);
55 | SimpleDbDomain simpleDbDomain = new SimpleDbDomain();
56 | return new SimpleDbQueryMethod(testMethod, repositoryMetadata, simpleDbDomain);
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/SimpleDbQueryMethodWithWhereClauseTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.mockito.Mockito.when;
5 |
6 | import java.lang.reflect.Method;
7 | import java.util.List;
8 |
9 | import org.junit.Test;
10 | import org.mockito.Mockito;
11 | import org.springframework.data.repository.core.RepositoryMetadata;
12 | import org.springframework.data.simpledb.annotation.Query;
13 | import org.springframework.data.simpledb.core.SimpleDbDomain;
14 |
15 | public class SimpleDbQueryMethodWithWhereClauseTest {
16 |
17 | @Test
18 | public void getAnnotatedQuery_should_returned_completed_where_clause_in_query() throws Exception {
19 | SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectWithWhereClause", SampleEntity.class);
20 |
21 | // @Query(where = "sampleAttribute<='3' or sampleList is ''")
22 | final String expectedQuery = "select * from `testDB.sampleEntity` where sampleAttribute<='3' or sampleList is ''";
23 |
24 | assertEquals(expectedQuery, repositoryMethod.getAnnotatedQuery());
25 | }
26 |
27 | @Test
28 | public void getAnnotatedQuery_should_change_id_in_where_clause() throws Exception {
29 | SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectChangeId", SampleEntity.class);
30 |
31 | final String expectedQuery = "select * from `testDB.sampleEntity` where item_id ='Item_0'";
32 | assertEquals(expectedQuery, repositoryMethod.getAnnotatedQuery());
33 | }
34 |
35 | public interface AnnotatedQueryRepository {
36 |
37 | @Query(where = "sampleAttribute<='3' or sampleList is ''")
38 | List selectWithWhereClause();
39 |
40 | @Query(where = "item_id ='Item_0'")
41 | List selectChangeId();
42 | }
43 |
44 | @SuppressWarnings({ "rawtypes", "unchecked" })
45 | private SimpleDbQueryMethod prepareQueryMethodToTest(String methodName, Class> entityClass) throws Exception {
46 | RepositoryMetadata repositoryMetadata = Mockito.mock(RepositoryMetadata.class);
47 | when(repositoryMetadata.getDomainType()).thenReturn((Class) entityClass);
48 |
49 | Method testMethod = AnnotatedQueryRepository.class.getMethod(methodName);
50 | when(repositoryMetadata.getReturnedDomainClass(testMethod)).thenReturn((Class) entityClass);
51 | SimpleDbDomain simpleDbDomain = new SimpleDbDomain();
52 | return new SimpleDbQueryMethod(testMethod, repositoryMetadata, simpleDbDomain);
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/SimpleDbQueryRunnerTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import static org.junit.Assert.assertNotNull;
4 | import static org.junit.Assert.assertNull;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | import org.junit.Test;
10 | import org.mockito.Mockito;
11 | import org.springframework.data.simpledb.core.SimpleDbOperations;
12 |
13 | public class SimpleDbQueryRunnerTest {
14 |
15 | @Test(expected = IllegalArgumentException.class)
16 | public void executeSingleResultQuery_should_fail_if_multiple_results_are_retrieved() {
17 |
18 | SimpleDbOperations simpleDbOperations = Mockito.mock(SimpleDbOperations.class);
19 |
20 | List sampleMultipleResults = new ArrayList();
21 | sampleMultipleResults.add(new SampleEntity());
22 | sampleMultipleResults.add(new SampleEntity());
23 |
24 | Mockito.when(simpleDbOperations.find(Mockito.same(SampleEntity.class), Mockito.anyString())).thenReturn(
25 | sampleMultipleResults);
26 |
27 | SimpleDbQueryRunner runner = new SimpleDbQueryRunner((SimpleDbOperations) simpleDbOperations,
28 | SampleEntity.class, null);
29 |
30 | runner.executeSingleResultQuery();
31 | }
32 |
33 | @Test
34 | public void getSingleResult_should_return_null_for_empty_list() {
35 | SimpleDbQueryRunner runner = new SimpleDbQueryRunner(null, SampleEntity.class, null);
36 |
37 | final Object result = runner.getSingleResult(new ArrayList());
38 |
39 | assertNull(result);
40 | }
41 |
42 | @Test
43 | public void getSingleResult_should_return_single_value_from_list_with_one_element() {
44 | SimpleDbQueryRunner runner = new SimpleDbQueryRunner(null, SampleEntity.class, null);
45 |
46 | final ArrayList results = new ArrayList();
47 | results.add(new SampleEntity());
48 |
49 | final Object result = runner.getSingleResult(results);
50 |
51 | assertNotNull(result);
52 | }
53 |
54 | @Test(expected = IllegalArgumentException.class)
55 | public void getSingleResult_should_fail_for_list_with_multiple_elements() {
56 | SimpleDbQueryRunner runner = new SimpleDbQueryRunner(null, SampleEntity.class, null);
57 |
58 | final ArrayList results = new ArrayList();
59 | results.add(new SampleEntity());
60 | results.add(new SampleEntity());
61 |
62 | runner.getSingleResult(results);
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/SimpleDbRepositoryQueryTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.junit.Test;
4 | import org.mockito.Mockito;
5 |
6 | public class SimpleDbRepositoryQueryTest {
7 |
8 | @SuppressWarnings({ "rawtypes", "unchecked" })
9 | @Test(expected = IllegalArgumentException.class)
10 | public void assertNotHavingNestedQueryParameters_should_fail_for_nested_attributes() {
11 | SimpleDbQueryMethod method = Mockito.mock(SimpleDbQueryMethod.class);
12 | Mockito.when(method.getDomainClazz()).thenReturn((Class) SampleEntity.class);
13 |
14 | SimpleDbRepositoryQuery repositoryQuery = new SimpleDbRepositoryQuery(method, null);
15 | repositoryQuery.assertNotHavingNestedQueryParameters("select sampleNestedAttribute from SampleEntity");
16 | }
17 | }
--------------------------------------------------------------------------------
/spring-data-simpledb-impl/src/test/java/org/springframework/data/simpledb/query/SimpleDbResultConverterTest.java:
--------------------------------------------------------------------------------
1 | package org.springframework.data.simpledb.query;
2 |
3 | import org.junit.Test;
4 | import org.springframework.data.mapping.model.MappingException;
5 |
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import java.util.List;
9 | import java.util.Set;
10 |
11 | import static org.junit.Assert.assertEquals;
12 | import static org.junit.Assert.assertTrue;
13 |
14 | public class SimpleDbResultConverterTest {
15 |
16 | public static final int SAMPLE_INT_VALUE = 5;
17 |
18 | @Test
19 | public void filterNamedAttributesAsList_should_return_list_of_named_attributes() throws Exception {
20 | List