├── .github ├── dependabot.yml ├── workflows │ ├── drafter.yml │ └── build.yml ├── ISSUE_TEMPLATE │ ├── feature_request.md │ ├── config.yml │ └── bug_report.md └── release-drafter.yml ├── template.mf ├── checkstyle ├── ClassHeader.txt ├── suppressions.xml └── checkstyle.xml ├── src ├── main │ └── java │ │ └── org │ │ └── springframework │ │ └── data │ │ └── hazelcast │ │ ├── repository │ │ ├── config │ │ │ ├── package-info.java │ │ │ ├── HazelcastRepositoriesRegistrar.java │ │ │ ├── HazelcastRepositoryConfigurationExtension.java │ │ │ └── EnableHazelcastRepositories.java │ │ ├── query │ │ │ ├── package-info.java │ │ │ ├── Query.java │ │ │ ├── HazelcastCriteriaAccessor.java │ │ │ ├── HazelcastSortAccessor.java │ │ │ ├── HazelcastPropertyComparator.java │ │ │ └── GeoPredicate.java │ │ ├── package-info.java │ │ ├── support │ │ │ ├── package-info.java │ │ │ ├── SimpleHazelcastRepository.java │ │ │ ├── HazelcastEntityInformation.java │ │ │ ├── HazelcastQueryMethod.java │ │ │ ├── StringBasedHazelcastRepositoryQuery.java │ │ │ ├── HazelcastRepositoryFactoryBean.java │ │ │ ├── HazelcastRepositoryFactory.java │ │ │ └── HazelcastQueryLookupStrategy.java │ │ └── HazelcastRepository.java │ │ ├── package-info.java │ │ ├── HazelcastKeyValueAdapter.java │ │ └── HazelcastQueryEngine.java └── test │ ├── java │ ├── test │ │ └── utils │ │ │ ├── domain │ │ │ ├── NoIdEntity.java │ │ │ ├── Song.java │ │ │ ├── Movie.java │ │ │ ├── City.java │ │ │ ├── Makeup.java │ │ │ ├── MyTitle.java │ │ │ └── Person.java │ │ │ ├── repository │ │ │ ├── custom │ │ │ │ ├── SongRepository.java │ │ │ │ ├── MovieRepository.java │ │ │ │ ├── MyTitleRepository.java │ │ │ │ ├── MyTitleRepositoryImpl.java │ │ │ │ ├── MyTitleRepositoryFactoryBean.java │ │ │ │ └── MyTitleRepositoryFactory.java │ │ │ └── standard │ │ │ │ ├── CityRepository.java │ │ │ │ └── PersonRepository.java │ │ │ ├── TestConstants.java │ │ │ ├── TestDataHelper.java │ │ │ └── InstanceHelper.java │ └── org │ │ └── springframework │ │ └── data │ │ └── hazelcast │ │ ├── topology │ │ ├── ClusterIT.java │ │ ├── ClientServerIT.java │ │ └── AbstractTopologyIT.java │ │ ├── repository │ │ ├── KeyValueIT.java │ │ ├── support │ │ │ ├── HazelcastEntityInformationTest.java │ │ │ └── SimpleHazelcastRepositoryIT.java │ │ ├── config │ │ │ └── EnableHazelcastRepositoriesIT.java │ │ ├── query │ │ │ ├── HazelcastPropertyComparatorTest.java │ │ │ └── HazelcastSortAccessorTest.java │ │ ├── custom │ │ │ └── CustomRepoIT.java │ │ └── PagingSortingIT.java │ │ └── HazelcastUtils.java │ └── resources │ └── logback-test.xml ├── README.md ├── .gitignore └── LICENSE /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "maven" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | time: "02:00" 8 | - package-ecosystem: "github-actions" 9 | directory: "/" 10 | schedule: 11 | interval: "daily" 12 | time: "02:00" 13 | -------------------------------------------------------------------------------- /.github/workflows/drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | update_release_draft: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: release-drafter/release-drafter@v5.17.5 13 | env: 14 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "Feature request" 3 | about: Suggest an idea for this project 4 | labels: 'Type: Enhancement' 5 | --- 6 | 7 | 12 | 13 | **Please describe the problem you are trying to solve** 14 | ... 15 | 16 | **Please describe the desired behavior** 17 | ... 18 | 19 | **Describe alternatives you've considered** 20 | ... 21 | -------------------------------------------------------------------------------- /template.mf: -------------------------------------------------------------------------------- 1 | Bundle-SymbolicName: org.springframework.data.hazelcast 2 | Bundle-Name: ${project.name} 3 | Bundle-Vendor: Hazelcast, Inc., Pivotal Software, Inc. 4 | Bundle-Version: ${project.version} 5 | Bundle-ManifestVersion: 2 6 | Bundle-RequiredExecutionEnvironment: JavaSE-1.8 7 | Import-Template: 8 | com.hazelcast.*;version="${hazelcast:[=.=.=,+1.0.0)}";resolution:=optional, 9 | org.springframework.*;version="${spring:[=.=.=,+1.0.0)}", 10 | org.springframework.data.*;version="${springdata.keyvalue:[=.=.=,+1.0.0)}" 11 | DynamicImport-Package: * 12 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: $NEXT_PATCH_VERSION 2 | tag-template: $NEXT_PATCH_VERSION 3 | template: | 4 | ## What’s Changed 5 | 6 | $CHANGES 7 | 8 | ## Contributors 9 | $CONTRIBUTORS 10 | 11 | Special thanks to all contributors! 👏 12 | 13 | categories: 14 | - title: Features & Enhancements 15 | labels: 16 | - 'feature' 17 | - 'enhancement' 18 | - title: Fixes 19 | labels: 20 | - 'fix' 21 | - 'bugfix' 22 | - 'bug' 23 | - title: Dependencies 24 | label: dependencies 25 | - title: Documentation 26 | label: documentation 27 | 28 | exclude-labels: 29 | - 'internal' 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | contact_links: 3 | - name: Hazelcast Google Group 4 | url: https://groups.google.com/forum/#!forum/hazelcast 5 | about: We're not actively answering questions on GitHub, so feel free to ask one on our Google Group! 6 | - name: Stack Overflow 7 | url: https://stackoverflow.com/questions/tagged/hazelcast 8 | about: We're not actively answering questions on GitHub, so feel free to ask one on Stack Overflow! 9 | - name: Hazelcast community Slack 10 | url: https://slack.hazelcast.com/ 11 | about: We're not actively answering questions on Github, so feel free to ask one on Slack! 12 | -------------------------------------------------------------------------------- /checkstyle/ClassHeader.txt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/config/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | /** 17 | *

18 | * Configuration defaults for using Hazelcast as a key-value store. 19 | *

20 | */ 21 | package org.springframework.data.hazelcast.repository.config; 22 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/query/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | /** 17 | *

18 | * Implementation of querying so that Hazelcast repositories can be queried in the standard Spring query method style. 19 | *

20 | */ 21 | package org.springframework.data.hazelcast.repository.query; 22 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | /** 17 | *

18 | * Contains the {@link org.springframework.stereotype.Repository @Repository} bean interface available for Hazelcast 19 | * applications. 20 | *

21 | */ 22 | package org.springframework.data.hazelcast.repository; 23 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | /** 17 | *

18 | * Mainly defines {@link org.springframework.data.hazelcast.HazelcastKeyValueAdapter} providing Hazelcast as an 19 | * implementation of a key-value store. 20 | *

21 | */ 22 | package org.springframework.data.hazelcast; 23 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: 3 | push: 4 | paths-ignore: 5 | - '**.md' 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | java: [ '8' ] 13 | hazelcast: [ '4.0.3', '4.1' ] 14 | architecture: [ 'x64' ] 15 | name: Build with JDK ${{ matrix.java }} and Hazelcast ${{ matrix.hazelcast }} 16 | steps: 17 | - uses: actions/checkout@v6 18 | - name: Setup JDK 19 | uses: actions/setup-java@v5 20 | with: 21 | distribution: 'zulu' 22 | java-version: ${{ matrix.java }} 23 | architecture: ${{ matrix.architecture }} 24 | 25 | - uses: actions/cache@v4 26 | with: 27 | path: ~/.m2/repository 28 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 29 | restore-keys: ${{ runner.os }}-maven- 30 | 31 | - name: Build with Maven 32 | run: mvn -Dhazelcast.version=${{ matrix.hazelcast }} package 33 | 34 | -------------------------------------------------------------------------------- /checkstyle/suppressions.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 18 | 19 | 22 | 23 | 24 | 27 | 28 | -------------------------------------------------------------------------------- /src/test/java/test/utils/domain/NoIdEntity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.domain; 18 | 19 | import org.springframework.data.annotation.Id; 20 | import org.springframework.data.keyvalue.annotation.KeySpace; 21 | 22 | import java.io.Serializable; 23 | 24 | /** 25 | * An entity with no {@link Id} annotation. 26 | * 27 | * @author Gokhan Oner 28 | */ 29 | @KeySpace 30 | public class NoIdEntity 31 | implements Serializable { 32 | private static final long serialVersionUID = 1L; 33 | 34 | private String name; 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/query/Query.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.query; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Query Annotation do define Hazelcast SqlPredicates 25 | */ 26 | @Retention(RetentionPolicy.RUNTIME) 27 | @Target(ElementType.METHOD) 28 | public @interface Query { 29 | 30 | String value() default ""; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/support/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | /** 17 | *

18 | * {@link HazelcastPartTreeQuery} is a required modification to that provided by Spring-Data-Keyvalue (class 19 | * {@link KeyValuePartTreeQuery}) to implement queries correctly for Hazelcast. 20 | *

21 | *

22 | * As this is embedded, need to provide {@link HazelcastRepositoryFactoryBean} to create 23 | * {@link HazelcastRepositoryFactory} which provide a {@link HazelcastQueryLookupStrategy}. There largely extend their 24 | * Spring-Data-KeyValue counterparts, copying where necessary, and overriding where possible. 25 | *

26 | */ 27 | package org.springframework.data.hazelcast.repository.support; 28 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/topology/ClusterIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package org.springframework.data.hazelcast.topology; 18 | 19 | import org.springframework.test.context.ActiveProfiles; 20 | import test.utils.TestConstants; 21 | 22 | /** 23 | *

24 | * Run the {@link AbstractTopologyIT} tests with the server-only profile, that defines a cluster with multiple server 25 | * nodes. 26 | *

27 | *

28 | * Spring Data Hazelcast selects one of server nodes to connect to, so the tests compare expected outcome against 29 | * another server node. 30 | *

31 | * 32 | * @author Neil Stevenson 33 | */ 34 | @ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_CLUSTER) 35 | public class ClusterIT 36 | extends AbstractTopologyIT { 37 | } 38 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug 3 | about: Create a report to help us improve 4 | labels: 'Type: Defect' 5 | --- 6 | 7 | 10 | 11 | **Describe the bug** 12 | A clear and concise description of what the bug is. 13 | 14 | **Expected behavior** 15 | A clear and concise description of what you expected to happen. 16 | 17 | **To Reproduce** 18 | 19 | Steps to reproduce the behavior: 20 | 1. Go to '...' 21 | 2. Click on '....' 22 | 3. ... 23 | 24 | **Additional context** 25 | 26 | 39 | -------------------------------------------------------------------------------- /src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | %d{HH:mm:ss.SSS} %5p %70(%c{50}.%M\(%L\)) - %m%n 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /src/test/java/test/utils/domain/Song.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.domain; 18 | 19 | import org.springframework.data.keyvalue.annotation.KeySpace; 20 | 21 | /** 22 | *

A {@code Song} is a kind of {@link MyTitle}, as the fields here are just the 23 | * year and the song title. 24 | *

25 | *

26 | * Don't provide a value for the {@code @KeySpace} annotation, so the map name 27 | * will default to the fully qualified class name, "{@code test.utils.Song}". 28 | *

29 | * 30 | * @author Neil Stevenson 31 | */ 32 | @KeySpace 33 | public class Song 34 | extends MyTitle { 35 | private static final long serialVersionUID = 1L; 36 | 37 | @Override 38 | public String toString() { 39 | return "Song [id=" + super.getId() + ", title=" + super.getTitle() + "]"; 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /src/test/java/test/utils/domain/Movie.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.domain; 18 | 19 | import org.springframework.data.keyvalue.annotation.KeySpace; 20 | import test.utils.TestConstants; 21 | 22 | /** 23 | *

A {@code Movie} is a kind of {@link MyTitle}, as the fields here are just the 24 | * year and the movie title. 25 | *

26 | *

27 | * Give an argument {@code @KeySpace} to name the map used, "{@code Movie}" 28 | * rather than the default fully class name. 29 | *

30 | * 31 | * @author Neil Stevenson 32 | */ 33 | @KeySpace(TestConstants.MOVIE_MAP_NAME) 34 | public class Movie 35 | extends MyTitle { 36 | private static final long serialVersionUID = 1L; 37 | 38 | @Override 39 | public String toString() { 40 | return "Movie [id=" + super.getId() + ", title=" + super.getTitle() + "]"; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/test/utils/repository/custom/SongRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.repository.custom; 18 | 19 | import test.utils.domain.Song; 20 | 21 | import java.util.List; 22 | 23 | /** 24 | *

Extend the {@link MyTitleRepository} for song titles, 25 | * inheriting some methods application to the base class {@link MyTitle} 26 | * and adding some methods specific to {@link Song} objects. 27 | *

28 | * 29 | * @author Neil Stevenson 30 | */ 31 | public interface SongRepository 32 | extends MyTitleRepository { 33 | 34 | /** 35 | *

36 | * This could be generic behaviour, but make specific 37 | * to {@link SongRepository} for tests. 38 | *

39 | * 40 | * @param text A year 41 | * @return Previous years 42 | */ 43 | public List findByIdLessThan(String text); 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/test/utils/repository/custom/MovieRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.repository.custom; 18 | 19 | import test.utils.domain.Movie; 20 | 21 | import java.util.List; 22 | 23 | /** 24 | *

Extend the {@link MyTitleRepository} for movie titles, 25 | * inheriting some methods application to the base class {@link MyTitle} 26 | * and adding some methods specific to {@link Movie} objects. 27 | *

28 | * 29 | * @author Neil Stevenson 30 | */ 31 | public interface MovieRepository 32 | extends MyTitleRepository { 33 | 34 | /** 35 | *

36 | * This could be generic behaviour, but make specific 37 | * to {@link MovieRepository} for tests. 38 | *

39 | * 40 | * @param text A word in the title 41 | * @return Matches 42 | */ 43 | public List findByTitleLike(String text); 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/test/utils/repository/custom/MyTitleRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.repository.custom; 18 | 19 | import org.springframework.data.hazelcast.repository.HazelcastRepository; 20 | import org.springframework.data.repository.NoRepositoryBean; 21 | 22 | import java.io.Serializable; 23 | 24 | /** 25 | *

Define a generic repository bean for extension by other interfaces. 26 | * Mark with {@code @NoRepositoryBean} so Spring doesn't try to create one 27 | * of these at runtime. 28 | *

29 | * 30 | * @author Neil Stevenson 31 | */ 32 | @NoRepositoryBean 33 | public interface MyTitleRepository 34 | extends HazelcastRepository { 35 | 36 | /** 37 | *

38 | * A method generic to {@code MyTitle} objects in 39 | * the {@code MovieRepository} and {@code SongRepository} 40 | *

41 | */ 42 | public int wordsInTitle(String year); 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/repository/KeyValueIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package org.springframework.data.hazelcast.repository; 18 | 19 | import org.junit.Test; 20 | import org.springframework.data.keyvalue.repository.KeyValueRepository; 21 | import org.springframework.data.repository.PagingAndSortingRepository; 22 | import test.utils.domain.Person; 23 | 24 | import javax.annotation.Resource; 25 | 26 | /** 27 | *

28 | * Downcast a {@link HazelcastRepository} into a {@link KeyValueRepository} to test any Key-Value additions to 29 | * {@link PagingAndSortingRepository}. At the moment, there are none so this is empty. 30 | *

31 | * 32 | * @author Neil Stevenson 33 | */ 34 | public class KeyValueIT { 35 | 36 | // PersonRepository is really a HazelcastRepository 37 | @Resource 38 | private KeyValueRepository personRepository; 39 | 40 | /* No tests required, see class comments above. 41 | */ 42 | @Test 43 | public void no_op() { 44 | ; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/test/utils/TestConstants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils; 18 | 19 | import test.utils.domain.Song; 20 | 21 | /** 22 | * @author Neil Stevenson 23 | */ 24 | public class TestConstants { 25 | 26 | public static final String CLIENT_INSTANCE_NAME = "hazelcast-instance-client"; 27 | public static final String SERVER_INSTANCE_NAME = "hazelcast-instance-server"; 28 | 29 | public static final String SPRING_TEST_PROFILE_CLIENT_SERVER = "client-server"; 30 | public static final String SPRING_TEST_PROFILE_CLUSTER = "cluster"; 31 | public static final String SPRING_TEST_PROFILE_SINGLETON = "singleton"; 32 | 33 | public static final String MAKEUP_MAP_NAME = "Make-up"; 34 | public static final String MOVIE_MAP_NAME = "Movie"; 35 | public static final String PERSON_MAP_NAME = "Actors"; 36 | public static final String SONG_MAP_NAME = Song.class.getCanonicalName(); 37 | public static final String CITY_MAP_NAME = "Cities"; 38 | 39 | public static final String[] OSCAR_MAP_NAMES = {MAKEUP_MAP_NAME, MOVIE_MAP_NAME, PERSON_MAP_NAME, SONG_MAP_NAME, CITY_MAP_NAME}; 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/test/utils/repository/standard/CityRepository.java: -------------------------------------------------------------------------------- 1 | package test.utils.repository.standard; 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.geo.Circle; 8 | import org.springframework.data.geo.Distance; 9 | import org.springframework.data.geo.Point; 10 | import org.springframework.data.geo.Shape; 11 | import org.springframework.data.hazelcast.repository.HazelcastRepository; 12 | 13 | import test.utils.domain.City; 14 | 15 | /** 16 | *

17 | * Repository class used for tests to test geospatial data. 18 | *

19 | *

20 | * The specified methods are implemented by Spring at run-time, using the method name and parameters to deduce the query 21 | * syntax. 22 | *

23 | *

24 | * See {@link org.springframework.data.repository.query.parser.PartTree PartTree} for details of the query syntax. A 25 | * simple example being a concatenation: 26 | *

    27 | *
  • '{@code Near}' - sorts entities by distance from a given point
  • 28 | *
  • '{@code Within}' - both sorts and filters entities, returning those within the given distance, range or shape
  • 29 | *
30 | *

31 | * 32 | * @author Ulhas R Manekar 33 | */ 34 | public interface CityRepository 35 | extends HazelcastRepository { 36 | 37 | public List findByLocationNear(Point point, Distance distance); 38 | 39 | public Long countByLocationNear(Point point, Distance distance); 40 | 41 | public List findByLocationNear(Point point, Object distance); 42 | 43 | public List findByLocationWithin(Circle circle); 44 | 45 | public Page findByLocationNear(Point point, Distance distance, Pageable pageable); 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/support/SimpleHazelcastRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.support; 17 | 18 | import org.springframework.data.hazelcast.repository.HazelcastRepository; 19 | import org.springframework.data.keyvalue.core.KeyValueOperations; 20 | import org.springframework.data.keyvalue.repository.support.SimpleKeyValueRepository; 21 | import org.springframework.data.repository.core.EntityInformation; 22 | 23 | import java.io.Serializable; 24 | 25 | /** 26 | *

A concrete implementation to instantiate directly rather than allow 27 | * Spring to generate. 28 | *

29 | * 30 | * @param The domain object 31 | * @param The key of the domain object 32 | * @author Neil Stevenson 33 | */ 34 | public class SimpleHazelcastRepository 35 | extends SimpleKeyValueRepository 36 | implements HazelcastRepository { 37 | 38 | public SimpleHazelcastRepository(EntityInformation metadata, KeyValueOperations operations) { 39 | super(metadata, operations); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/HazelcastUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast; 17 | 18 | import com.hazelcast.config.Config; 19 | import com.hazelcast.core.Hazelcast; 20 | import com.hazelcast.core.HazelcastInstance; 21 | 22 | /** 23 | * @author Christoph Strobl 24 | */ 25 | public class HazelcastUtils { 26 | 27 | static Config hazelcastConfig() { 28 | 29 | Config hazelcastConfig = new Config(); 30 | hazelcastConfig.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); 31 | hazelcastConfig.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false); 32 | hazelcastConfig.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false); 33 | 34 | return hazelcastConfig; 35 | } 36 | 37 | public static HazelcastKeyValueAdapter preconfiguredHazelcastKeyValueAdapter() { 38 | HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(hazelcastConfig()); 39 | HazelcastKeyValueAdapter hazelcastKeyValueAdapter = new HazelcastKeyValueAdapter(hazelcastInstance); 40 | return hazelcastKeyValueAdapter; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/support/HazelcastEntityInformation.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.support; 17 | 18 | import org.springframework.data.annotation.Id; 19 | import org.springframework.data.mapping.MappingException; 20 | import org.springframework.data.mapping.PersistentEntity; 21 | import org.springframework.data.repository.core.EntityInformation; 22 | import org.springframework.data.repository.core.support.PersistentEntityInformation; 23 | 24 | /** 25 | * {@link EntityInformation} implementation checks for {@link Id} field eagarly to prevent NPE if not found. 26 | * 27 | * @author Gokhan Oner 28 | */ 29 | class HazelcastEntityInformation 30 | extends PersistentEntityInformation { 31 | 32 | /** 33 | * @param entity must not be {@literal null}. 34 | */ 35 | HazelcastEntityInformation(PersistentEntity entity) { 36 | super(entity); 37 | if (!entity.hasIdProperty()) { 38 | throw new MappingException( 39 | String.format("Entity %s requires a field annotated with %s", entity.getName(), Id.class.getName())); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/HazelcastRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository; 17 | 18 | import org.springframework.data.keyvalue.repository.KeyValueRepository; 19 | import org.springframework.data.repository.NoRepositoryBean; 20 | 21 | import java.io.Serializable; 22 | 23 | /** 24 | *

25 | * Subtype {@link org.springframework.stereotype.Repository @Repository} for Hazelcast usage. 26 | *

27 | *

28 | * Although part of the rationale of the repository interface is to abstract the implementation, it is useful for type 29 | * checking to confirm the allowed type generics for the domain classes. 30 | *

31 | *

32 | * Note that {@link org.springframework.data.keyvalue.repository.KeyValueRepository KeyValueRepository} defines that the 33 | * {@code ID} class extends {@link Serializable}. 34 | *

35 | * 36 | * @param The type of the domain value class 37 | * @param The type of the domain key class 38 | * @author Neil Stevenson 39 | */ 40 | @NoRepositoryBean 41 | public interface HazelcastRepository 42 | extends KeyValueRepository { 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/test/utils/domain/City.java: -------------------------------------------------------------------------------- 1 | package test.utils.domain; 2 | 3 | import java.io.Serializable; 4 | import java.util.Objects; 5 | 6 | import org.springframework.data.annotation.Id; 7 | import org.springframework.data.geo.Point; 8 | import org.springframework.data.keyvalue.annotation.KeySpace; 9 | 10 | import test.utils.TestConstants; 11 | 12 | /** 13 | * Domain class used for tests to test geospatial data. 14 | * 15 | * @author Ulhas R Manekar 16 | */ 17 | @KeySpace(TestConstants.CITY_MAP_NAME) 18 | public class City 19 | implements Comparable, Serializable { 20 | private static final long serialVersionUID = 1L; 21 | 22 | @Id 23 | private String id; 24 | private String name; 25 | private Point location; 26 | 27 | public City() { 28 | super(); 29 | } 30 | 31 | public City(String id, String name, Point location) { 32 | super(); 33 | this.id = id; 34 | this.name = name; 35 | this.location = location; 36 | } 37 | 38 | public String getId() { 39 | return id; 40 | } 41 | 42 | public void setId(String id) { 43 | this.id = id; 44 | } 45 | 46 | public String getName() { 47 | return name; 48 | } 49 | 50 | public void setName(String name) { 51 | this.name = name; 52 | } 53 | 54 | public Point getLocation() { 55 | return location; 56 | } 57 | 58 | public void setLocation(Point location) { 59 | this.location = location; 60 | } 61 | 62 | @Override 63 | public int hashCode() { 64 | return Objects.hash(id, name, location); 65 | } 66 | 67 | @Override 68 | public boolean equals(Object o) { 69 | if (this == o) { 70 | return true; 71 | } 72 | if (o == null || getClass() != o.getClass()) { 73 | return false; 74 | } 75 | City city = (City) o; 76 | return Objects.equals(id, city.id) && Objects.equals(name, city.name) 77 | && Objects.equals(location, city.location); 78 | } 79 | 80 | // Sort by name 81 | @Override 82 | public int compareTo(City that) { 83 | return this.name.compareTo(that.getName()); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/repository/support/HazelcastEntityInformationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.support; 17 | 18 | import com.hazelcast.core.Hazelcast; 19 | import org.junit.AfterClass; 20 | import org.junit.Before; 21 | import org.junit.Test; 22 | import org.springframework.data.hazelcast.HazelcastUtils; 23 | import org.springframework.data.keyvalue.core.KeyValueOperations; 24 | import org.springframework.data.keyvalue.core.KeyValueTemplate; 25 | import org.springframework.data.mapping.MappingException; 26 | import org.springframework.data.mapping.PersistentEntity; 27 | import test.utils.domain.NoIdEntity; 28 | 29 | public class HazelcastEntityInformationTest { 30 | 31 | private KeyValueOperations operations; 32 | 33 | @Before 34 | public void setUp() { 35 | this.operations = new KeyValueTemplate(HazelcastUtils.preconfiguredHazelcastKeyValueAdapter()); 36 | } 37 | 38 | @Test(expected = MappingException.class) 39 | public void throwsMappingExceptionWhenNoIdPropertyPresent() { 40 | PersistentEntity persistentEntity = operations.getMappingContext().getPersistentEntity(NoIdEntity.class); 41 | new HazelcastEntityInformation<>(persistentEntity); 42 | } 43 | 44 | @AfterClass 45 | public static void close() { 46 | Hazelcast.shutdownAll(); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/config/HazelcastRepositoriesRegistrar.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.config; 17 | 18 | import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; 19 | import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport; 20 | import org.springframework.data.repository.config.RepositoryConfigurationExtension; 21 | 22 | import java.lang.annotation.Annotation; 23 | 24 | /** 25 | * Special {@link ImportBeanDefinitionRegistrar} to point the infrastructure to inspect 26 | * {@link EnableHazelcastRepositories}. 27 | * 28 | * @author Oliver Gierke 29 | * @author Neil Stevenson 30 | * @author Rafal Leszko 31 | */ 32 | class HazelcastRepositoriesRegistrar extends RepositoryBeanDefinitionRegistrarSupport { 33 | 34 | /* 35 | * (non-Javadoc) 36 | * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoriesRegistrar#getAnnotation() 37 | */ 38 | @Override 39 | protected Class getAnnotation() { 40 | return EnableHazelcastRepositories.class; 41 | } 42 | 43 | /* 44 | * (non-Javadoc) 45 | * @see org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport#getExtension() 46 | */ 47 | @Override 48 | protected RepositoryConfigurationExtension getExtension() { 49 | return new HazelcastRepositoryConfigurationExtension(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastCriteriaAccessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.query; 17 | 18 | import com.hazelcast.query.Predicate; 19 | import com.hazelcast.query.impl.predicates.PagingPredicateImpl; 20 | import org.springframework.data.keyvalue.core.CriteriaAccessor; 21 | import org.springframework.data.keyvalue.core.query.KeyValueQuery; 22 | 23 | /** 24 | *

25 | * Provide a mechanism to convert the abstract query into the direct implementation in Hazelcast. 26 | *

27 | * 28 | * @author Neil Stevenson 29 | * @author Viacheslav Petriaiev 30 | */ 31 | public class HazelcastCriteriaAccessor 32 | implements CriteriaAccessor> { 33 | 34 | /** 35 | * @param A query in Spring form 36 | * @return The same in Hazelcast form 37 | */ 38 | public Predicate resolve(KeyValueQuery query) { 39 | 40 | if (query == null) { 41 | return null; 42 | } 43 | 44 | final Object criteria = query.getCriteria(); 45 | if (criteria == null) { 46 | return null; 47 | } 48 | 49 | if (criteria instanceof PagingPredicateImpl) { 50 | PagingPredicateImpl pagingPredicate = (PagingPredicateImpl) criteria; 51 | query.limit(pagingPredicate.getPageSize()); 52 | return pagingPredicate.getPredicate(); 53 | } 54 | 55 | if (criteria instanceof Predicate) { 56 | return (Predicate) criteria; 57 | } 58 | 59 | throw new UnsupportedOperationException(query.toString()); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/test/utils/repository/custom/MyTitleRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.repository.custom; 18 | 19 | import org.springframework.data.hazelcast.repository.support.SimpleHazelcastRepository; 20 | import org.springframework.data.keyvalue.core.KeyValueOperations; 21 | import org.springframework.data.repository.core.EntityInformation; 22 | import test.utils.domain.MyTitle; 23 | 24 | import java.io.Serializable; 25 | 26 | /** 27 | *

Implement a custom repository for {@link MyTitleRepository}, but 28 | * inherit most of the behaviour from {@link SimpleHazelcastRepository}. 29 | *

30 | * 31 | * @param The domain object 32 | * @param The key of the domain object 33 | * @author Neil Stevenson 34 | */ 35 | public class MyTitleRepositoryImpl 36 | extends SimpleHazelcastRepository 37 | implements MyTitleRepository { 38 | 39 | public MyTitleRepositoryImpl(EntityInformation metadata, KeyValueOperations keyValueOperations) { 40 | super(metadata, keyValueOperations); 41 | } 42 | 43 | /** 44 | *

45 | * Count the words in a particular title. 46 | *

47 | * 48 | * @param Key to lookup 49 | * @return Tokens in string, -1 if not found 50 | */ 51 | public int wordsInTitle(String year) { 52 | @SuppressWarnings("unchecked") MyTitle myTitle = (MyTitle) super.findById((ID) year).orElse(null); 53 | 54 | if (myTitle == null) { 55 | return -1; 56 | } else { 57 | return myTitle.getTitle().split("[-\\s]").length; 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/test/utils/domain/Makeup.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.domain; 18 | 19 | import org.springframework.data.annotation.Id; 20 | import org.springframework.data.keyvalue.annotation.KeySpace; 21 | import test.utils.TestConstants; 22 | 23 | import java.io.Serializable; 24 | 25 | /** 26 | *

{@code Makeup} is for the prize for make-up and hair styling. 27 | *

28 | *

29 | * Give an argument {@code @KeySpace} to name the map used, "{@code Make-up}" 30 | * rather than the default fully class name. 31 | *

32 | * 33 | * @author Neil Stevenson 34 | */ 35 | @KeySpace(TestConstants.MAKEUP_MAP_NAME) 36 | public class Makeup 37 | implements Comparable, Serializable { 38 | 39 | private static final long serialVersionUID = 1L; 40 | 41 | @Id 42 | private String id; 43 | private String filmTitle; 44 | private String artistOrArtists; 45 | 46 | public String getId() { 47 | return id; 48 | } 49 | 50 | public void setId(String id) { 51 | this.id = id; 52 | } 53 | 54 | public String getFilmTitle() { 55 | return filmTitle; 56 | } 57 | 58 | public void setFilmTitle(String filmTitle) { 59 | this.filmTitle = filmTitle; 60 | } 61 | 62 | public String getArtistOrArtists() { 63 | return artistOrArtists; 64 | } 65 | 66 | public void setArtistOrArtists(String artistOrArtists) { 67 | this.artistOrArtists = artistOrArtists; 68 | } 69 | 70 | @Override 71 | public String toString() { 72 | return "Makeup [id=" + id + ", filmTitle=" + filmTitle + ", artistOrArtists=" + artistOrArtists + "]"; 73 | } 74 | 75 | // Sort by film title only 76 | @Override 77 | public int compareTo(Makeup that) { 78 | return this.filmTitle.compareTo(that.getFilmTitle()); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/support/HazelcastQueryMethod.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.support; 17 | 18 | import org.springframework.core.annotation.AnnotationUtils; 19 | import org.springframework.data.hazelcast.repository.query.Query; 20 | import org.springframework.data.keyvalue.annotation.KeySpace; 21 | import org.springframework.data.projection.ProjectionFactory; 22 | import org.springframework.data.repository.core.RepositoryMetadata; 23 | import org.springframework.data.repository.query.QueryMethod; 24 | import org.springframework.util.StringUtils; 25 | 26 | import java.lang.reflect.Method; 27 | 28 | /** 29 | * Hazelcast {@link QueryMethod} Implementation 30 | */ 31 | public class HazelcastQueryMethod 32 | extends QueryMethod { 33 | 34 | private final Method method; 35 | 36 | public HazelcastQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory) { 37 | super(method, metadata, factory); 38 | this.method = method; 39 | } 40 | 41 | public boolean hasAnnotatedQuery() { 42 | return StringUtils.hasText(getAnnotatedQuery()); 43 | } 44 | 45 | String getAnnotatedQuery() { 46 | Query query = method.getAnnotation(Query.class); 47 | String queryString = (query != null ? (String) AnnotationUtils.getValue(query) : null); 48 | return (StringUtils.hasText(queryString) ? queryString : null); 49 | } 50 | 51 | String getKeySpace() { 52 | Class clazz = getEntityInformation().getJavaType(); 53 | KeySpace keySpace = clazz.getAnnotation(KeySpace.class); 54 | String queryString = (keySpace != null ? (String) AnnotationUtils.getValue(keySpace) : null); 55 | return (StringUtils.hasText(queryString) ? queryString : clazz.getName()); 56 | 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/repository/config/EnableHazelcastRepositoriesIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.config; 17 | 18 | import org.junit.Test; 19 | import org.junit.runner.RunWith; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.test.annotation.DirtiesContext; 22 | import org.springframework.test.context.ActiveProfiles; 23 | import org.springframework.test.context.ContextConfiguration; 24 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 25 | import test.utils.InstanceHelper; 26 | import test.utils.TestConstants; 27 | import test.utils.domain.Person; 28 | import test.utils.repository.standard.PersonRepository; 29 | 30 | import java.util.List; 31 | 32 | import static org.hamcrest.Matchers.hasSize; 33 | import static org.hamcrest.Matchers.is; 34 | import static org.hamcrest.Matchers.notNullValue; 35 | import static org.junit.Assert.assertThat; 36 | 37 | /** 38 | *

39 | * Integration test for Hazelcast repositories. 40 | *

41 | *

42 | * Domain class {@link Person} and repository {@link PersonRepository} made into outer classes for use in other tests. 43 | *

44 | * 45 | * @author Christoph Strobl 46 | * @author Oliver Gierke 47 | * @author Neil Stevenson 48 | */ 49 | @RunWith(SpringJUnit4ClassRunner.class) 50 | @ContextConfiguration(classes = {InstanceHelper.class}) 51 | @ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_SINGLETON) 52 | @DirtiesContext 53 | public class EnableHazelcastRepositoriesIT { 54 | 55 | @Autowired 56 | PersonRepository repo; 57 | 58 | @Test 59 | public void shouldEnableKeyValueRepositoryCorrectly() { 60 | 61 | assertThat(repo, notNullValue()); 62 | 63 | Person person = new Person(); 64 | person.setFirstname("foo"); 65 | repo.save(person); 66 | 67 | List result = repo.findByFirstname("foo"); 68 | 69 | assertThat(result, hasSize(1)); 70 | assertThat(result.get(0).getFirstname(), is("foo")); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/test/utils/repository/custom/MyTitleRepositoryFactoryBean.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.repository.custom; 18 | 19 | import com.hazelcast.core.HazelcastInstance; 20 | import org.springframework.data.hazelcast.repository.support.HazelcastRepositoryFactoryBean; 21 | import org.springframework.data.keyvalue.core.KeyValueOperations; 22 | import org.springframework.data.repository.Repository; 23 | import org.springframework.data.repository.query.RepositoryQuery; 24 | import org.springframework.data.repository.query.parser.AbstractQueryCreator; 25 | 26 | import javax.annotation.Resource; 27 | import java.io.Serializable; 28 | 29 | /** 30 | *

Factory bean for creating instances of {@link MyTitleRepository}, 31 | * being {@link MovieRepository} and {@link SongRepository}. 32 | *

33 | * 34 | * @param Repository type 35 | * @param Domain object type 36 | * @param Key of domain object type 37 | * @author Neil Stevenson 38 | */ 39 | public class MyTitleRepositoryFactoryBean, S, ID extends Serializable> 40 | extends HazelcastRepositoryFactoryBean { 41 | @Resource 42 | private HazelcastInstance hazelcastInstance; 43 | 44 | /* 45 | * Creates a new {@link MyTitleRepositoryFactoryBean} for the given repository interface. 46 | */ 47 | public MyTitleRepositoryFactoryBean(Class repositoryInterface) { 48 | super(repositoryInterface); 49 | } 50 | 51 | /* Create a specialised repository factory. 52 | * 53 | * (non-Javadoc) 54 | * @see org.springframework.data.hazelcast.repository.support.HazelcastRepositoryFactoryBean#createRepositoryFactory(org 55 | * .springframework.data.keyvalue.core.KeyValueOperations, java.lang.Class, java.lang.Class) 56 | */ 57 | @Override 58 | protected MyTitleRepositoryFactory createRepositoryFactory(KeyValueOperations operations, 59 | Class> queryCreator, 60 | Class repositoryQueryType) { 61 | 62 | return new MyTitleRepositoryFactory(operations, queryCreator, hazelcastInstance); 63 | } 64 | 65 | } 66 | 67 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/topology/ClientServerIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package org.springframework.data.hazelcast.topology; 18 | 19 | import com.hazelcast.query.Predicate; 20 | import com.hazelcast.query.Predicates; 21 | import org.junit.Test; 22 | import org.springframework.test.context.ActiveProfiles; 23 | import test.utils.TestConstants; 24 | import test.utils.domain.Person; 25 | 26 | import java.util.Set; 27 | 28 | import static org.hamcrest.Matchers.equalTo; 29 | import static org.hamcrest.Matchers.notNullValue; 30 | import static org.junit.Assert.assertThat; 31 | 32 | /** 33 | *

34 | * Run the {@link AbstractTopologyIT} tests with the client-server profile. 35 | *

36 | *

37 | * Spring Data Hazelcast uses the client, so the tests examine the server content to confirm client operations are sent 38 | * there. 39 | *

40 | * 41 | * @author Neil Stevenson 42 | */ 43 | @ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_CLIENT_SERVER) 44 | public class ClientServerIT 45 | extends AbstractTopologyIT { 46 | 47 | /* Test data loaded into the client should exist on the 48 | * server. 49 | */ 50 | @Test 51 | public void notJavaDuke() { 52 | String FIRST_NAME_IS_JOHN = "John"; 53 | String LAST_NAME_IS_WAYNE = "Wayne"; 54 | String NINETEEN_SIXTY_NINE = "1969"; 55 | 56 | Predicate predicate = Predicates 57 | .and(Predicates.equal("firstname", FIRST_NAME_IS_JOHN), Predicates.equal("lastname", LAST_NAME_IS_WAYNE)); 58 | 59 | // Force operation to server's content, not remote 60 | Set localKeySet = super.server_personMap.localKeySet((Predicate) predicate); 61 | 62 | assertThat("Entry exists", localKeySet.size(), equalTo(1)); 63 | String key = localKeySet.iterator().next(); 64 | 65 | assertThat("Correct key", key, equalTo(NINETEEN_SIXTY_NINE)); 66 | 67 | Person person = super.server_personMap.get(key); 68 | assertThat("Not invalidated", person, notNullValue()); 69 | assertThat("@Id matches key", person.getId(), equalTo(key)); 70 | assertThat("First name", person.getFirstname(), equalTo(FIRST_NAME_IS_JOHN)); 71 | assertThat("Last name", person.getLastname(), equalTo(LAST_NAME_IS_WAYNE)); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/test/utils/domain/MyTitle.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.domain; 18 | 19 | import org.springframework.data.annotation.Id; 20 | 21 | import java.io.Serializable; 22 | 23 | /** 24 | *

25 | * An abstract base clase for key-value objects that have a string 26 | * key and another string field. 27 | *

28 | * 29 | * @author Neil Stevenson 30 | * @see {@link Movie} 31 | * @see {@link Song} 32 | */ 33 | public abstract class MyTitle 34 | implements Comparable, Serializable { 35 | private static final long serialVersionUID = 1L; 36 | 37 | @Id 38 | private String id; 39 | private String title; 40 | 41 | public String getId() { 42 | return id; 43 | } 44 | 45 | public void setId(String id) { 46 | this.id = id; 47 | } 48 | 49 | public String getTitle() { 50 | return title; 51 | } 52 | 53 | public void setTitle(String title) { 54 | this.title = title; 55 | } 56 | 57 | @Override 58 | public int hashCode() { 59 | final int prime = 31; 60 | int result = 1; 61 | result = prime * result + ((id == null) ? 0 : id.hashCode()); 62 | result = prime * result + ((title == null) ? 0 : title.hashCode()); 63 | return result; 64 | } 65 | 66 | @Override 67 | public boolean equals(Object obj) { 68 | if (this == obj) { 69 | return true; 70 | } 71 | if (obj == null) { 72 | return false; 73 | } 74 | if (getClass() != obj.getClass()) { 75 | return false; 76 | } 77 | MyTitle other = (MyTitle) obj; 78 | if (id == null) { 79 | if (other.id != null) { 80 | return false; 81 | } 82 | } else if (!id.equals(other.id)) { 83 | return false; 84 | } 85 | if (title == null) { 86 | if (other.title != null) { 87 | return false; 88 | } 89 | } else if (!title.equals(other.title)) { 90 | return false; 91 | } 92 | return true; 93 | } 94 | 95 | // Sort by title only 96 | @Override 97 | public int compareTo(MyTitle that) { 98 | return this.title.compareTo(that.getTitle()); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/test/java/test/utils/repository/custom/MyTitleRepositoryFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.repository.custom; 18 | 19 | import com.hazelcast.core.HazelcastInstance; 20 | import org.springframework.data.hazelcast.repository.support.HazelcastRepositoryFactory; 21 | import org.springframework.data.keyvalue.core.KeyValueOperations; 22 | import org.springframework.data.repository.core.EntityInformation; 23 | import org.springframework.data.repository.core.RepositoryInformation; 24 | import org.springframework.data.repository.core.RepositoryMetadata; 25 | import org.springframework.data.repository.query.parser.AbstractQueryCreator; 26 | 27 | import java.io.Serializable; 28 | 29 | /** 30 | *

Factory for creating instances of {@link MyTitleRepository}, 31 | * being {@link MovieRepository} and {@link SongRepository}. 32 | *

33 | * 34 | * @author Neil Stevenson 35 | */ 36 | public class MyTitleRepositoryFactory 37 | extends HazelcastRepositoryFactory { 38 | 39 | private KeyValueOperations keyValueOperations; 40 | 41 | /* Delegate creation to super, but capture the KeyValueOperations 42 | * object for later use. 43 | */ 44 | public MyTitleRepositoryFactory(KeyValueOperations keyValueOperations, 45 | Class> queryCreator, 46 | HazelcastInstance hazelcastInstance) { 47 | super(keyValueOperations, queryCreator, hazelcastInstance); 48 | this.keyValueOperations = keyValueOperations; 49 | } 50 | 51 | /* Create an implementation using captured KeyValueOperations 52 | * and the domain class metadata. 53 | * 54 | * (non-Javadoc) 55 | * @see org.springframework.data.keyvalue.repository.support.KeyValueRepositoryFactory#getTargetRepository(org 56 | * .springframework.data.repository.core.RepositoryInformation) 57 | */ 58 | @SuppressWarnings({"unchecked", "rawtypes"}) 59 | protected Object getTargetRepository(RepositoryInformation repositoryInformation) { 60 | EntityInformation entityInformation = getEntityInformation(repositoryInformation.getDomainType()); 61 | return new MyTitleRepositoryImpl(entityInformation, this.keyValueOperations); 62 | } 63 | 64 | protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { 65 | return MyTitleRepository.class; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/support/StringBasedHazelcastRepositoryQuery.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.support; 17 | 18 | import com.hazelcast.core.HazelcastInstance; 19 | import com.hazelcast.map.IMap; 20 | import com.hazelcast.query.impl.predicates.SqlPredicate; 21 | import org.springframework.data.repository.query.QueryMethod; 22 | import org.springframework.data.repository.query.RepositoryQuery; 23 | 24 | import java.util.Collection; 25 | import java.util.stream.Collectors; 26 | 27 | /** 28 | * {@link RepositoryQuery} using String based {@link SqlPredicate} to query Hazelcast Cluster. 29 | */ 30 | public class StringBasedHazelcastRepositoryQuery 31 | implements RepositoryQuery { 32 | 33 | private final HazelcastQueryMethod queryMethod; 34 | private final String keySpace; 35 | private final HazelcastInstance hazelcastInstance; 36 | 37 | public StringBasedHazelcastRepositoryQuery(HazelcastQueryMethod queryMethod, HazelcastInstance hazelcastInstance) { 38 | this.queryMethod = queryMethod; 39 | this.keySpace = queryMethod.getKeySpace(); 40 | this.hazelcastInstance = hazelcastInstance; 41 | } 42 | 43 | @Override 44 | public Object execute(Object[] parameters) { 45 | String queryStringTemplate = queryMethod.getAnnotatedQuery(); 46 | String queryString = String.format(queryStringTemplate, formatParameters(parameters)); 47 | SqlPredicate sqlPredicate = new SqlPredicate(queryString); 48 | return getMap(keySpace).values(sqlPredicate); 49 | } 50 | 51 | private Object[] formatParameters(Object[] parameters) { 52 | Object[] result = new Object[parameters.length]; 53 | for (int i = 0; i < parameters.length; i++) { 54 | if (parameters[i] instanceof Collection) { 55 | result[i] = formatCollection((Collection) parameters[i]); 56 | } else { 57 | result[i] = parameters[i]; 58 | } 59 | } 60 | return result; 61 | } 62 | 63 | private static String formatCollection(Collection collection) { 64 | return String.format("(%s)", collection.stream().map(Object::toString).collect(Collectors.joining(","))); 65 | } 66 | 67 | private IMap getMap(String keySpace) { 68 | return hazelcastInstance.getMap(keySpace); 69 | } 70 | 71 | @Override 72 | public QueryMethod getQueryMethod() { 73 | return queryMethod; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/repository/query/HazelcastPropertyComparatorTest.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.hazelcast.repository.query; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.AbstractMap; 6 | import java.util.Map.Entry; 7 | 8 | import static org.junit.Assert.assertEquals; 9 | 10 | public class HazelcastPropertyComparatorTest { 11 | 12 | private final HazelcastPropertyComparator propertyComparator = new HazelcastPropertyComparator("value", true); 13 | 14 | @Test 15 | public void testNaturalOrder() { 16 | TestData testData1 = new TestData(1); 17 | TestData testData2 = new TestData(2); 18 | Entry entry1 = entryOf("testData1", testData1); 19 | Entry entry2 = entryOf("testData2", testData2); 20 | assertEquals(-1, propertyComparator.compare(entry1, entry2)); 21 | assertEquals(1, propertyComparator.compare(entry2, entry1)); 22 | } 23 | 24 | @Test 25 | public void compareTwoNullProperties() { 26 | TestData testData1 = new TestData(null); 27 | TestData testData2 = new TestData(null); 28 | Entry nullField1 = entryOf("testData1", testData1); 29 | Entry nullField2 = entryOf("testData2", testData2); 30 | assertEquals(0, propertyComparator.compare(nullField1, nullField2)); 31 | assertEquals(0, propertyComparator.compare(nullField2, nullField1)); 32 | } 33 | 34 | @Test 35 | public void compareNullPropertyWithNonNullProperty() { 36 | TestData testData1 = new TestData(null); 37 | TestData testData2 = new TestData(2); 38 | Entry nullField = entryOf("testData1", testData1); 39 | Entry notNullField = entryOf("testData2", testData2); 40 | assertEquals(1, propertyComparator.compare(nullField, notNullField)); 41 | assertEquals(-1, propertyComparator.compare(notNullField, nullField)); 42 | } 43 | 44 | @Test 45 | public void compareNotComparableProperties() { 46 | TestData testData1 = new TestData(new TestData(1)); 47 | TestData testData2 = new TestData(2); 48 | TestData testData3 = new TestData(new TestData(3)); 49 | Entry entry1NotComparable = entryOf("testData1", testData1); 50 | Entry entry2Comparable = entryOf("testData2", testData2); 51 | Entry entry3NotComparable = entryOf("testData3", testData3); 52 | assertEquals(0, propertyComparator.compare(entry1NotComparable, entry2Comparable)); 53 | assertEquals(0, propertyComparator.compare(entry2Comparable, entry1NotComparable)); 54 | assertEquals(0, propertyComparator.compare(entry1NotComparable, entry3NotComparable)); 55 | } 56 | 57 | private static Entry entryOf(K key, V value) { 58 | return new AbstractMap.SimpleEntry<>(key, value); 59 | } 60 | 61 | private static class TestData { 62 | private final Object value; 63 | 64 | public TestData(Object value) { 65 | this.value = value; 66 | } 67 | 68 | public Object getValue() { 69 | return value; 70 | } 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastSortAccessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.query; 17 | 18 | import org.springframework.data.domain.Sort; 19 | import org.springframework.data.domain.Sort.NullHandling; 20 | import org.springframework.data.domain.Sort.Order; 21 | import org.springframework.data.keyvalue.core.SortAccessor; 22 | import org.springframework.data.keyvalue.core.query.KeyValueQuery; 23 | 24 | import java.util.Comparator; 25 | import java.util.Map.Entry; 26 | 27 | /** 28 | *

29 | * Implements sorting for Hazelcast repository queries. 30 | *

31 | *

32 | * Although {@code SpelPropertyComparator} would do most of the work, this is not serializable so cannot work in a 33 | * cluster. Also, do not wish to assume anything other than Hazelcast classes are available on remote nodes. 34 | *

35 | * 36 | * @author Neil Stevenson 37 | */ 38 | public class HazelcastSortAccessor 39 | implements SortAccessor>> { 40 | 41 | /** 42 | *

43 | * Sort on a sequence of fields, possibly none. 44 | *

45 | * 46 | * @param query If not null, will contain one of more {@link Sort.Order} objects. 47 | * @return A sequence of comparators or {@code null} 48 | */ 49 | public Comparator> resolve(KeyValueQuery query) { 50 | 51 | if (query == null || query.getSort() == Sort.unsorted()) { 52 | return null; 53 | } 54 | 55 | Comparator hazelcastPropertyComparator = null; 56 | 57 | for (Order order : query.getSort()) { 58 | 59 | if (order.getProperty().indexOf('.') > -1) { 60 | throw new UnsupportedOperationException("Embedded fields not implemented: " + order); 61 | } 62 | 63 | if (order.isIgnoreCase()) { 64 | throw new UnsupportedOperationException("Ignore case not implemented: " + order); 65 | } 66 | 67 | if (NullHandling.NATIVE != order.getNullHandling()) { 68 | throw new UnsupportedOperationException("Null handling not implemented: " + order); 69 | } 70 | 71 | if (hazelcastPropertyComparator == null) { 72 | hazelcastPropertyComparator = new HazelcastPropertyComparator(order.getProperty(), 73 | order.isAscending()); 74 | } else { 75 | hazelcastPropertyComparator = hazelcastPropertyComparator.thenComparing( 76 | new HazelcastPropertyComparator(order.getProperty(), 77 | order.isAscending())); 78 | } 79 | } 80 | 81 | return hazelcastPropertyComparator; 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/HazelcastKeyValueAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast; 17 | 18 | import com.hazelcast.core.HazelcastInstance; 19 | import com.hazelcast.map.IMap; 20 | import org.springframework.data.keyvalue.core.AbstractKeyValueAdapter; 21 | import org.springframework.data.keyvalue.core.ForwardingCloseableIterator; 22 | import org.springframework.data.util.CloseableIterator; 23 | import org.springframework.util.Assert; 24 | 25 | import java.util.Iterator; 26 | import java.util.Map; 27 | import java.util.Map.Entry; 28 | 29 | /** 30 | * @author Christoph Strobl 31 | * @author Neil Stevenson 32 | * @author Viacheslav Petriaiev 33 | */ 34 | public class HazelcastKeyValueAdapter 35 | extends AbstractKeyValueAdapter { 36 | 37 | private HazelcastInstance hzInstance; 38 | 39 | public HazelcastKeyValueAdapter(HazelcastInstance hzInstance) { 40 | super(new HazelcastQueryEngine()); 41 | Assert.notNull(hzInstance, "hzInstance must not be 'null'."); 42 | this.hzInstance = hzInstance; 43 | } 44 | 45 | public void setHzInstance(HazelcastInstance hzInstance) { 46 | this.hzInstance = hzInstance; 47 | } 48 | 49 | @Override 50 | public Object put(Object id, Object item, String keyspace) { 51 | Assert.notNull(id, "Id must not be 'null' for adding."); 52 | Assert.notNull(item, "Item must not be 'null' for adding."); 53 | 54 | return getMap(keyspace).put(id, item); 55 | } 56 | 57 | @Override 58 | public boolean contains(Object id, String keyspace) { 59 | return getMap(keyspace).containsKey(id); 60 | } 61 | 62 | @Override 63 | public Object get(Object id, String keyspace) { 64 | return getMap(keyspace).get(id); 65 | } 66 | 67 | @Override 68 | public Object delete(Object id, String keyspace) { 69 | return getMap(keyspace).remove(id); 70 | } 71 | 72 | @Override 73 | public Iterable getAllOf(String keyspace) { 74 | return getMap(keyspace).values(); 75 | } 76 | 77 | @Override 78 | public void deleteAllOf(String keyspace) { 79 | getMap(keyspace).clear(); 80 | } 81 | 82 | @Override 83 | public void clear() { 84 | this.hzInstance.shutdown(); 85 | } 86 | 87 | protected IMap getMap(final String keyspace) { 88 | return hzInstance.getMap(keyspace); 89 | } 90 | 91 | @Override 92 | public void destroy() { 93 | this.clear(); 94 | } 95 | 96 | @Override 97 | public long count(String keyspace) { 98 | return getMap(keyspace).size(); 99 | } 100 | 101 | @Override 102 | public CloseableIterator> entries(String keyspace) { 103 | Iterator> iterator = this.getMap(keyspace).entrySet().iterator(); 104 | return new ForwardingCloseableIterator<>(iterator); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Data Hazelcast 2 | 3 | GitHub Actions status 4 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.hazelcast/spring-data-hazelcast/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.hazelcast/spring-data-hazelcast) 5 | 6 | The primary goal of the [Spring Data](http://projects.spring.io/spring-data/) is to make it easier to build Spring-powered applications that use new data access technologies. This module provides integration with [Hazelcast](http://hazelcast.com). 7 | 8 | # Examples 9 | 10 | For examples on using Spring Data Hazelcast, see dedicated Code Samples: [spring-data-hazelcast-chemistry-sample](https://github.com/hazelcast/hazelcast-code-samples/tree/master/hazelcast-integration/spring-data-hazelcast-chemistry-sample) and [spring-data-jpa-hazelcast-migration](https://github.com/hazelcast/hazelcast-code-samples/tree/master/hazelcast-integration/spring-data-jpa-hazelcast-migration). 11 | 12 | # Artifacts 13 | 14 | ## Maven 15 | 16 | ```xml 17 | 18 | com.hazelcast 19 | spring-data-hazelcast 20 | ${version} 21 | 22 | ``` 23 | 24 | ## Gradle 25 | 26 | ```groovy 27 | dependencies { 28 | compile 'com.hazelcast:spring-data-hazelcast:${version}' 29 | } 30 | ``` 31 | 32 | # Usage 33 | 34 | ## Spring Configuration 35 | 36 | ```java 37 | @Configuration 38 | @EnableHazelcastRepositories(basePackages={"example.springdata.keyvalue.chemistry"}) // <1> 39 | public class ApplicationConfiguration { 40 | @Bean 41 | HazelcastInstance hazelcastInstance() { // <2> 42 | return Hazelcast.newHazelcastInstance(); 43 | // return HazelcastClient.newHazelcastClient(); 44 | } 45 | } 46 | ``` 47 | 48 | 1. Enables Spring Data magic for Hazelcast. You can specify `basePackages` for component scan. 49 | 2. Instantiates Hazelcast instance (a member or a client) 50 | 51 | ## Repository Definition 52 | 53 | ```java 54 | public interface SpeakerRepository extends HazelcastRepository {} 55 | ``` 56 | 57 | ## Test of Repository 58 | 59 | ```java 60 | @RunWith(SpringJUnit4ClassRunner.class) 61 | @ContextConfiguration(classes = AppConfiguration.class) 62 | public class AppTest { 63 | @Autowired 64 | SpeakerRepository speakerRepository; 65 | 66 | @Test 67 | public void testStart(){ 68 | speakerRepository.findAll(); 69 | } 70 | } 71 | ``` 72 | 73 | # @Query Support 74 | 75 | ## Sample @Query Usages 76 | 77 | ### Query with hardcoded value 78 | 79 | ```java 80 | @Query("firstname=James") 81 | public List peopleWithTheirFirstNameIsJames(); 82 | ``` 83 | 84 | ### Query with one variable 85 | 86 | ```java 87 | @Query("firstname=%s") 88 | public List peopleWithTheirFirstName(String firstName); 89 | ``` 90 | 91 | ### Query with multiple variable values 92 | 93 | ```java 94 | @Query("firstname=%s and lastname=%s") 95 | public List peopleWithFirstAndLastName(String firstName,String lastName); 96 | ``` 97 | 98 | ## Supported Query Keywords 99 | 100 | ``` 101 | True 102 | False 103 | Equal 104 | NotEqual 105 | Before 106 | LessThan 107 | LessThanEqual 108 | After 109 | GreaterThan 110 | GreaterThanEqual 111 | Between 112 | IsNull 113 | IsNotNull 114 | In 115 | NotIn 116 | Containing 117 | NotContaining 118 | StartingWith 119 | EndingWith 120 | Like 121 | NotLike 122 | Regex 123 | Distinct 124 | IsEmpty 125 | ExistsBy 126 | IsWithin 127 | IsNear 128 | ``` 129 | 130 | -------------------------------------------------------------------------------- /src/test/java/test/utils/domain/Person.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.domain; 18 | 19 | import org.springframework.data.annotation.Id; 20 | import org.springframework.data.keyvalue.annotation.KeySpace; 21 | import test.utils.TestConstants; 22 | 23 | import java.io.Serializable; 24 | import java.util.Objects; 25 | 26 | /** 27 | *

28 | * Domain class used for tests, re-factored from inner class in {@link EnableHazelcastRepositoriesIT} for wider use. 29 | *

30 | *

31 | * A simple Pojo for the value part of a key-value store. Although it is not necessary for the value 32 | * object to contain the key, this is done here and the field is indicated with {@code @Id}. 33 | *

34 | *

35 | * Use {@code @KeySpace} to name the map used for storage, "@{code Actors}". 36 | *

37 | * 38 | * @author Christoph Strobl 39 | * @author Oliver Gierke 40 | * @author Neil Stevenson 41 | */ 42 | @KeySpace(TestConstants.PERSON_MAP_NAME) 43 | public class Person 44 | implements Comparable, Serializable { 45 | 46 | private static final long serialVersionUID = 1L; 47 | 48 | @Id 49 | private String id; 50 | private String firstname; 51 | private String lastname; 52 | private boolean isChild = false; 53 | 54 | public String getId() { 55 | return id; 56 | } 57 | 58 | public void setId(String id) { 59 | this.id = id; 60 | } 61 | 62 | public String getFirstname() { 63 | return firstname; 64 | } 65 | 66 | public void setFirstname(String firstname) { 67 | this.firstname = firstname; 68 | } 69 | 70 | public String getLastname() { 71 | return lastname; 72 | } 73 | 74 | public void setLastname(String lastname) { 75 | this.lastname = lastname; 76 | } 77 | 78 | public boolean isChild() { 79 | return isChild; 80 | } 81 | 82 | public void setChild(boolean child) { 83 | isChild = child; 84 | } 85 | 86 | // Sort by lastname then firstname 87 | @Override 88 | public int compareTo(Person that) { 89 | int lastnameCompare = this.lastname.compareTo(that.getLastname()); 90 | return (lastnameCompare != 0 ? lastnameCompare : this.firstname.compareTo(that.getFirstname())); 91 | } 92 | 93 | @Override 94 | public boolean equals(Object o) { 95 | if (this == o) { 96 | return true; 97 | } 98 | if (o == null || getClass() != o.getClass()) { 99 | return false; 100 | } 101 | Person person = (Person) o; 102 | return isChild == person.isChild && Objects.equals(id, person.id) && Objects.equals(firstname, person.firstname) 103 | && Objects.equals(lastname, person.lastname); 104 | } 105 | 106 | @Override 107 | public int hashCode() { 108 | return Objects.hash(id, firstname, lastname, isChild); 109 | } 110 | 111 | @Override 112 | public String toString() { 113 | return "Person{" + "id='" + id + '\'' + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' 114 | + ", isChild=" + isChild + '}'; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/maven,intellij,java,eclipse 3 | 4 | ### Maven ### 5 | target/ 6 | pom.xml.tag 7 | pom.xml.releaseBackup 8 | pom.xml.versionsBackup 9 | pom.xml.next 10 | release.properties 11 | dependency-reduced-pom.xml 12 | buildNumber.properties 13 | .mvn/timing.properties 14 | 15 | 16 | ### Intellij ### 17 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 18 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 19 | 20 | # User-specific stuff: 21 | .idea/workspace.xml 22 | .idea/tasks.xml 23 | .idea/dictionaries 24 | .idea/vcs.xml 25 | .idea/jsLibraryMappings.xml 26 | 27 | # Sensitive or high-churn files: 28 | .idea/dataSources.ids 29 | .idea/dataSources.xml 30 | .idea/dataSources.local.xml 31 | .idea/sqlDataSources.xml 32 | .idea/dynamic.xml 33 | .idea/uiDesigner.xml 34 | 35 | # Gradle: 36 | .idea/gradle.xml 37 | .idea/libraries 38 | 39 | # Mongo Explorer plugin: 40 | .idea/mongoSettings.xml 41 | 42 | ## File-based project format: 43 | *.iws 44 | 45 | ## Plugin-specific files: 46 | 47 | # IntelliJ 48 | /out/ 49 | 50 | # mpeltonen/sbt-idea plugin 51 | .idea_modules/ 52 | 53 | # JIRA plugin 54 | atlassian-ide-plugin.xml 55 | 56 | # Crashlytics plugin (for Android Studio and IntelliJ) 57 | com_crashlytics_export_strings.xml 58 | crashlytics.properties 59 | crashlytics-build.properties 60 | fabric.properties 61 | 62 | ### Intellij Patch ### 63 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 64 | 65 | # *.iml 66 | # modules.xml 67 | # .idea/misc.xml 68 | # *.ipr 69 | 70 | 71 | ### Eclipse ### 72 | 73 | .metadata 74 | bin/ 75 | tmp/ 76 | *.tmp 77 | *.bak 78 | *.swp 79 | *~.nib 80 | local.properties 81 | .settings/ 82 | .loadpath 83 | .recommenders 84 | 85 | # Eclipse Core 86 | .project 87 | 88 | # External tool builders 89 | .externalToolBuilders/ 90 | 91 | # Locally stored "Eclipse launch configurations" 92 | *.launch 93 | 94 | # PyDev specific (Python IDE for Eclipse) 95 | *.pydevproject 96 | 97 | # CDT-specific (C/C++ Development Tooling) 98 | .cproject 99 | 100 | # JDT-specific (Eclipse Java Development Tools) 101 | .classpath 102 | 103 | # Java annotation processor (APT) 104 | .factorypath 105 | 106 | # PDT-specific (PHP Development Tools) 107 | .buildpath 108 | 109 | # sbteclipse plugin 110 | .target 111 | 112 | # Tern plugin 113 | .tern-project 114 | 115 | # TeXlipse plugin 116 | .texlipse 117 | 118 | # STS (Spring Tool Suite) 119 | .springBeans 120 | 121 | # Code Recommenders 122 | .recommenders/ 123 | 124 | 125 | ### Java ### 126 | *.class 127 | 128 | # Mobile Tools for Java (J2ME) 129 | .mtj.tmp/ 130 | 131 | # Package Files # 132 | *.jar 133 | *.war 134 | *.ear 135 | 136 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 137 | hs_err_pid* 138 | 139 | # Created by https://www.gitignore.io/api/intellij 140 | 141 | ### Intellij ### 142 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 143 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 144 | 145 | # User-specific stuff: 146 | .idea/workspace.xml 147 | .idea/tasks.xml 148 | .idea/dictionaries 149 | .idea/vcs.xml 150 | .idea/jsLibraryMappings.xml 151 | 152 | # Sensitive or high-churn files: 153 | .idea/dataSources.ids 154 | .idea/dataSources.xml 155 | .idea/dataSources.local.xml 156 | .idea/sqlDataSources.xml 157 | .idea/dynamic.xml 158 | .idea/uiDesigner.xml 159 | 160 | # Gradle: 161 | .idea/gradle.xml 162 | .idea/libraries 163 | 164 | # Mongo Explorer plugin: 165 | .idea/mongoSettings.xml 166 | 167 | ## File-based project format: 168 | *.iws 169 | 170 | ## Plugin-specific files: 171 | 172 | # IntelliJ 173 | /out/ 174 | 175 | # mpeltonen/sbt-idea plugin 176 | .idea_modules/ 177 | 178 | # JIRA plugin 179 | atlassian-ide-plugin.xml 180 | 181 | # Crashlytics plugin (for Android Studio and IntelliJ) 182 | com_crashlytics_export_strings.xml 183 | crashlytics.properties 184 | crashlytics-build.properties 185 | fabric.properties 186 | 187 | ### Intellij Patch ### 188 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 189 | 190 | *.iml 191 | modules.xml 192 | .idea/misc.xml 193 | *.ipr 194 | .idea 195 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/topology/AbstractTopologyIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package org.springframework.data.hazelcast.topology; 18 | 19 | import com.hazelcast.core.Hazelcast; 20 | import com.hazelcast.core.HazelcastInstance; 21 | import com.hazelcast.map.IMap; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | import test.utils.TestConstants; 25 | import test.utils.TestDataHelper; 26 | import test.utils.domain.Person; 27 | import test.utils.repository.standard.PersonRepository; 28 | 29 | import javax.annotation.Resource; 30 | 31 | import static org.hamcrest.Matchers.equalTo; 32 | import static org.hamcrest.Matchers.not; 33 | import static org.hamcrest.Matchers.notNullValue; 34 | import static org.junit.Assert.assertThat; 35 | 36 | /** 37 | *

38 | * A single Hazelcast instance is sufficient for most tests, but does not confirm the operations invoked via Spring Data 39 | * Hazelcast are distributed. 40 | *

41 | *

42 | * Define common tests to prove distribution, for use in more advanced topologies. The nature of these tests is to have 43 | * more than one Hazelcast instance, and to verify object state on an instance other than the one Spring is using. 44 | *

45 | *

46 | * Note that when multiple Hazelcast instances are used, they are all part of the same JVM. This is to simplify the 47 | * co-ordination of process starting and stopping, since networking isn't relevant to the tests. 48 | *

49 | * 50 | * @author Neil Stevenson 51 | */ 52 | public abstract class AbstractTopologyIT 53 | extends TestDataHelper { 54 | 55 | // From the server that isn't Spring's Hazelcast instance 56 | protected IMap server_personMap = null; 57 | 58 | @Resource 59 | private PersonRepository personRepository; 60 | 61 | @Before 62 | public void setUp() { 63 | super.setUp(); 64 | 65 | HazelcastInstance hazelcastServer = null; 66 | 67 | // Look for any instance apart from Spring's one 68 | hazelcastServer = Hazelcast.getHazelcastInstanceByName(TestConstants.SERVER_INSTANCE_NAME); 69 | 70 | assertThat("Server found", hazelcastServer, notNullValue()); 71 | this.server_personMap = hazelcastServer.getMap(TestConstants.PERSON_MAP_NAME); 72 | } 73 | 74 | /* Data manipulated via the other instance should be visible 75 | * to the Spring instance, and vice versa. 76 | */ 77 | @Test 78 | public void obiWanKenobi() { 79 | String NINETEEN_FIFTY_SEVEN = "1957"; 80 | 81 | Person springBefore = this.personRepository.findById(NINETEEN_FIFTY_SEVEN).orElse(null); 82 | 83 | assertThat("1957 winner found", springBefore, notNullValue()); 84 | assertThat("Firstname Alec", springBefore.getFirstname(), equalTo("Alec")); 85 | assertThat("Lastname Guinness", springBefore.getLastname(), equalTo("Guinness")); 86 | 87 | Person person = new Person(); 88 | person.setFirstname("Obi-Wan"); 89 | person.setLastname("Kenobi"); 90 | person.setId(NINETEEN_FIFTY_SEVEN); 91 | 92 | this.server_personMap.put(person.getId(), person); 93 | 94 | Person springAfter = this.personRepository.findById(NINETEEN_FIFTY_SEVEN).orElse(null); 95 | 96 | assertThat("1957 winner found again", springAfter, notNullValue()); 97 | assertThat("Firstname changed", springAfter.getFirstname(), not(equalTo("Alec"))); 98 | assertThat("Lastname changed", springAfter.getLastname(), not(equalTo("Guinness"))); 99 | 100 | this.personRepository.deleteById(NINETEEN_FIFTY_SEVEN); 101 | 102 | assertThat("Obi-Wan has vanished", this.server_personMap.containsKey(NINETEEN_FIFTY_SEVEN), equalTo(false)); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/support/HazelcastRepositoryFactoryBean.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.support; 17 | 18 | import com.hazelcast.core.HazelcastInstance; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.data.keyvalue.core.KeyValueOperations; 21 | import org.springframework.data.keyvalue.repository.support.KeyValueRepositoryFactory; 22 | import org.springframework.data.keyvalue.repository.support.KeyValueRepositoryFactoryBean; 23 | import org.springframework.data.repository.Repository; 24 | import org.springframework.data.repository.query.RepositoryQuery; 25 | import org.springframework.data.repository.query.parser.AbstractQueryCreator; 26 | import org.springframework.util.Assert; 27 | 28 | import java.io.Serializable; 29 | 30 | /** 31 | *

32 | * Extend {@link KeyValueRepositoryFactoryBean} purely to be able to return {@link HazelcastRepositoryFactory} from 33 | * {@link #createRepositoryFactory(KeyValueOperations, Class, Class)} method. 34 | *

35 | *

36 | * This is necessary as the default implementation does not implement querying in a manner consistent with Hazelcast. 37 | * More details of this are in {@link HazelcastRepositoryFactory}. 38 | *

39 | *

40 | * This class is only called as repositories are needed. Rather than try to optimise called methods, allow to delegate 41 | * to {@code super} to ease future changes. 42 | *

43 | *

44 | * The end goal of this bean is for {@link HazelcastPartTreeQuery} to be used for query preparation. 45 | *

46 | * 47 | * @param Repository type, {@link HazelcastRepository} 48 | * @param Domain object class 49 | * @param Domain object key, super expects {@link Serializable} 50 | * @author Neil Stevenson 51 | */ 52 | public class HazelcastRepositoryFactoryBean, S, ID extends Serializable> 53 | extends KeyValueRepositoryFactoryBean { 54 | 55 | @Autowired(required = false) 56 | private HazelcastInstance hazelcastInstance; 57 | 58 | /** 59 | *

60 | * Default Spring Data KeyValue constructor {@link KeyValueRepositoryFactoryBean} 61 | * Creates a new {@link HazelcastRepositoryFactoryBean} for the given repository interface. 62 | *

63 | * 64 | * @param repositoryInterface must not be {@literal null}. 65 | */ 66 | public HazelcastRepositoryFactoryBean(Class repositoryInterface) { 67 | super(repositoryInterface); 68 | } 69 | 70 | /** 71 | *

72 | * Return a {@link HazelcastRepositoryFactory}. 73 | *

74 | *

75 | * {@code super} would return {@link KeyValueRepositoryFactory} which in turn builds {@link KeyValueRepository} 76 | * instances, and these have a private method that implement querying in a manner that does not fit with Hazelcast. 77 | * More details are in {@link HazelcastRepositoryFactory}. 78 | *

79 | * 80 | * @param KeyValueOperations 81 | * @param Query Creator 82 | * @param RepositoryQueryType, not used 83 | * @return A {@link HazelcastRepositoryFactory} that creates {@link HazelcastRepository} instances. 84 | */ 85 | @Override 86 | protected KeyValueRepositoryFactory createRepositoryFactory(KeyValueOperations operations, 87 | Class> queryCreator, 88 | Class repositoryQueryType) { 89 | Assert.state(hazelcastInstance != null, "HazelcastInstance must be set"); 90 | 91 | return new HazelcastRepositoryFactory(operations, queryCreator, hazelcastInstance); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/HazelcastQueryEngine.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast; 17 | 18 | import com.hazelcast.query.PagingPredicate; 19 | import com.hazelcast.query.Predicate; 20 | import com.hazelcast.query.impl.predicates.PagingPredicateImpl; 21 | import org.springframework.data.hazelcast.repository.query.HazelcastCriteriaAccessor; 22 | import org.springframework.data.hazelcast.repository.query.HazelcastSortAccessor; 23 | import org.springframework.data.keyvalue.core.QueryEngine; 24 | import org.springframework.util.Assert; 25 | 26 | import java.util.Collection; 27 | import java.util.Comparator; 28 | import java.util.Map.Entry; 29 | 30 | /** 31 | *

32 | * Implementation of {@code findBy*()} and {@code countBy*{}} queries. 33 | *

34 | * 35 | * @author Christoph Strobl 36 | * @author Neil Stevenson 37 | * @author Viacheslav Petriaiev 38 | */ 39 | public class HazelcastQueryEngine 40 | extends QueryEngine, Comparator>> { 41 | 42 | public HazelcastQueryEngine() { 43 | super(new HazelcastCriteriaAccessor(), new HazelcastSortAccessor()); 44 | } 45 | 46 | /** 47 | *

48 | * Construct the final query predicate for Hazelcast to execute, from the base query plus any paging and sorting. 49 | *

50 | *

51 | * Variations here allow the base query predicate to be omitted, sorting to be omitted, and paging to be omitted. 52 | *

53 | * 54 | * @param criteria Search criteria, null means match everything 55 | * @param sort Possibly null collation 56 | * @param offset Start point of returned page, -1 if not used 57 | * @param rows Size of page, -1 if not used 58 | * @param keyspace The map name 59 | * @return Results from Hazelcast 60 | */ 61 | @Override 62 | public Collection execute(final Predicate criteria, final Comparator> sort, final long offset, 63 | final int rows, final String keyspace) { 64 | 65 | final HazelcastKeyValueAdapter adapter = getAdapter(); 66 | Assert.notNull(adapter, "Adapter must not be 'null'."); 67 | 68 | Predicate predicateToUse = criteria; 69 | @SuppressWarnings({"unchecked", "rawtypes"}) Comparator sortToUse = ((Comparator) (Comparator) sort); 70 | 71 | if (rows > 0) { 72 | PagingPredicate pp = new PagingPredicateImpl(predicateToUse, sortToUse, rows); 73 | long x = offset / rows; 74 | while (x > 0) { 75 | pp.nextPage(); 76 | x--; 77 | } 78 | predicateToUse = pp; 79 | 80 | } else { 81 | if (sortToUse != null) { 82 | predicateToUse = new PagingPredicateImpl(predicateToUse, sortToUse, Integer.MAX_VALUE); 83 | } 84 | } 85 | 86 | if (predicateToUse == null) { 87 | return adapter.getMap(keyspace).values(); 88 | } else { 89 | return adapter.getMap(keyspace).values((Predicate) predicateToUse); 90 | } 91 | 92 | } 93 | 94 | /** 95 | *

96 | * Execute {@code countBy*()} queries against a Hazelcast map. 97 | *

98 | * 99 | * @param criteria Predicate to use, not null 100 | * @param keyspace The map name 101 | * @return Results from Hazelcast 102 | */ 103 | @Override 104 | public long count(final Predicate criteria, final String keyspace) { 105 | final HazelcastKeyValueAdapter adapter = getAdapter(); 106 | Assert.notNull(adapter, "Adapter must not be 'null'."); 107 | return adapter.getMap(keyspace).keySet((Predicate) criteria).size(); 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/support/HazelcastRepositoryFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.support; 17 | 18 | import com.hazelcast.core.HazelcastInstance; 19 | import org.springframework.data.keyvalue.core.KeyValueOperations; 20 | import org.springframework.data.keyvalue.repository.query.SpelQueryCreator; 21 | import org.springframework.data.keyvalue.repository.support.KeyValueRepositoryFactory; 22 | import org.springframework.data.mapping.PersistentEntity; 23 | import org.springframework.data.repository.core.EntityInformation; 24 | import org.springframework.data.repository.query.QueryLookupStrategy; 25 | import org.springframework.data.repository.query.QueryMethodEvaluationContextProvider; 26 | import org.springframework.data.repository.query.parser.AbstractQueryCreator; 27 | import org.springframework.util.Assert; 28 | 29 | import java.util.Optional; 30 | 31 | /** 32 | *

33 | * Hazelcast version of {@link KeyValueRepositoryFactory}, a factory to build {@link HazelcastRepository} instances. 34 | *

35 | *

36 | * The purpose of extending is to ensure that the {@link #getQueryLookupStrategy} method returns a 37 | * {@link HazelcastQueryLookupStrategy} rather than the default. 38 | *

39 | *

40 | * The end goal of this bean is for {@link HazelcastPartTreeQuery} to be used for query preparation. 41 | *

42 | * 43 | * @author Neil Stevenson 44 | */ 45 | public class HazelcastRepositoryFactory 46 | extends KeyValueRepositoryFactory { 47 | 48 | private static final Class DEFAULT_QUERY_CREATOR = SpelQueryCreator.class; 49 | 50 | private final KeyValueOperations keyValueOperations; 51 | private final Class> queryCreator; 52 | private final HazelcastInstance hazelcastInstance; 53 | 54 | /* Mirror functionality of super, to ensure private 55 | * fields are set. 56 | */ 57 | public HazelcastRepositoryFactory(KeyValueOperations keyValueOperations, HazelcastInstance hazelcastInstance) { 58 | this(keyValueOperations, DEFAULT_QUERY_CREATOR, hazelcastInstance); 59 | } 60 | 61 | /* Capture KeyValueOperations and QueryCreator objects after passing to super. 62 | */ 63 | public HazelcastRepositoryFactory(KeyValueOperations keyValueOperations, 64 | Class> queryCreator, 65 | HazelcastInstance hazelcastInstance) { 66 | 67 | super(keyValueOperations, queryCreator); 68 | 69 | this.keyValueOperations = keyValueOperations; 70 | this.queryCreator = queryCreator; 71 | this.hazelcastInstance = hazelcastInstance; 72 | } 73 | 74 | /** 75 | *

76 | * Ensure the mechanism for query evaluation is Hazelcast specific, as the original 77 | * {@link KeyValueRepositoryFactory.KeyValueQueryLookupStrategy} does not function correctly for Hazelcast. 78 | *

79 | */ 80 | @Override 81 | protected Optional getQueryLookupStrategy(QueryLookupStrategy.Key key, 82 | QueryMethodEvaluationContextProvider evaluationContextProvider) { 83 | return Optional.of(new HazelcastQueryLookupStrategy(key, evaluationContextProvider, keyValueOperations, queryCreator, 84 | hazelcastInstance)); 85 | } 86 | 87 | @Override 88 | public EntityInformation getEntityInformation(Class domainClass) { 89 | PersistentEntity entity = (PersistentEntity) keyValueOperations.getMappingContext() 90 | .getPersistentEntity(domainClass); 91 | Assert.notNull(entity, "Entity must not be 'null'."); 92 | return new HazelcastEntityInformation<>(entity); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/config/HazelcastRepositoryConfigurationExtension.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package org.springframework.data.hazelcast.repository.config; 18 | 19 | import org.springframework.beans.factory.config.ConstructorArgumentValues; 20 | import org.springframework.beans.factory.config.RuntimeBeanReference; 21 | import org.springframework.beans.factory.support.AbstractBeanDefinition; 22 | import org.springframework.beans.factory.support.BeanDefinitionRegistry; 23 | import org.springframework.beans.factory.support.RootBeanDefinition; 24 | import org.springframework.data.hazelcast.HazelcastKeyValueAdapter; 25 | import org.springframework.data.keyvalue.core.KeyValueTemplate; 26 | import org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension; 27 | import org.springframework.data.repository.config.RepositoryConfigurationExtension; 28 | import org.springframework.data.repository.config.RepositoryConfigurationSource; 29 | 30 | /** 31 | * Hazelcast-specific {@link RepositoryConfigurationExtension}. 32 | * 33 | * @author Oliver Gierke 34 | * @author Rafal Leszko 35 | */ 36 | class HazelcastRepositoryConfigurationExtension 37 | extends KeyValueRepositoryConfigurationExtension { 38 | 39 | private static final String HAZELCAST_ADAPTER_BEAN_NAME = "hazelcastKeyValueAdapter"; 40 | 41 | /* 42 | * (non-Javadoc) 43 | * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension 44 | * #getModuleName() 45 | */ 46 | @Override 47 | public String getModuleName() { 48 | return "Hazelcast"; 49 | } 50 | 51 | /* 52 | * (non-Javadoc) 53 | * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension 54 | * #getModulePrefix() 55 | */ 56 | @Override 57 | protected String getModulePrefix() { 58 | return "hazelcast"; 59 | } 60 | 61 | /* 62 | * (non-Javadoc) 63 | * @see org.springframework.data.keyvalue.repository.config.KeyValueRepositoryConfigurationExtension 64 | * #getDefaultKeyValueTemplateRef() 65 | */ 66 | @Override 67 | protected String getDefaultKeyValueTemplateRef() { 68 | return "keyValueTemplate"; 69 | } 70 | 71 | @Override 72 | public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConfigurationSource configurationSource) { 73 | // register HazelcastKeyValueAdapter 74 | String hazelcastInstanceRef = configurationSource.getAttribute("hazelcastInstanceRef").get(); 75 | 76 | RootBeanDefinition hazelcastKeyValueAdapterDefinition = new RootBeanDefinition(HazelcastKeyValueAdapter.class); 77 | ConstructorArgumentValues constructorArgumentValuesForHazelcastKeyValueAdapter = new ConstructorArgumentValues(); 78 | constructorArgumentValuesForHazelcastKeyValueAdapter 79 | .addIndexedArgumentValue(0, new RuntimeBeanReference(hazelcastInstanceRef)); 80 | hazelcastKeyValueAdapterDefinition.setConstructorArgumentValues(constructorArgumentValuesForHazelcastKeyValueAdapter); 81 | registerIfNotAlreadyRegistered(() -> hazelcastKeyValueAdapterDefinition, registry, HAZELCAST_ADAPTER_BEAN_NAME, 82 | configurationSource); 83 | 84 | super.registerBeansForRoot(registry, configurationSource); 85 | } 86 | 87 | @Override 88 | protected AbstractBeanDefinition getDefaultKeyValueTemplateBeanDefinition(RepositoryConfigurationSource configurationSource) { 89 | RootBeanDefinition keyValueTemplateDefinition = new RootBeanDefinition(KeyValueTemplate.class); 90 | ConstructorArgumentValues constructorArgumentValuesForKeyValueTemplate = new ConstructorArgumentValues(); 91 | constructorArgumentValuesForKeyValueTemplate 92 | .addIndexedArgumentValue(0, new RuntimeBeanReference(HAZELCAST_ADAPTER_BEAN_NAME)); 93 | constructorArgumentValuesForKeyValueTemplate 94 | .addIndexedArgumentValue(1, new RuntimeBeanReference(MAPPING_CONTEXT_BEAN_NAME)); 95 | 96 | keyValueTemplateDefinition.setConstructorArgumentValues(constructorArgumentValuesForKeyValueTemplate); 97 | 98 | return keyValueTemplateDefinition; 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/query/HazelcastPropertyComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.query; 17 | 18 | import com.hazelcast.query.impl.getters.ReflectionHelper; 19 | 20 | import java.io.Serializable; 21 | import java.lang.invoke.MethodHandle; 22 | import java.lang.invoke.MethodHandles; 23 | import java.lang.invoke.MethodType; 24 | import java.util.Comparator; 25 | import java.util.Map.Entry; 26 | 27 | /** 28 | *

29 | * Implement a limited form of custom comparison between entries. The fields used for the comparison and the 30 | * ascending/descending can be specified at run time. 31 | *

32 | * 33 | * @author Neil Stevenson 34 | */ 35 | public class HazelcastPropertyComparator 36 | implements Comparator>, Serializable { 37 | private static final long serialVersionUID = 1L; 38 | 39 | private static final MethodHandle EXTRACT_VALUE_HAZELCAST_41 = resolveExtractValueHazelcast41(); 40 | private static final MethodHandle EXTRACT_VALUE_HAZELCAST_403 = resolveExtractValueHazelcast403(); 41 | 42 | 43 | private static MethodHandle resolveExtractValueHazelcast41() { 44 | try { 45 | return MethodHandles.lookup().findStatic(ReflectionHelper.class, 46 | "extractValue", MethodType.methodType(Object.class, Object.class, String.class, boolean.class)); 47 | } catch (Throwable ex) { 48 | return null; 49 | } 50 | } 51 | 52 | private static MethodHandle resolveExtractValueHazelcast403() { 53 | try { 54 | return MethodHandles.lookup().findStatic(ReflectionHelper.class, 55 | "extractValue", MethodType.methodType(Object.class, Object.class, String.class)); 56 | } catch (Throwable ex) { 57 | return null; 58 | } 59 | } 60 | 61 | private final String attributeName; 62 | private final int direction; 63 | 64 | public HazelcastPropertyComparator(String attributeName, boolean ascending) { 65 | this.attributeName = attributeName; 66 | this.direction = (ascending ? 1 : -1); 67 | } 68 | 69 | /** 70 | *

71 | * Use Hazelcast's {@code ReflectionHelper} to extract a field in an entry, and use this is in the comparison. 72 | *

73 | * 74 | * @param o1 An entry in a map 75 | * @param o2 Another entry in the map 76 | * @return Comparison result 77 | */ 78 | @SuppressWarnings({"rawtypes", "unchecked"}) 79 | public int compare(Entry o1, Entry o2) { 80 | 81 | try { 82 | 83 | Object o1Field; 84 | Object o2Field; 85 | 86 | if (EXTRACT_VALUE_HAZELCAST_41 == null && EXTRACT_VALUE_HAZELCAST_403 == null) { 87 | throw new IllegalStateException("Could not resolve a ReflectionHelper.extractValue method. Using a non-supported Hazelcast version"); 88 | } 89 | 90 | try { 91 | if (EXTRACT_VALUE_HAZELCAST_403 != null) { 92 | o1Field = EXTRACT_VALUE_HAZELCAST_403.invoke(o1.getValue(), this.attributeName); 93 | o2Field = EXTRACT_VALUE_HAZELCAST_403.invoke(o2.getValue(), this.attributeName); 94 | } else { 95 | o1Field = EXTRACT_VALUE_HAZELCAST_41.invoke(o1.getValue(), this.attributeName, true); 96 | o2Field = EXTRACT_VALUE_HAZELCAST_41.invoke(o2.getValue(), this.attributeName, true); 97 | } 98 | } catch (Throwable throwable) { 99 | throw new IllegalStateException("Could not resolve a ReflectionHelper.extractValue method. Using a non-supported Hazelcast version", throwable); 100 | } 101 | 102 | if (o1Field == o2Field) { 103 | return 0; 104 | } 105 | if (o1Field == null) { 106 | return this.direction; 107 | } 108 | if (o2Field == null) { 109 | return -1 * this.direction; 110 | } 111 | if (o1Field instanceof Comparable && o2Field instanceof Comparable) { 112 | return this.direction * ((Comparable) o1Field).compareTo(o2Field); 113 | } 114 | 115 | } catch (Exception ex) { 116 | return 0; 117 | } 118 | 119 | return 0; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/support/HazelcastQueryLookupStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.support; 17 | 18 | import com.hazelcast.core.HazelcastInstance; 19 | import org.springframework.data.hazelcast.repository.query.HazelcastPartTreeQuery; 20 | import org.springframework.data.keyvalue.core.KeyValueOperations; 21 | import org.springframework.data.projection.ProjectionFactory; 22 | import org.springframework.data.repository.core.NamedQueries; 23 | import org.springframework.data.repository.core.RepositoryMetadata; 24 | import org.springframework.data.repository.query.QueryLookupStrategy; 25 | import org.springframework.data.repository.query.QueryMethodEvaluationContextProvider; 26 | import org.springframework.data.repository.query.RepositoryQuery; 27 | import org.springframework.data.repository.query.parser.AbstractQueryCreator; 28 | import org.springframework.util.Assert; 29 | 30 | import java.lang.reflect.Method; 31 | 32 | /** 33 | *

34 | * Ensures {@link HazelcastPartTreeQuery} is used for query preparation rather than {@link KeyValuePartTreeQuery} or 35 | * other alternatives. 36 | *

37 | * 38 | * @author Neil Stevenson 39 | */ 40 | public class HazelcastQueryLookupStrategy 41 | implements QueryLookupStrategy { 42 | 43 | private final QueryMethodEvaluationContextProvider evaluationContextProvider; 44 | private final KeyValueOperations keyValueOperations; 45 | private final Class> queryCreator; 46 | private final HazelcastInstance hazelcastInstance; 47 | 48 | /** 49 | *

50 | * Required constructor, capturing arguments for use in {@link #resolveQuery}. 51 | *

52 | *

53 | * Assertions copied from {@link KayValueRepositoryFactory.KeyValueQUeryLookupStrategy} which this class essentially 54 | * duplicates. 55 | *

56 | * 57 | * @param key Not used 58 | * @param evaluationContextProvider For evaluation of query expressions 59 | * @param keyValueOperations Bean to use for Key/Value operations on Hazelcast repos 60 | * @param queryCreator Likely to be {@link HazelcastQueryCreator} 61 | * @param hazelcastInstance Instance of Hazelcast 62 | */ 63 | public HazelcastQueryLookupStrategy(QueryLookupStrategy.Key key, 64 | QueryMethodEvaluationContextProvider evaluationContextProvider, 65 | KeyValueOperations keyValueOperations, 66 | Class> queryCreator, 67 | HazelcastInstance hazelcastInstance) { 68 | 69 | Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!"); 70 | Assert.notNull(keyValueOperations, "KeyValueOperations must not be null!"); 71 | Assert.notNull(queryCreator, "Query creator type must not be null!"); 72 | Assert.notNull(hazelcastInstance, "HazelcastInstance must not be null!"); 73 | 74 | this.evaluationContextProvider = evaluationContextProvider; 75 | this.keyValueOperations = keyValueOperations; 76 | this.queryCreator = queryCreator; 77 | this.hazelcastInstance = hazelcastInstance; 78 | } 79 | 80 | /** 81 | *

82 | * Use {@link HazelcastPartTreeQuery} for resolving queries against Hazelcast repositories. 83 | *

84 | * 85 | * @param Method, the query method 86 | * @param RepositoryMetadata, not used 87 | * @param ProjectionFactory, not used 88 | * @param NamedQueries, not used 89 | * @return A mechanism for querying Hazelcast repositories 90 | */ 91 | public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory projectionFactory, 92 | NamedQueries namedQueries) { 93 | 94 | HazelcastQueryMethod queryMethod = new HazelcastQueryMethod(method, metadata, projectionFactory); 95 | 96 | if (queryMethod.hasAnnotatedQuery()) { 97 | return new StringBasedHazelcastRepositoryQuery(queryMethod, hazelcastInstance); 98 | } 99 | 100 | return new HazelcastPartTreeQuery(queryMethod, evaluationContextProvider, this.keyValueOperations, this.queryCreator); 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/query/GeoPredicate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.query; 17 | 18 | import static com.hazelcast.query.impl.IndexUtils.canonicalizeAttribute; 19 | 20 | import java.util.Map; 21 | 22 | import org.springframework.data.geo.Distance; 23 | import org.springframework.data.geo.Metric; 24 | import org.springframework.data.geo.Metrics; 25 | import org.springframework.data.geo.Point; 26 | 27 | import com.hazelcast.query.Predicate; 28 | import com.hazelcast.query.impl.Extractable; 29 | /** 30 | * Geo Predicate - Used to calculate near and within queries 31 | *
  • Finds all the Points within the given distance range from source Point. 32 | *
  • Finds all the Points within given Circle. 33 | * 34 | * @param key of map entry 35 | * @param value of map entry 36 | * @author Ulhas R Manekar 37 | */ 38 | public class GeoPredicate 39 | implements Predicate { 40 | 41 | private static final double KM_TO_MILES = 0.621371; 42 | private static final double KM_TO_NEUTRAL = 0.539957; 43 | private static final double R = 6372.8; 44 | 45 | final String attributeName; 46 | final Point queryPoint; 47 | final Distance distance; 48 | 49 | /** 50 | * Constructor accepts the name of the attribute which is of type Point. 51 | * Constructs a new geo predicate on the given point 52 | * @param attribute the name of the attribute in a object within Map which is of type Point. 53 | * @param point the source point from where the distance is calculated. 54 | * @param distance the Distance object with value and unit of distance. 55 | */ 56 | public GeoPredicate(String attribute, Point point, Distance distance) { 57 | this.attributeName = canonicalizeAttribute(attribute); 58 | this.queryPoint = point; 59 | this.distance = distance; 60 | } 61 | 62 | @Override 63 | public boolean apply(Map.Entry mapEntry) { 64 | Object attributeValue = readAttributeValue(mapEntry); 65 | if (attributeValue instanceof Point) { 66 | return compareDistance((Point) attributeValue); 67 | } else { 68 | throw new IllegalArgumentException(String.format("Cannot use %s predicate with attribute other than Point", 69 | getClass().getSimpleName())); 70 | } 71 | } 72 | 73 | private boolean compareDistance(Point point) { 74 | double calculatedDistance = calculateDistance(point.getX(), point.getY(), this.queryPoint.getX(), 75 | this.queryPoint.getY(), this.distance.getMetric()); 76 | return calculatedDistance < this.distance.getValue(); 77 | } 78 | 79 | /** 80 | * This method users Haversine formula to calculate the distance between two points 81 | * Formula is explained here - https://www.movable-type.co.uk/scripts/gis-faq-5.1.html 82 | * Sample Java code is here - https://rosettacode.org/wiki/Haversine_formula#Java 83 | * @param lat1 - Latitude of first point. 84 | * @param lng1 - Longitude of first point. 85 | * @param lat2 - Latitude of second point. 86 | * @param lng2 - Longitude of second point. 87 | * @param metric - metric to specify where its KILOMETERS, MILES or NEUTRAL 88 | * @return 89 | */ 90 | private double calculateDistance(double lat1, double lng1, double lat2, double lng2, Metric metric) { 91 | if ((lat1 == lat2) && (lng1 == lng2)) { 92 | return 0; 93 | } else { 94 | double dLat = Math.toRadians(lat2 - lat1); 95 | double dLon = Math.toRadians(lng2 - lng1); 96 | double lat1Radians = Math.toRadians(lat1); 97 | double lat2Radians = Math.toRadians(lat2); 98 | 99 | double a = Math.pow(Math.sin(dLat / 2), 2) 100 | + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1Radians) * Math.cos(lat2Radians); 101 | double c = 2 * Math.asin(Math.sqrt(a)); 102 | double dist = R * c; 103 | 104 | if (Metrics.MILES.equals(metric)) { 105 | dist = dist * KM_TO_MILES; 106 | } else if (Metrics.NEUTRAL.equals(metric)) { 107 | dist = dist * KM_TO_NEUTRAL; 108 | } 109 | 110 | return dist; 111 | } 112 | } 113 | 114 | private Object readAttributeValue(Map.Entry entry) { 115 | Extractable extractable = (Extractable) entry; 116 | return extractable.getAttributeValue(this.attributeName); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/hazelcast/repository/config/EnableHazelcastRepositories.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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.hazelcast.repository.config; 17 | 18 | import org.springframework.beans.factory.FactoryBean; 19 | import org.springframework.context.annotation.ComponentScan.Filter; 20 | import org.springframework.context.annotation.Import; 21 | import org.springframework.data.hazelcast.repository.query.HazelcastQueryCreator; 22 | import org.springframework.data.hazelcast.repository.support.HazelcastRepositoryFactoryBean; 23 | import org.springframework.data.keyvalue.core.KeyValueOperations; 24 | import org.springframework.data.keyvalue.repository.config.QueryCreatorType; 25 | import org.springframework.data.repository.config.DefaultRepositoryBaseClass; 26 | import org.springframework.data.repository.query.QueryLookupStrategy; 27 | import org.springframework.data.repository.query.QueryLookupStrategy.Key; 28 | 29 | import java.lang.annotation.Documented; 30 | import java.lang.annotation.ElementType; 31 | import java.lang.annotation.Inherited; 32 | import java.lang.annotation.Retention; 33 | import java.lang.annotation.RetentionPolicy; 34 | import java.lang.annotation.Target; 35 | 36 | /** 37 | * Annotation to activate Hazelcast repositories. If no base package is configured through either {@link #value()}, 38 | * {@link #basePackages()} or {@link #basePackageClasses()} it will trigger scanning of the package of annotated class. 39 | * 40 | * @author Christoph Strobl 41 | * @author Oliver Gierke 42 | * @author Neil Stevenson 43 | * @author Rafal Leszko 44 | */ 45 | @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) 46 | @Retention(RetentionPolicy.RUNTIME) 47 | @Documented 48 | @Inherited 49 | @Import(HazelcastRepositoriesRegistrar.class) 50 | @QueryCreatorType(HazelcastQueryCreator.class) 51 | public @interface EnableHazelcastRepositories { 52 | 53 | /** 54 | * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.: 55 | * {@code @EnableJpaRepositories("org.my.pkg")} instead of {@code @EnableJpaRepositories(basePackages="org.my.pkg")}. 56 | */ 57 | String[] value() default {}; 58 | 59 | /** 60 | * Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this 61 | * attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names. 62 | */ 63 | String[] basePackages() default {}; 64 | 65 | /** 66 | * Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. The 67 | * package of each class specified will be scanned. Consider creating a special no-op marker class or interface in 68 | * each package that serves no purpose other than being referenced by this attribute. 69 | */ 70 | Class[] basePackageClasses() default {}; 71 | 72 | /** 73 | * Specifies which types are not eligible for component scanning. 74 | */ 75 | Filter[] excludeFilters() default {}; 76 | 77 | /** 78 | * Specifies which types are eligible for component scanning. Further narrows the set of candidate components from 79 | * everything in {@link #basePackages()} to everything in the base packages that matches the given filter or filters. 80 | */ 81 | Filter[] includeFilters() default {}; 82 | 83 | /** 84 | * Returns the postfix to be used when looking up custom repository implementations. Defaults to {@literal Impl}. So 85 | * for a repository named {@code PersonRepository} the corresponding implementation class will be looked up scanning 86 | * for {@code PersonRepositoryImpl}. 87 | * 88 | * @return 89 | */ 90 | String repositoryImplementationPostfix() default "Impl"; 91 | 92 | /** 93 | * Configures the location of where to find the Spring Data named queries properties file. 94 | * 95 | * @return 96 | */ 97 | String namedQueriesLocation() default ""; 98 | 99 | /** 100 | * Returns the key of the {@link QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to 101 | * {@link Key#CREATE_IF_NOT_FOUND}. 102 | * 103 | * @return 104 | */ 105 | Key queryLookupStrategy() default Key.CREATE_IF_NOT_FOUND; 106 | 107 | /** 108 | * Returns the {@link FactoryBean} class to be used for each repository instance. Defaults to 109 | * {@link HazelcastRepositoryFactoryBean}. 110 | * 111 | * @return 112 | */ 113 | Class repositoryFactoryBeanClass() default HazelcastRepositoryFactoryBean.class; 114 | 115 | /** 116 | * Allow custom base classes, for generic behavior shared amongst selected 117 | * repositories. 118 | * 119 | * @return 120 | */ 121 | Class repositoryBaseClass() default DefaultRepositoryBaseClass.class; 122 | 123 | /** 124 | * Configures the name of the {@link KeyValueOperations} bean to be used with the repositories detected. 125 | * 126 | * @return 127 | */ 128 | String keyValueTemplateRef() default "keyValueTemplate"; 129 | 130 | /** 131 | * Configures whether nested repository-interfaces (e.g. defined as inner classes) should be discovered by the 132 | * repositories infrastructure. 133 | */ 134 | boolean considerNestedRepositories() default false; 135 | 136 | /** 137 | * Configures the bean name of the {@link HazelcastInstance} to be used. Defaulted to {@literal hazelcastInstance}. 138 | * 139 | * @return 140 | */ 141 | String hazelcastInstanceRef() default "hazelcastInstance"; 142 | } 143 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/repository/query/HazelcastSortAccessorTest.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.hazelcast.repository.query; 2 | 3 | import com.hazelcast.query.Predicate; 4 | import org.junit.Test; 5 | import org.springframework.data.domain.Sort; 6 | import org.springframework.data.history.RevisionSort; 7 | import org.springframework.data.keyvalue.core.query.KeyValueQuery; 8 | import org.springframework.util.ObjectUtils; 9 | 10 | import java.io.Serializable; 11 | import java.util.*; 12 | 13 | import static org.junit.Assert.*; 14 | 15 | public class HazelcastSortAccessorTest { 16 | 17 | @Test(expected = UnsupportedOperationException.class) 18 | public void testResolvingNonNativeNullHandlingOrderIsUnsupported() { 19 | // given 20 | KeyValueQuery keyValueQuery = new KeyValueQuery<>("^pg~]=P"); 21 | Sort.Order sortOrder1 = Sort.Order.asc("^pg~]=P"); 22 | Sort.Order sortOrder2 = sortOrder1.nullsLast(); 23 | keyValueQuery.setSort(Sort.by(sortOrder1, sortOrder2)); 24 | 25 | HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); 26 | // when 27 | hazelcastSortAccessor.resolve(keyValueQuery); 28 | // Then expect UnsupportedOperationException 29 | } 30 | 31 | @Test(expected = UnsupportedOperationException.class) 32 | public void testResolvingIgnoreCaseOrderIsUnsupported() { 33 | // given 34 | HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); 35 | KeyValueQuery keyValueQuery = new KeyValueQuery<>(RevisionSort.asc()); 36 | Sort.Order sortOrderA = Sort.Order.asc("Cannot resolve nest mates of a latent type description: "); 37 | Sort.Order sortOrderB = sortOrderA.ignoreCase(); 38 | keyValueQuery.setSort(Sort.by(sortOrderA, sortOrderB)); 39 | 40 | // when 41 | hazelcastSortAccessor.resolve(keyValueQuery); 42 | // Then expect UnsupportedOperationException 43 | } 44 | 45 | @Test 46 | public void testResolvingNonEmptyKeyValueQueryReturnsNonNullComparator() { 47 | //given 48 | KeyValueQuery keyValueQuery = new KeyValueQuery<>(RevisionSort.asc()); 49 | 50 | //when 51 | HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); 52 | Comparator> comparator = hazelcastSortAccessor.resolve(keyValueQuery); 53 | 54 | //then 55 | assertNotNull(comparator); 56 | } 57 | 58 | @Test 59 | public void testResolvingEmptyKeyValueQueryReturnsNullComparator() { 60 | //given 61 | KeyValueQuery keyValueQuery = new KeyValueQuery<>(); 62 | 63 | //when 64 | HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); 65 | Comparator> comparator = hazelcastSortAccessor.resolve(keyValueQuery); 66 | 67 | //then 68 | assertNull(comparator); 69 | } 70 | 71 | @Test 72 | public void testResolvingNullKeyValueQueryReturnsNullComparator() { 73 | //given //when 74 | HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); 75 | Comparator> comparator = hazelcastSortAccessor.resolve(null); 76 | //then 77 | assertNull(comparator); 78 | } 79 | 80 | @Test 81 | public void testResolvingMultipleSortOrdersReturnsCompositeComparator() { 82 | //given 83 | KeyValueQuery> query = new KeyValueQuery<>(); 84 | Sort.Order fooOrder = new Sort.Order(Sort.Direction.DESC, "foo"); 85 | Sort.Order barOrder = new Sort.Order(Sort.Direction.DESC, "bar"); 86 | 87 | query.setSort(Sort.by(fooOrder, barOrder)); 88 | 89 | HazelcastSortAccessorTest.Foo testData1 = new HazelcastSortAccessorTest.Foo("zzz", "def"); 90 | HazelcastSortAccessorTest.Foo testData2 = new HazelcastSortAccessorTest.Foo("aaa", "aaa"); 91 | Map.Entry entry1 = entryOf("testData1", testData1); 92 | Map.Entry entry2 = entryOf("testData2", testData2); 93 | 94 | HazelcastSortAccessorTest.Foo testData3 = new HazelcastSortAccessorTest.Foo("aaa", "aaa"); 95 | HazelcastSortAccessorTest.Foo testData4 = new HazelcastSortAccessorTest.Foo("aaa", "def"); 96 | Map.Entry entry3 = entryOf("testData3", testData3); 97 | Map.Entry entry4 = entryOf("testData4", testData4); 98 | 99 | //when 100 | HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); 101 | Comparator> comparator = hazelcastSortAccessor.resolve(query); 102 | 103 | //then 104 | assertNotNull(comparator); 105 | assertTrue(comparator.compare(entry1, entry2) < 0); 106 | assertTrue(comparator.compare(entry2, entry1) > 0); 107 | assertFalse(comparator.compare(entry3, entry4) == 0); 108 | assertTrue((comparator.compare(entry3, entry4) > 0)); 109 | } 110 | 111 | private static Map.Entry entryOf(K key, V value) { 112 | return new AbstractMap.SimpleEntry<>(key, value); 113 | } 114 | 115 | static class Foo 116 | implements Serializable { 117 | 118 | String foo; 119 | String bar; 120 | 121 | public Foo(String foo, String bar) { 122 | this.foo = foo; 123 | this.bar = bar; 124 | } 125 | 126 | @Override 127 | public int hashCode() { 128 | return ObjectUtils.nullSafeHashCode(new Object[]{this.foo, this.bar}); 129 | } 130 | 131 | @Override 132 | public boolean equals(Object obj) { 133 | if (this == obj) { 134 | return true; 135 | } 136 | if (obj == null) { 137 | return false; 138 | } 139 | if (!(obj instanceof HazelcastSortAccessorTest.Foo)) { 140 | return false; 141 | } 142 | HazelcastSortAccessorTest.Foo other = (HazelcastSortAccessorTest.Foo) obj; 143 | return ObjectUtils.nullSafeEquals(this.foo, other.foo) && ObjectUtils.nullSafeEquals(this.bar, other.bar); 144 | } 145 | 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/repository/custom/CustomRepoIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package org.springframework.data.hazelcast.repository.custom; 18 | 19 | import org.junit.Test; 20 | import org.springframework.test.context.ActiveProfiles; 21 | import test.utils.TestConstants; 22 | import test.utils.TestDataHelper; 23 | import test.utils.domain.Movie; 24 | import test.utils.domain.Song; 25 | import test.utils.repository.custom.MovieRepository; 26 | import test.utils.repository.custom.MyTitleRepositoryFactoryBean; 27 | import test.utils.repository.custom.SongRepository; 28 | 29 | import javax.annotation.Resource; 30 | import java.util.Iterator; 31 | import java.util.List; 32 | 33 | import static org.hamcrest.Matchers.containsInAnyOrder; 34 | import static org.hamcrest.Matchers.equalTo; 35 | import static org.hamcrest.Matchers.greaterThan; 36 | import static org.hamcrest.Matchers.hasProperty; 37 | import static org.hamcrest.Matchers.instanceOf; 38 | import static org.hamcrest.Matchers.lessThan; 39 | import static org.hamcrest.Matchers.not; 40 | import static org.hamcrest.Matchers.nullValue; 41 | import static org.junit.Assert.assertThat; 42 | 43 | /** 44 | *

    45 | * Test customized repository functionality. 46 | *

    47 | *

    48 | * {@link MovieRepository} and {@link SongRepository} both extend custom repository 49 | * base class {@link MyTitleRepository}. Test each has inherited custom and unique 50 | * behaviours. 51 | *

    52 | *

    53 | * In addition to package scanning for standard repositories in {@link TestDataHelper}, 54 | * package scanning also constructs custom / non-standard repositories using a 55 | * special factory bean for tests only, {@link MyTitleRepositoryFactoryBean}. 56 | *

    57 | * 58 | * @author Neil Stevenson 59 | */ 60 | @ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_SINGLETON) 61 | public class CustomRepoIT 62 | extends TestDataHelper { 63 | private static final String YEAR_1939 = "1939"; 64 | private static final String YEAR_1959 = "1959"; 65 | private static final String YEAR_1993 = "1993"; 66 | private static final String YEAR_1997 = "1997"; 67 | 68 | @Resource 69 | private MovieRepository movieRepository; 70 | @Resource 71 | private SongRepository songRepository; 72 | 73 | /* Although what we're testing here is that we can execute a generic 74 | * method, may as well be thorough and check the correctness of the 75 | * logic for hyphens and apostrophes. 76 | */ 77 | @Test 78 | public void movieRepositoryGenericBehaviour() { 79 | long countGoneWithTheWind = this.movieRepository.wordsInTitle(YEAR_1939); 80 | long countBenHur = this.movieRepository.wordsInTitle(YEAR_1959); 81 | long countSchindlersList = this.movieRepository.wordsInTitle(YEAR_1993); 82 | long countTitanic = this.movieRepository.wordsInTitle(YEAR_1997); 83 | 84 | assertThat("4 words in 'Gone With The Wind'", countGoneWithTheWind, equalTo(4L)); 85 | assertThat("2 words in 'Ben-Hur'", countBenHur, equalTo(2L)); 86 | assertThat("2 words in 'Schindler's List'", countSchindlersList, equalTo(2L)); 87 | assertThat("1 word in 'Titanic'", countTitanic, equalTo(1L)); 88 | } 89 | 90 | @Test 91 | public void movieRepositorySpecificBehaviour() { 92 | String WORD = "The"; 93 | 94 | int all = 0; 95 | int allWithWord = 0; 96 | 97 | Iterable iterable = this.movieRepository.findAll(); 98 | assertThat("iterable", iterable, not(nullValue())); 99 | Iterator iterator = iterable.iterator(); 100 | 101 | while (iterator.hasNext()) { 102 | Movie movie = iterator.next(); 103 | all++; 104 | if (movie.getTitle().contains(WORD)) { 105 | allWithWord++; 106 | } 107 | } 108 | 109 | assertThat("Some movies found", all, greaterThan(0)); 110 | assertThat(String.format("Some movies found with word '%s' in title title", WORD), allWithWord, greaterThan(0)); 111 | assertThat(String.format("Not all movies found with word '%s' in title title", WORD), allWithWord, lessThan(all)); 112 | 113 | Object result = this.movieRepository.findByTitleLike("%" + WORD + "%"); 114 | 115 | assertThat("Result exists", result, not(nullValue())); 116 | assertThat("Result list", result, instanceOf(List.class)); 117 | 118 | @SuppressWarnings("unchecked") List resultList = (List) result; 119 | 120 | assertThat("Result size", resultList.size(), equalTo(allWithWord)); 121 | } 122 | 123 | @Test 124 | public void songRepositoryGenericBehaviour() { 125 | long count = this.songRepository.wordsInTitle(YEAR_1939); 126 | 127 | assertThat("3 words in 'Over The Rainbow'", count, equalTo(3L)); 128 | } 129 | 130 | @SuppressWarnings("unchecked") 131 | @Test 132 | public void songRepositorySpecificBehaviour() { 133 | Object result = this.songRepository.findByIdLessThan(YEAR_1939); 134 | 135 | assertThat("Result exists", result, not(nullValue())); 136 | assertThat("Result list", result, instanceOf(List.class)); 137 | 138 | List resultList = (List) result; 139 | 140 | assertThat("First song prize was 1934", resultList.size(), equalTo(5)); 141 | 142 | assertThat("1934 through 1938", resultList, 143 | containsInAnyOrder(hasProperty("id", equalTo("1934")), hasProperty("id", equalTo("1935")), 144 | hasProperty("id", equalTo("1936")), hasProperty("id", equalTo("1937")), 145 | hasProperty("id", equalTo("1938")))); 146 | 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/test/java/test/utils/TestDataHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils; 18 | 19 | import com.hazelcast.core.DistributedObject; 20 | import com.hazelcast.core.Hazelcast; 21 | import com.hazelcast.core.HazelcastInstance; 22 | import com.hazelcast.map.IMap; 23 | import org.junit.After; 24 | import org.junit.AfterClass; 25 | import org.junit.Before; 26 | import org.junit.runner.RunWith; 27 | import org.springframework.beans.factory.annotation.Autowired; 28 | import org.springframework.data.geo.Point; 29 | import org.springframework.test.annotation.DirtiesContext; 30 | import org.springframework.test.context.ContextConfiguration; 31 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 32 | 33 | import test.utils.domain.City; 34 | import test.utils.domain.Makeup; 35 | import test.utils.domain.Movie; 36 | import test.utils.domain.Person; 37 | import test.utils.domain.Song; 38 | 39 | import java.util.Collection; 40 | 41 | import static org.hamcrest.Matchers.equalTo; 42 | import static org.hamcrest.Matchers.greaterThan; 43 | import static org.hamcrest.Matchers.instanceOf; 44 | import static org.hamcrest.Matchers.isIn; 45 | import static org.junit.Assert.assertThat; 46 | 47 | /** 48 | *

    49 | * Common processing for integration tests. 50 | *

    51 | *

    52 | * Test data is based around 53 | * the Oscars. 54 | *

    55 | *

    56 | * Load the {@code Movie} {@code IMap} with the Oscar winners for best movies, 57 | * {@code Person} with the Oscar winners for best actor, and {@code Song} 58 | * with the best theme songs. 59 | *

    60 | * 61 | * @author Neil Stevenson 62 | */ 63 | @RunWith(SpringJUnit4ClassRunner.class) 64 | @ContextConfiguration(classes = {InstanceHelper.class}) 65 | @DirtiesContext 66 | public abstract class TestDataHelper { 67 | @Autowired 68 | protected HazelcastInstance hazelcastInstance; 69 | 70 | protected IMap makeupMap; 71 | protected IMap movieMap; 72 | protected IMap personMap; 73 | protected IMap songMap; 74 | protected IMap cityMap; 75 | 76 | /* Use Hazelcast directly, minimise reliance on Spring as the object is 77 | * to test Spring encapsulation of Hazelcast. 78 | */ 79 | @Before 80 | public void setUp() { 81 | assertThat("Correct Hazelcast instance", this.hazelcastInstance.getName(), equalTo(TestConstants.CLIENT_INSTANCE_NAME)); 82 | 83 | checkMapsEmpty("setUp"); 84 | 85 | this.makeupMap = this.hazelcastInstance.getMap(TestConstants.MAKEUP_MAP_NAME); 86 | loadMakeup(this.makeupMap); 87 | 88 | this.movieMap = this.hazelcastInstance.getMap(TestConstants.MOVIE_MAP_NAME); 89 | loadMovie(this.movieMap); 90 | 91 | this.personMap = this.hazelcastInstance.getMap(TestConstants.PERSON_MAP_NAME); 92 | loadPerson(this.personMap); 93 | 94 | this.songMap = this.hazelcastInstance.getMap(TestConstants.SONG_MAP_NAME); 95 | loadSong(this.songMap); 96 | 97 | this.cityMap = this.hazelcastInstance.getMap(TestConstants.CITY_MAP_NAME); 98 | loadCities(this.cityMap); 99 | 100 | checkMapsNotEmpty("setUp"); 101 | 102 | /* As Hazelcast will create objects on demand, check no more are present 103 | * than should be. 104 | */ 105 | Collection distributedObjects = this.hazelcastInstance.getDistributedObjects(); 106 | assertThat("Correct number of distributed objects", distributedObjects.size(), 107 | equalTo(TestConstants.OSCAR_MAP_NAMES.length)); 108 | } 109 | 110 | protected void checkMapsEmpty(String phase) { 111 | for (String mapName : TestConstants.OSCAR_MAP_NAMES) { 112 | IMap iMap = this.hazelcastInstance.getMap(mapName); 113 | assertThat(phase + "(): No test data left behind by previous tests in '" + iMap.getName() + "'", iMap.size(), 114 | equalTo(0)); 115 | } 116 | } 117 | 118 | private void checkMapsNotEmpty(String phase) { 119 | for (String mapName : TestConstants.OSCAR_MAP_NAMES) { 120 | IMap iMap = this.hazelcastInstance.getMap(mapName); 121 | assertThat(phase + "(): Test data has been loaded into '" + iMap.getName() + "'", iMap.size(), greaterThan(0)); 122 | } 123 | } 124 | 125 | private void loadMakeup(IMap akeupMap) { 126 | for (int i = 0; i < TestData.bestMakeUp.length; i++) { 127 | Makeup makeup = new Makeup(); 128 | 129 | makeup.setId(Integer.toString((int) TestData.bestMakeUp[i][0])); 130 | makeup.setFilmTitle(TestData.bestMakeUp[i][1].toString()); 131 | makeup.setArtistOrArtists(TestData.bestMakeUp[i][2].toString()); 132 | 133 | makeupMap.put(makeup.getId(), makeup); 134 | } 135 | } 136 | 137 | private void loadMovie(IMap movieMap) { 138 | for (int i = 0; i < TestData.bestPictures.length; i++) { 139 | Movie movie = new Movie(); 140 | 141 | movie.setId(Integer.toString((int) TestData.bestPictures[i][0])); 142 | movie.setTitle(TestData.bestPictures[i][1].toString()); 143 | 144 | movieMap.put(movie.getId(), movie); 145 | } 146 | } 147 | 148 | private void loadPerson(IMap personMap) { 149 | for (int i = 0; i < TestData.bestActors.length; i++) { 150 | Person person = new Person(); 151 | 152 | person.setId(Integer.toString((int) TestData.bestActors[i][0])); 153 | person.setFirstname(TestData.bestActors[i][1].toString()); 154 | person.setLastname(TestData.bestActors[i][2].toString()); 155 | 156 | personMap.put(person.getId(), person); 157 | } 158 | } 159 | 160 | private void loadSong(IMap songMap) { 161 | for (int i = 0; i < TestData.bestSongs.length; i++) { 162 | Song song = new Song(); 163 | 164 | song.setId(Integer.toString((int) TestData.bestSongs[i][0])); 165 | song.setTitle(TestData.bestSongs[i][1].toString()); 166 | 167 | songMap.put(song.getId(), song); 168 | } 169 | } 170 | 171 | private void loadCities(IMap cityMap) { 172 | for (int i = 0; i < TestData.newYorkCities.length; i++) { 173 | City city = new City(); 174 | 175 | city.setId(Integer.toString((int) TestData.newYorkCities[i][2])); 176 | city.setName(TestData.newYorkCities[i][0].toString()); 177 | final String[] latLng = TestData.newYorkCities[i][1].toString().split(","); 178 | city.setLocation(new Point(Double.parseDouble(latLng[0]), Double.parseDouble(latLng[1]))); 179 | 180 | cityMap.put(city.getId(), city); 181 | } 182 | } 183 | 184 | @After 185 | public void tearDown() { 186 | for (String mapName : TestConstants.OSCAR_MAP_NAMES) { 187 | IMap iMap = this.hazelcastInstance.getMap(mapName); 188 | iMap.clear(); 189 | } 190 | 191 | checkMapsEmpty("tearDown"); 192 | 193 | Collection distributedObjects = this.hazelcastInstance.getDistributedObjects(); 194 | 195 | for (DistributedObject distributedObject : distributedObjects) { 196 | assertThat(distributedObject.getName(), distributedObject, instanceOf(IMap.class)); 197 | assertThat(distributedObject.getName(), isIn(TestConstants.OSCAR_MAP_NAMES)); 198 | } 199 | 200 | assertThat("Correct number of distributed objects", distributedObjects.size(), 201 | equalTo(TestConstants.OSCAR_MAP_NAMES.length)); 202 | 203 | } 204 | 205 | @AfterClass 206 | public static void close() { 207 | Hazelcast.shutdownAll(); 208 | } 209 | } -------------------------------------------------------------------------------- /src/test/java/test/utils/repository/standard/PersonRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils.repository.standard; 18 | 19 | import org.springframework.data.domain.Page; 20 | import org.springframework.data.domain.Pageable; 21 | import org.springframework.data.domain.Slice; 22 | import org.springframework.data.domain.Sort; 23 | import org.springframework.data.hazelcast.repository.HazelcastRepository; 24 | import org.springframework.data.hazelcast.repository.config.EnableHazelcastRepositoriesIT; 25 | import org.springframework.data.hazelcast.repository.query.Query; 26 | import org.springframework.data.repository.query.Param; 27 | import org.springframework.scheduling.annotation.Async; 28 | import org.springframework.util.concurrent.ListenableFuture; 29 | import test.utils.domain.Person; 30 | 31 | import java.util.Collection; 32 | import java.util.List; 33 | import java.util.Optional; 34 | import java.util.concurrent.CompletableFuture; 35 | import java.util.concurrent.Future; 36 | import java.util.stream.Stream; 37 | 38 | /** 39 | *

    40 | * Repository class used for tests, re-factored from inner class in {@link EnableHazelcastRepositoriesIT} for wider use. 41 | *

    42 | *

    43 | * The specified methods are implemented by Spring at run-time, using the method name and parameters to deduce the query 44 | * syntax. 45 | *

    46 | *

    47 | * See {@link org.springframework.data.repository.query.parser.PartTree PartTree} for details of the query syntax. A 48 | * simple example being a concatenation: 49 | *

      50 | *
    • '{@code find}' - return results or result
    • 51 | *
    • [optional] '{@code first}nn' - limit results to the first nn matches
    • 52 | *
    • '{@code By}' - filters follow this token 53 | *
    • [optional] '{@code fieldname}' - select on a field in the {@code Map.Entry.getValue()} 54 | *
    • [optional] '{@code OrderBy}' - sorts follow this token 55 | *
    • [optional] '{@code fieldname}' - select on a field in the {@code Map.Entry.getValue()} 56 | *
    57 | *

    58 | * 59 | * @author Christoph Strobl 60 | * @author Oliver Gierke 61 | * @author Neil Stevenson 62 | */ 63 | public interface PersonRepository 64 | extends HazelcastRepository { 65 | 66 | // Count methods 67 | 68 | public Long countByFirstname(String firstname); 69 | 70 | public Long countByIdLessThanEqual(String id); 71 | 72 | public Long countByLastnameAllIgnoreCase(String lastname); 73 | 74 | public Long countByFirstnameOrLastnameAllIgnoreCase(String firstname, String lastname); 75 | 76 | public Long countByFirstnameAndLastnameAllIgnoreCase(String firstname, String lastname); 77 | 78 | public Long countByIdAfter(String id); 79 | 80 | public Long countByIdBetween(String firstId, String lastId); 81 | 82 | // Find methods 83 | 84 | public Person findByFirstnameOrLastnameIgnoreCase(String firstname, String lastname); 85 | 86 | public Person findByFirstnameIgnoreCaseOrLastname(String firstname, String lastname); 87 | 88 | public Person findByFirstnameOrLastnameAllIgnoreCase(String firstname, String lastname); 89 | 90 | public Person findFirstIdByOrderById(); 91 | 92 | public Person findFirstIdByFirstnameOrderByIdDesc(String firstname); 93 | 94 | public List findByFirstname(String firstname); 95 | 96 | public List findByLastnameIsNull(); 97 | 98 | public List findByIsChildTrue(); 99 | 100 | public List findByLastnameRegex(String regex); 101 | 102 | // Underscores are permitted after field names, improving readability slightly 103 | public List findByFirstname_AndLastname(String firstname, String lastname); 104 | 105 | // Params are positional unless tagged 106 | public List findByFirstnameOrLastname(@Param("lastname") String s1, @Param("firstname") String s2); 107 | 108 | public List findByFirstnameGreaterThan(String firstname); 109 | 110 | public List queryByFirstnameLike(String firstname); 111 | 112 | public List findByFirstnameContains(String firstname); 113 | 114 | public List findByFirstnameContainsAndLastnameStartsWithAllIgnoreCase(String firstname, String lastname); 115 | 116 | public List findByFirstnameOrderById(String firstname); 117 | 118 | public List findByLastnameOrderByIdAsc(String lastname); 119 | 120 | public List findByFirstnameOrderByLastnameDesc(String firstname); 121 | 122 | public List findByLastnameIgnoreCase(String lastname); 123 | 124 | public List findTop3ByOrderByFirstnameAsc(); 125 | 126 | public List findFirst3ByOrderByFirstnameDescLastnameAsc(); 127 | 128 | public List findByFirstnameIn(Collection firstnames); 129 | 130 | public List findByFirstnameEndsWithAndLastnameNotIn(String firstname, Collection lastnames); 131 | 132 | public Stream findFirst4By(); 133 | 134 | public Stream streamByLastnameGreaterThanEqual(String lastname); 135 | 136 | public Stream streamByFirstname(String firstname); 137 | 138 | // Find methods with special parameters 139 | 140 | public List findByFirstname(String firstname, Sort sort); 141 | 142 | public List findByLastnameNotNull(Sort sort); 143 | 144 | public Page findByLastname(String lastname, Pageable pageable); 145 | 146 | public Page findByOrderByLastnameDesc(Pageable pageable); 147 | 148 | public Slice findByIdLike(String pattern, Pageable pageable); 149 | 150 | public Slice findByIdGreaterThanEqualAndFirstnameGreaterThanAndFirstnameLessThanEqual(String id, String firstname1, 151 | String firstname2, 152 | Pageable pageable); 153 | 154 | public Page findAllById(@Param("id") String id, Pageable pageable); 155 | 156 | // Delete methods 157 | 158 | public long deleteByLastname(String firstname); 159 | 160 | public List deleteByFirstname(String firstname); 161 | 162 | // Query methods 163 | 164 | @Query("firstname=James") 165 | public List peopleWithTheirFirstNameIsJames(); 166 | 167 | @Query("firstname=%s") 168 | public List peopleWithTheirFirstName(String firstName); 169 | 170 | @Query("firstname=%s and lastname=%s") 171 | public List peopleWithFirstAndLastName(String firstName, String lastName); 172 | 173 | @Query("lastname like %s") 174 | public List peopleWithLastNameLike(String lastName); 175 | 176 | @Query("lastname in %s") 177 | public List peopleWithLastNameIn(Collection lastNames); 178 | 179 | // Null handling methods 180 | 181 | public Optional getByLastname(String lastname); 182 | 183 | // Async methods 184 | 185 | @Async 186 | Future findOneByFirstname(String firstname); 187 | 188 | @Async 189 | CompletableFuture findOneByLastname(String lastname); 190 | 191 | @Async 192 | ListenableFuture> findByLastname(String lastname); 193 | 194 | //distinct methods 195 | public Long countDistinctByFirstname(String firstname); 196 | 197 | public List findDistinctByFirstname(String firstname); 198 | 199 | public Stream streamDistinctByFirstname(String firstname); 200 | 201 | // exists methods 202 | public boolean existsByFirstname(String firstname); 203 | 204 | //Empty, IsEmpty methods 205 | public List findByLastnameEmpty(); 206 | 207 | public List findByLastnameIsEmpty(); 208 | 209 | //NotEmpty, IsNotEmpty methods 210 | public List findByLastnameNotEmpty(); 211 | 212 | public List findByLastnameIsNotEmpty(); 213 | } 214 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/repository/PagingSortingIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package org.springframework.data.hazelcast.repository; 18 | 19 | import org.junit.Test; 20 | import org.springframework.data.domain.Page; 21 | import org.springframework.data.domain.PageRequest; 22 | import org.springframework.data.domain.Pageable; 23 | import org.springframework.data.domain.Sort; 24 | import org.springframework.data.repository.PagingAndSortingRepository; 25 | import org.springframework.test.context.ActiveProfiles; 26 | import test.utils.TestData; 27 | import test.utils.TestConstants; 28 | import test.utils.TestDataHelper; 29 | import test.utils.domain.Person; 30 | 31 | import javax.annotation.Resource; 32 | import java.util.Iterator; 33 | import java.util.List; 34 | import java.util.Set; 35 | import java.util.TreeSet; 36 | 37 | import static org.hamcrest.Matchers.equalTo; 38 | import static org.hamcrest.Matchers.greaterThanOrEqualTo; 39 | import static org.hamcrest.Matchers.is; 40 | import static org.hamcrest.Matchers.lessThanOrEqualTo; 41 | import static org.hamcrest.Matchers.notNullValue; 42 | import static org.junit.Assert.assertThat; 43 | 44 | /** 45 | *

    46 | * Downcast a {@link HazelcastRepository} into a {@link PagingAndSortingRepository} to test paging and sorting 47 | * additions. 48 | *

    49 | *

    50 | * Where possible, verify the repository against the underlying Hazelcast instance directly. 51 | *

    52 | * 53 | * @author Neil Stevenson 54 | */ 55 | @ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_CLIENT_SERVER) 56 | public class PagingSortingIT 57 | extends TestDataHelper { 58 | 59 | // PersonRepository is really a HazelcastRepository 60 | @Resource 61 | private PagingAndSortingRepository personRepository; 62 | 63 | // If no paging provided, everything is returned on a single page 64 | @Test 65 | public void unpaged() { 66 | Page page = this.personRepository.findAll(Pageable.unpaged()); 67 | 68 | assertThat("Page returned for null input", page, notNullValue()); 69 | 70 | List content = page.getContent(); 71 | 72 | assertThat("First page is returned", page.getNumber(), equalTo(0)); 73 | assertThat("First page count matches content", page.getNumberOfElements(), equalTo(content.size())); 74 | assertThat("First page has all content", (long) page.getNumberOfElements(), equalTo(page.getTotalElements())); 75 | assertThat("First page has correct content count", page.getNumberOfElements(), equalTo(TestData.bestActors.length)); 76 | assertThat("First page is only page", page.getTotalPages(), equalTo(1)); 77 | } 78 | 79 | @Test 80 | public void paging() { 81 | int PAGE_0 = 0; 82 | int PAGE_2 = 2; 83 | int SIZE_5 = 5; 84 | int SIZE_20 = 20; 85 | 86 | PageRequest thirdPageOf5Request = PageRequest.of(PAGE_2, SIZE_5); 87 | Page thirdPageOf5Response = this.personRepository.findAll(thirdPageOf5Request); 88 | assertThat("11 onwards returned", thirdPageOf5Response, notNullValue()); 89 | 90 | List thirdPageOf5Content = thirdPageOf5Response.getContent(); 91 | assertThat("11-15 returned", thirdPageOf5Content.size(), equalTo(5)); 92 | 93 | Pageable fourthPageOf5Request = thirdPageOf5Response.nextPageable(); 94 | Page fourthPageOf5Response = this.personRepository.findAll(fourthPageOf5Request); 95 | assertThat("16 onwards returned", fourthPageOf5Response, notNullValue()); 96 | 97 | List fourthPageOf5Content = fourthPageOf5Response.getContent(); 98 | assertThat("16-20 returned", fourthPageOf5Content.size(), equalTo(5)); 99 | 100 | PageRequest firstPageOf20Request = PageRequest.of(PAGE_0, SIZE_20); 101 | Page firstPageOf20Response = this.personRepository.findAll(firstPageOf20Request); 102 | assertThat("1 onwards returned", firstPageOf20Response, notNullValue()); 103 | 104 | List firstPageOf20Content = firstPageOf20Response.getContent(); 105 | assertThat("1-20 returned", firstPageOf20Content.size(), equalTo(20)); 106 | 107 | assertThat("11th", thirdPageOf5Content.get(0), equalTo(firstPageOf20Content.get(10))); 108 | assertThat("12th", thirdPageOf5Content.get(1), equalTo(firstPageOf20Content.get(11))); 109 | assertThat("13th", thirdPageOf5Content.get(2), equalTo(firstPageOf20Content.get(12))); 110 | assertThat("14th", thirdPageOf5Content.get(3), equalTo(firstPageOf20Content.get(13))); 111 | assertThat("15th", thirdPageOf5Content.get(4), equalTo(firstPageOf20Content.get(14))); 112 | assertThat("16th", fourthPageOf5Content.get(0), equalTo(firstPageOf20Content.get(15))); 113 | assertThat("17th", fourthPageOf5Content.get(1), equalTo(firstPageOf20Content.get(16))); 114 | assertThat("18th", fourthPageOf5Content.get(2), equalTo(firstPageOf20Content.get(17))); 115 | assertThat("19th", fourthPageOf5Content.get(3), equalTo(firstPageOf20Content.get(18))); 116 | assertThat("20th", fourthPageOf5Content.get(4), equalTo(firstPageOf20Content.get(19))); 117 | 118 | Set ids = new TreeSet<>(); 119 | firstPageOf20Content.forEach(person -> ids.add(person.getId())); 120 | 121 | assertThat("20 different years", ids.size(), equalTo(20)); 122 | } 123 | 124 | @Test 125 | public void unsorted() { 126 | Iterable iterable = this.personRepository.findAll(Sort.unsorted()); 127 | 128 | assertThat("Results returned", iterable, notNullValue()); 129 | 130 | Iterator iterator = iterable.iterator(); 131 | 132 | int count = 0; 133 | while (iterator.hasNext()) { 134 | count++; 135 | iterator.next(); 136 | } 137 | 138 | assertThat("Correct number, order undefined", count, equalTo(TestData.bestActors.length)); 139 | } 140 | 141 | @Test 142 | public void sorting() { 143 | Sort sortAscending = Sort.by(Sort.Direction.ASC, "firstname"); 144 | Sort sortDescending = Sort.by(Sort.Direction.DESC, "firstname"); 145 | 146 | Iterable iterableAscending = this.personRepository.findAll(sortAscending); 147 | Iterable iterableDescending = this.personRepository.findAll(sortDescending); 148 | assertThat("Results returned ascending", iterableAscending, notNullValue()); 149 | assertThat("Results returned descending", iterableDescending, notNullValue()); 150 | 151 | Iterator iteratorAscending = iterableAscending.iterator(); 152 | Iterator iteratorDescending = iterableDescending.iterator(); 153 | assertThat("Not empty returned ascending", iteratorAscending.hasNext(), is(true)); 154 | assertThat("Not empty returned descending", iteratorDescending.hasNext(), is(true)); 155 | 156 | String previousFirstname = ""; 157 | int count = 0; 158 | while (iteratorAscending.hasNext()) { 159 | Person person = iteratorAscending.next(); 160 | assertThat("Firstname " + count + " ascending", person.getFirstname(), greaterThanOrEqualTo(previousFirstname)); 161 | count++; 162 | previousFirstname = person.getFirstname(); 163 | } 164 | assertThat("Everything found ascending", count, equalTo(TestData.bestActors.length)); 165 | 166 | assertThat("1956 winner, last firstname ascending", previousFirstname, equalTo("Yul")); 167 | 168 | while (iteratorDescending.hasNext()) { 169 | Person person = iteratorDescending.next(); 170 | assertThat("Firstname " + count + " descending", person.getFirstname(), lessThanOrEqualTo(previousFirstname)); 171 | count--; 172 | previousFirstname = person.getFirstname(); 173 | } 174 | assertThat("Everything found decending", count, equalTo(0)); 175 | 176 | assertThat("2002 winner, last firstname descending", previousFirstname, equalTo("Adrien")); 177 | } 178 | 179 | } 180 | -------------------------------------------------------------------------------- /src/test/java/test/utils/InstanceHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package test.utils; 18 | 19 | import com.hazelcast.client.HazelcastClient; 20 | import com.hazelcast.client.config.ClientConfig; 21 | import com.hazelcast.config.Config; 22 | import com.hazelcast.config.TcpIpConfig; 23 | import com.hazelcast.core.Hazelcast; 24 | import com.hazelcast.core.HazelcastInstance; 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | import org.springframework.context.annotation.Bean; 28 | import org.springframework.context.annotation.Configuration; 29 | import org.springframework.context.annotation.Profile; 30 | import org.springframework.data.hazelcast.repository.config.EnableHazelcastRepositories; 31 | import test.utils.repository.custom.MyTitleRepositoryFactoryBean; 32 | 33 | import javax.annotation.PreDestroy; 34 | import javax.annotation.Resource; 35 | import java.util.Arrays; 36 | import java.util.Set; 37 | 38 | /** 39 | *

    40 | * Bootstrap Spring objects as part of test context. Creates a {@link HazelcastInstance} {@code @Bean} for all tests, 41 | * and uses {@link EnableHazelcastRepositories @EnableHazelcastRepositories} to initiate a class scan to load 42 | * repositories and domain classes. Depending on the Spring active profile, the Hazelcast instance may be isolated or 43 | * connected to others in this JVM. 44 | *

    45 | *

    46 | * Package scanning adds standard repositories, from "{@code test.utils.repository.standard}", 47 | * using {@link HazelcastRepositoryFactoryBean}. 48 | *

    49 | * 50 | * @author Neil Stevenson 51 | */ 52 | @Configuration 53 | @EnableHazelcastRepositories(basePackages = "test.utils.repository.standard", hazelcastInstanceRef = TestConstants.CLIENT_INSTANCE_NAME) 54 | public class InstanceHelper { 55 | private static final Logger LOG = LoggerFactory.getLogger(InstanceHelper.class); 56 | private static final String CLUSTER_HOST = "127.0.0.1"; 57 | private static final int CLUSTER_PORT = 5701; 58 | private static final String MASTER_SERVER = CLUSTER_HOST + ":" + CLUSTER_PORT; 59 | @Resource(name = TestConstants.CLIENT_INSTANCE_NAME) 60 | private HazelcastInstance hazelcastInstance; 61 | 62 | /** 63 | *

    64 | * Create a cluster using {@code 127.0.0.1:5701} as the master. The master must be created first, and may be the only 65 | * server instance in this JVM. 66 | *

    67 | * 68 | * @param name Enables easy identification 69 | * @param port The only port this server can use. 70 | * @return The master or the 2nd server in the cluster 71 | */ 72 | public static HazelcastInstance makeServer(final String name, final int port) { 73 | Config hazelcastConfig = new Config(name); 74 | 75 | hazelcastConfig.getNetworkConfig().setReuseAddress(true); 76 | 77 | hazelcastConfig.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); 78 | hazelcastConfig.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false); 79 | 80 | TcpIpConfig tcpIpConfig = hazelcastConfig.getNetworkConfig().getJoin().getTcpIpConfig(); 81 | tcpIpConfig.setEnabled(true); 82 | tcpIpConfig.setMembers(Arrays.asList(MASTER_SERVER)); 83 | tcpIpConfig.setRequiredMember(MASTER_SERVER); 84 | 85 | hazelcastConfig.getNetworkConfig().setPort(port); 86 | hazelcastConfig.getNetworkConfig().setPortAutoIncrement(false); 87 | 88 | HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(hazelcastConfig); 89 | 90 | LOG.debug("Created {}", hazelcastInstance); 91 | 92 | return hazelcastInstance; 93 | } 94 | 95 | /** 96 | *

    97 | * Create a client that can connect to the cluster via the master server {@code 127.0.0.1:5701}. The server will be in 98 | * the same JVM, but connect via the network. 99 | *

    100 | * 101 | * @param name The client's instance name 102 | * @return A client in a client-server topology. 103 | */ 104 | public static HazelcastInstance makeClient(final String name) { 105 | ClientConfig clientConfig = new ClientConfig(); 106 | 107 | clientConfig.setInstanceName(name); 108 | clientConfig.getNetworkConfig().setAddresses(Arrays.asList(MASTER_SERVER)); 109 | 110 | HazelcastInstance hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig); 111 | 112 | LOG.debug("Created {}", hazelcastInstance); 113 | 114 | return hazelcastInstance; 115 | } 116 | 117 | /** 118 | *

    119 | * Spring will shutdown the test Hazelcast instance, as the {@code @Bean} is defined as a 120 | * {@link org.springframework.beans.factory.DisposableBean}. Shut down any other server instances started, which may 121 | * be needed for cluster tests. 122 | *

    123 | */ 124 | @PreDestroy 125 | public void preDestroy() { 126 | boolean testInstanceWasRunning = false; 127 | 128 | Set hazelcastInstances = Hazelcast.getAllHazelcastInstances(); 129 | if (hazelcastInstances.size() != 0) { 130 | for (HazelcastInstance hazelcastInstance : hazelcastInstances) { 131 | if (TestConstants.CLIENT_INSTANCE_NAME.equals(hazelcastInstance.getName())) { 132 | testInstanceWasRunning = true; 133 | } 134 | LOG.debug("Closing '{}'", hazelcastInstance); 135 | hazelcastInstance.shutdown(); 136 | } 137 | } 138 | ; 139 | 140 | if (testInstanceWasRunning) { 141 | LOG.error("'{}' was still running", TestConstants.CLIENT_INSTANCE_NAME); 142 | } else { 143 | LOG.debug("'{}' already closed by Spring", TestConstants.CLIENT_INSTANCE_NAME); 144 | } 145 | } 146 | 147 | /** 148 | *

    The {@code @EnableHazelcastRepositories} annotation is not repeatable, 149 | * so use an inner class to scan a second package. 150 | *

    151 | */ 152 | @EnableHazelcastRepositories(basePackages = "test.utils.repository.custom", repositoryFactoryBeanClass = MyTitleRepositoryFactoryBean.class, hazelcastInstanceRef = TestConstants.CLIENT_INSTANCE_NAME) 153 | static class InstanceHelperInner { 154 | } 155 | 156 | /** 157 | *

    158 | * A single Hazelcast instance is the simplest, and sufficient for most of the tests. 159 | *

    160 | */ 161 | @Configuration 162 | @Profile(TestConstants.SPRING_TEST_PROFILE_SINGLETON) 163 | public static class Singleton { 164 | /** 165 | *

    166 | * Create a singleton {@link HazelcastInstance} server {@code @Bean}. 167 | *

    168 | * 169 | * @return A standalone Hazelcast instance, a cluster of one 170 | */ 171 | @Bean(name = TestConstants.CLIENT_INSTANCE_NAME) 172 | public HazelcastInstance singleton() { 173 | HazelcastInstance hazelcastInstance = InstanceHelper.makeServer(TestConstants.CLIENT_INSTANCE_NAME, CLUSTER_PORT); 174 | LOG.trace("@Bean=='{}'", hazelcastInstance); 175 | return hazelcastInstance; 176 | } 177 | } 178 | 179 | /** 180 | *

    181 | * Create a cluster with more than one instance, for use in more complex tests. 182 | *

    183 | *

    184 | * Although one per JVM is more typical, create them all in the one JVM to simplify control from JUnit. 185 | *

    186 | *

    187 | * To avoid overloading the JVM, "multiple" instances means 2. 188 | *

    189 | */ 190 | @Configuration 191 | @Profile(TestConstants.SPRING_TEST_PROFILE_CLUSTER) 192 | public static class Cluster { 193 | /** 194 | *

    195 | * Create two {@link HazelcastInstance} server {@code @Bean}s clustered together. 196 | *

    197 | * 198 | * @return One of two Hazelcast instances created. 199 | */ 200 | @Bean(name = TestConstants.CLIENT_INSTANCE_NAME) 201 | public HazelcastInstance cluster() { 202 | HazelcastInstance hazelcastInstance = InstanceHelper.makeServer(TestConstants.CLIENT_INSTANCE_NAME, CLUSTER_PORT); 203 | LOG.trace("@Bean == '{}'", hazelcastInstance); 204 | 205 | InstanceHelper.makeServer(TestConstants.SERVER_INSTANCE_NAME, (1 + CLUSTER_PORT)); 206 | 207 | return hazelcastInstance; 208 | } 209 | } 210 | 211 | /** 212 | *

    213 | * Create a client-server topology, for use in more complex tests. 214 | *

    215 | *

    216 | * As per {@code Constants.SPRING_TEST_PROFILE_CLUSTER}, these instances are all in the one JVM and the minimum number 217 | * (1 client, 1 server) is made. 218 | *

    219 | */ 220 | @Configuration 221 | @Profile(TestConstants.SPRING_TEST_PROFILE_CLIENT_SERVER) 222 | public static class ClientServer { 223 | /** 224 | *

    225 | * Create a client-server topology, using one {@link HazelcastInstance} server and one {@link HazelcastInstance} 226 | * client. The client is the returned as the {@code @Bean}. 227 | *

    228 | * 229 | * @return The client Hazelcast instance. 230 | */ 231 | @Bean(name = TestConstants.CLIENT_INSTANCE_NAME) 232 | public HazelcastInstance cluster() { 233 | InstanceHelper.makeServer(TestConstants.SERVER_INSTANCE_NAME, CLUSTER_PORT); 234 | 235 | HazelcastInstance hazelcastInstance = InstanceHelper.makeClient(TestConstants.CLIENT_INSTANCE_NAME); 236 | LOG.trace("@Bean == '{}'", hazelcastInstance); 237 | 238 | return hazelcastInstance; 239 | } 240 | } 241 | 242 | static { 243 | System.setProperty("hazelcast.logging.type", "slf4j"); 244 | } 245 | 246 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/hazelcast/repository/support/SimpleHazelcastRepositoryIT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 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 | 17 | package org.springframework.data.hazelcast.repository.support; 18 | 19 | import org.junit.Before; 20 | import org.junit.Test; 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.data.domain.Page; 23 | import org.springframework.data.domain.PageRequest; 24 | import org.springframework.data.domain.Pageable; 25 | import org.springframework.data.domain.Sort; 26 | import org.springframework.data.keyvalue.core.KeyValueOperations; 27 | import org.springframework.data.repository.core.support.PersistentEntityInformation; 28 | import org.springframework.test.context.ActiveProfiles; 29 | import test.utils.TestData; 30 | import test.utils.TestConstants; 31 | import test.utils.TestDataHelper; 32 | import test.utils.domain.Makeup; 33 | 34 | import java.util.ArrayList; 35 | import java.util.Iterator; 36 | import java.util.List; 37 | import java.util.Set; 38 | import java.util.TreeSet; 39 | 40 | import static org.hamcrest.Matchers.equalTo; 41 | import static org.hamcrest.Matchers.greaterThan; 42 | import static org.hamcrest.Matchers.hasSize; 43 | import static org.hamcrest.Matchers.lessThan; 44 | import static org.hamcrest.Matchers.not; 45 | import static org.hamcrest.Matchers.nullValue; 46 | import static org.junit.Assert.assertThat; 47 | 48 | /** 49 | *

    50 | * Validate the methods provided by {@link SimpleHazelcastRepository} 51 | * by creating a repository for {@link Makeup} which doesn't 52 | * have one created by Spring from a repository interface. 53 | *

    54 | * 55 | * @author Neil Stevenson 56 | */ 57 | @ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_SINGLETON) 58 | public class SimpleHazelcastRepositoryIT 59 | extends TestDataHelper { 60 | private static final String YEAR_1939 = "1939"; 61 | private static final String YEAR_1941 = "1941"; 62 | private static final String YEAR_1986 = "1986"; 63 | private static final String YEAR_2009 = "2009"; 64 | private static final String YEAR_9999 = "9999"; 65 | private static final int PAGE_0 = 0; 66 | private static final int SIZE_10 = 10; 67 | 68 | private SimpleHazelcastRepository theRepository; 69 | 70 | @Autowired 71 | private KeyValueOperations keyValueOperations; 72 | 73 | @Before 74 | public void setUp_After_Super_SetUp() { 75 | PersistentEntityInformation entityInformation = new PersistentEntityInformation(keyValueOperations.getMappingContext().getPersistentEntity(Makeup.class)); 76 | 77 | this.theRepository = new SimpleHazelcastRepository<>(entityInformation, keyValueOperations); 78 | } 79 | 80 | @Test 81 | public void findAll_Sort() { 82 | Sort sort = Sort.by(Sort.Direction.DESC, "id"); 83 | 84 | Iterable iterable = this.theRepository.findAll(sort); 85 | assertThat("iterable", iterable, not(nullValue())); 86 | 87 | Iterator iterator = iterable.iterator(); 88 | int count = 0; 89 | String previous = YEAR_9999; 90 | while (iterator.hasNext()) { 91 | Makeup makeup = iterator.next(); 92 | assertThat("Makeup after " + previous, makeup, not(nullValue())); 93 | 94 | count++; 95 | String current = makeup.getId(); 96 | 97 | assertThat("CCYY " + current, current.length(), equalTo(4)); 98 | assertThat(current, lessThan(previous)); 99 | 100 | previous = current; 101 | } 102 | 103 | assertThat(count, equalTo(TestData.bestMakeUp.length)); 104 | } 105 | 106 | @Test 107 | public void findAll_Pageable() { 108 | Set yearsExpected = new TreeSet<>(); 109 | for (Object[] datum : TestData.bestMakeUp) { 110 | yearsExpected.add(datum[0].toString()); 111 | } 112 | 113 | Pageable pageRequest = PageRequest.of(PAGE_0, SIZE_10); 114 | 115 | Page pageResponse = this.theRepository.findAll(pageRequest); 116 | int page = 0; 117 | while (pageResponse != null) { 118 | assertThat("Page " + page + ", has content", pageResponse.hasContent(), equalTo(true)); 119 | 120 | List makeups = pageResponse.getContent(); 121 | assertThat("Page " + page + ", has makeups", makeups.size(), greaterThan(0)); 122 | 123 | for (Makeup makeup : makeups) { 124 | assertThat(makeup.toString(), yearsExpected.contains(makeup.getId()), equalTo(true)); 125 | yearsExpected.remove(makeup.getId()); 126 | } 127 | 128 | if (pageResponse.hasNext()) { 129 | pageRequest = pageResponse.nextPageable(); 130 | pageResponse = this.theRepository.findAll(pageRequest); 131 | } else { 132 | pageResponse = null; 133 | } 134 | page++; 135 | } 136 | 137 | assertThat("All years matched", yearsExpected, hasSize(0)); 138 | } 139 | 140 | @Test 141 | public void count() { 142 | long count = this.theRepository.count(); 143 | assertThat(count, equalTo((long) TestData.bestMakeUp.length)); 144 | } 145 | 146 | @Test 147 | public void delete_ID() { 148 | assertThat("Exists before", this.makeupMap.containsKey(YEAR_2009), equalTo(true)); 149 | 150 | this.theRepository.deleteById(YEAR_2009); 151 | 152 | assertThat("Does not exist after", this.makeupMap.containsKey(YEAR_2009), equalTo(false)); 153 | } 154 | 155 | @Test 156 | public void delete_T() { 157 | Makeup starTrek = new Makeup(); 158 | starTrek.setId(YEAR_2009); 159 | starTrek.setFilmTitle("Star Trek"); 160 | starTrek.setArtistOrArtists("Barney Burman & Mindy Hall & Joel Harlow"); 161 | 162 | assertThat("2009 exists before", this.makeupMap.containsKey(YEAR_2009), equalTo(true)); 163 | 164 | this.theRepository.delete(starTrek); 165 | 166 | assertThat("2009 does not exist after", this.makeupMap.containsKey(YEAR_2009), equalTo(false)); 167 | } 168 | 169 | @Test 170 | public void delete_Iterable_T() { 171 | Makeup starTrek = new Makeup(); 172 | starTrek.setId(YEAR_2009); 173 | starTrek.setFilmTitle("Star Trek"); 174 | starTrek.setArtistOrArtists("Barney Burman & Mindy Hall & Joel Harlow"); 175 | 176 | Makeup theFly = new Makeup(); 177 | theFly.setId(YEAR_1986); 178 | theFly.setFilmTitle("The Fly"); 179 | theFly.setArtistOrArtists("Chris Walas & Stephan Dupuis"); 180 | 181 | assertThat("2009 exists before", this.makeupMap.containsKey(YEAR_2009), equalTo(true)); 182 | assertThat("1986 exists before", this.makeupMap.containsKey(YEAR_1986), equalTo(true)); 183 | 184 | List list = new ArrayList<>(); 185 | list.add(starTrek); 186 | list.add(theFly); 187 | 188 | this.theRepository.deleteAll(list); 189 | 190 | assertThat("2009 does not exist after", this.makeupMap.containsKey(YEAR_2009), equalTo(false)); 191 | assertThat("1986 does not exist after", this.makeupMap.containsKey(YEAR_1986), equalTo(false)); 192 | } 193 | 194 | @Test 195 | public void deleteAll() { 196 | assertThat("Before", this.makeupMap.size(), equalTo(TestData.bestMakeUp.length)); 197 | 198 | this.theRepository.deleteAll(); 199 | 200 | assertThat("After", this.makeupMap.size(), equalTo(0)); 201 | } 202 | 203 | @Test 204 | public void exists_ID() { 205 | assertThat(YEAR_1986, this.theRepository.existsById(YEAR_1986), equalTo(true)); 206 | assertThat(YEAR_9999, this.theRepository.existsById(YEAR_9999), equalTo(false)); 207 | } 208 | 209 | @Test 210 | public void findAll() { 211 | 212 | Set expected = new TreeSet<>(); 213 | for (Object[] datum : TestData.bestMakeUp) { 214 | Makeup makeup = new Makeup(); 215 | makeup.setId(datum[0].toString()); 216 | makeup.setFilmTitle(datum[1].toString()); 217 | makeup.setArtistOrArtists(datum[2].toString()); 218 | 219 | expected.add(makeup); 220 | } 221 | 222 | Iterable iterable = this.theRepository.findAll(); 223 | assertThat("iterable", iterable, not(nullValue())); 224 | 225 | for (Makeup makeup : iterable) { 226 | assertThat(makeup.toString(), expected.contains(makeup), equalTo(true)); 227 | expected.remove(makeup); 228 | } 229 | 230 | assertThat("All expected accounted for", expected, equalTo(new TreeSet())); 231 | } 232 | 233 | @Test 234 | public void findAll_Iterable_ID() { 235 | List years = new ArrayList<>(); 236 | years.add(YEAR_1986); 237 | years.add(YEAR_2009); 238 | 239 | Iterable iterable = this.theRepository.findAllById(years); 240 | assertThat("iterable", iterable, not(nullValue())); 241 | 242 | Iterator iterator = iterable.iterator(); 243 | 244 | boolean found1986 = false; 245 | boolean found2009 = false; 246 | int count = 0; 247 | while (iterator.hasNext()) { 248 | Makeup makeup = iterator.next(); 249 | count++; 250 | 251 | if (makeup.getId().equals(YEAR_1986)) { 252 | found1986 = true; 253 | } 254 | if (makeup.getId().equals(YEAR_2009)) { 255 | found2009 = true; 256 | } 257 | } 258 | 259 | assertThat(YEAR_1986, found1986, equalTo(true)); 260 | assertThat(YEAR_2009, found2009, equalTo(true)); 261 | assertThat("Only 1986 & 2009 found", count, equalTo(2)); 262 | } 263 | 264 | @Test 265 | public void findOne_ID() { 266 | Makeup makeup = this.theRepository.findById(YEAR_1986).orElse(null); 267 | 268 | assertThat("1986 found", makeup, not(nullValue())); 269 | assertThat(makeup.getId(), equalTo(YEAR_1986)); 270 | assertThat(makeup.getFilmTitle(), equalTo("The Fly")); 271 | assertThat(makeup.getArtistOrArtists(), equalTo("Chris Walas & Stephan Dupuis")); 272 | } 273 | 274 | @Test 275 | public void save_T() { 276 | Makeup citizenKane = new Makeup(); 277 | citizenKane.setId(YEAR_1941); 278 | citizenKane.setFilmTitle("Citizen Kane"); 279 | citizenKane.setArtistOrArtists("Maurice Seiderman"); 280 | 281 | assertThat("Before", this.makeupMap.size(), equalTo(TestData.bestMakeUp.length)); 282 | 283 | Makeup saved = this.theRepository.save(citizenKane); 284 | 285 | assertThat("Saved entry", saved, not(nullValue())); 286 | 287 | assertThat("After", this.makeupMap.size(), equalTo(TestData.bestMakeUp.length + 1)); 288 | } 289 | 290 | @Test 291 | public void save_Iterable_T() { 292 | Makeup goneWithTheWind = new Makeup(); 293 | goneWithTheWind.setId(YEAR_1939); 294 | goneWithTheWind.setFilmTitle("Gone With The Wind"); 295 | goneWithTheWind.setArtistOrArtists("Monte Westmore"); 296 | 297 | Makeup citizenKane = new Makeup(); 298 | citizenKane.setId(YEAR_1941); 299 | citizenKane.setFilmTitle("Citizen Kane"); 300 | citizenKane.setArtistOrArtists("Maurice Seiderman"); 301 | 302 | assertThat("Before", this.makeupMap.size(), equalTo(TestData.bestMakeUp.length)); 303 | 304 | List list = new ArrayList<>(); 305 | list.add(citizenKane); 306 | list.add(goneWithTheWind); 307 | 308 | Iterable iterable = this.theRepository.saveAll(list); 309 | assertThat("iterable", iterable, not(nullValue())); 310 | 311 | Iterator iterator = iterable.iterator(); 312 | int count = 0; 313 | while (iterator.hasNext()) { 314 | iterator.next(); 315 | count++; 316 | } 317 | assertThat("Correct number saved", count, equalTo(list.size())); 318 | 319 | assertThat("After", this.makeupMap.size(), equalTo(TestData.bestMakeUp.length + list.size())); 320 | } 321 | 322 | } 323 | -------------------------------------------------------------------------------- /checkstyle/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 21 | 22 | 46 | 47 | 48 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 315 | 316 | 317 | 318 | --------------------------------------------------------------------------------