diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..145fe6f1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,28 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug, help wanted, needs-verification +assignees: mmnaseri + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +Minimal example to reproduce. This is *very* helpful, as we can just use this as a regression +test and make sure we catch the error exactly as intended, and not as interpreted. + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..6adb20e1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement, help wanted, needs-verification +assignees: mmnaseri + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..7ae85a38 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at m.m.naseri+spring-data-mock@gmail.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..4f82e9de --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,29 @@ +Contributing +------------ + +Contributors are more than welcome! + +Since this project aims to help you in the testing phase of your code, it is paramount that it is +written with the best of qualities and that it maintains the highest standard. + +Contributors are more than welcome. In fact, I flag most of the issues I receive as `help wanted` and +there are really generous people out there who do take care of some issues. + +If you see a piece of code that you don't like for whatever reason -- so long as that reason can be backed +by pioneers and standards -- feel free to dig in and change the code to your heart's content and create a +pull request. + +### Building the Code + +To make the code builds universal and canonical, I have a Docker configuration attached to this project +which installs OpenJDK 8 on Ubuntu Xenial. This is the build environment I will be using to test and release +the code. + +```bash +docker build -t spring-data-mock:jdk8 . +docker run -it --rm -v $(pwd):/src spring-data-mock:jdk8 +``` + +See the project website at https://mmnaseri.github.io/spring-data-mock for details, explanation, and other stuff. + +Contact me for more info, if needed. diff --git a/README.md b/README.md index ad57f2a1..13671dba 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,6 @@ ----------- - This is a fairly flexible, versatile framework for mocking Spring Data repositories. Spring Data provides a very good foundation for separating the concerns of managing a database and its subsequently resulting queries from those of the business layer. @@ -105,8 +104,6 @@ your shiny applications. - As well it should, it is now adopting all the new method signatures for the new Spring Data, meaning that those are now automatic breaking changes. -- We have now dropped support for Querydsl repositories until further notice, due to compiler issues with the EJC -dependency used by Querydsl. - The library now runs on Java 8+, meaning we do not support JDK 7 anymore. ## History diff --git a/spring-data-mock-build/pom.xml b/spring-data-mock-build/pom.xml index f1fce08a..b1cab04c 100644 --- a/spring-data-mock-build/pom.xml +++ b/spring-data-mock-build/pom.xml @@ -19,14 +19,14 @@ ~ SOFTWARE. --> - 4.0.0 com.mmnaseri.utils spring-data-mock-build - 2.1.0 + 2.1.1 pom Spring Data Mock: Build Aggregator diff --git a/spring-data-mock-sample-jpa/pom.xml b/spring-data-mock-sample-jpa/pom.xml index d3a8d67b..875ab485 100644 --- a/spring-data-mock-sample-jpa/pom.xml +++ b/spring-data-mock-sample-jpa/pom.xml @@ -1,16 +1,17 @@ - 4.0.0 com.mmnaseri.utils.sample spring-data-mock-sample-jpa - 1.0 + 1.0.0 Spring Data Mock: Samples (JPA) This module tries to demonstrate how Spring Data Mock could be used to test an application that - is using Spring Data JPA. + is using Spring Data JPA. + 2016 @@ -36,7 +37,7 @@ 2.2.6.RELEASE 2.2.6.RELEASE 1.0.2 - 2.1.0 + 2.1.1 7.1.0 1.3 3.8.1 diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Card.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Card.java new file mode 100644 index 00000000..30e2ef69 --- /dev/null +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Card.java @@ -0,0 +1,29 @@ +package com.mmnaseri.utils.samples.spring.data.jpa.model; + +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +public class Card { + + @Id @GeneratedValue private Integer id; + + private String blabla; + + public Integer getId() { + return id; + } + + public Card setId(final Integer id) { + this.id = id; + return this; + } + + public String getBlabla() { + return blabla; + } + + public Card setBlabla(final String blabla) { + this.blabla = blabla; + return this; + } +} diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Customer.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Customer.java index 61274f78..1b21d6f7 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Customer.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Customer.java @@ -14,43 +14,43 @@ @SuppressWarnings("unused") public class Customer { - @Id - private Long id; - @Temporal(TemporalType.DATE) - private Date birthday; - private String firstName; - private String lastName; + @Id private Long id; - public Long getId() { - return id; - } + @Temporal(TemporalType.DATE) + private Date birthday; - public void setId(Long id) { - this.id = id; - } + private String firstName; + private String lastName; - public Date getBirthday() { - return birthday; - } + public Long getId() { + return id; + } - public void setBirthday(Date birthday) { - this.birthday = birthday; - } + public void setId(Long id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public Date getBirthday() { + return birthday; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setBirthday(Date birthday) { + this.birthday = birthday; + } - public String getLastName() { - return lastName; - } + public String getFirstName() { + return firstName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Group.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Group.java index d5f84665..34f2b018 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Group.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Group.java @@ -11,24 +11,22 @@ @Entity public class Group { - @Id - private String id; - private String name; + @Id private String id; + private String name; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Membership.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Membership.java index 41ca2ca7..669fb8c2 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Membership.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Membership.java @@ -12,35 +12,41 @@ @SuppressWarnings("unused") public class Membership { - @Id - private String id; - @ManyToOne - private User user; - @ManyToOne - private Group group; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public Group getGroup() { - return group; - } - - public void setGroup(Group group) { - this.group = group; - } - + @Id private String id; + @ManyToOne private User user; + @ManyToOne private Group group; + private Boolean active; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Group getGroup() { + return group; + } + + public void setGroup(Group group) { + this.group = group; + } + + public Boolean getActive() { + return active; + } + + public Membership setActive(final Boolean active) { + this.active = active; + return this; + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Plane.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Plane.java index 3b02d14f..2ec48659 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Plane.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/Plane.java @@ -11,33 +11,31 @@ @SuppressWarnings("unused") public class Plane extends SerialAwareEntity { - @Id - private Long id; - private String model; - private int capacity; + @Id private Long id; + private String model; + private int capacity; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getModel() { - return model; - } + public String getModel() { + return model; + } - public void setModel(String model) { - this.model = model; - } + public void setModel(String model) { + this.model = model; + } - public int getCapacity() { - return capacity; - } - - public void setCapacity(int capacity) { - this.capacity = capacity; - } + public int getCapacity() { + return capacity; + } + public void setCapacity(int capacity) { + this.capacity = capacity; + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/SerialAwareEntity.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/SerialAwareEntity.java index f24fb237..4276a86d 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/SerialAwareEntity.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/SerialAwareEntity.java @@ -9,14 +9,13 @@ @MappedSuperclass public class SerialAwareEntity { - private String serial; + private String serial; - public String getSerial() { - return serial; - } - - public void setSerial(String serial) { - this.serial = serial; - } + public String getSerial() { + return serial; + } + public void setSerial(String serial) { + this.serial = serial; + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/User.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/User.java index cce788e3..dcea99a2 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/User.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/model/User.java @@ -11,42 +11,40 @@ @SuppressWarnings("unused") public class User { - @Id - private String id; - private String username; - private String email; - private String passwordHash; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getPasswordHash() { - return passwordHash; - } - - public void setPasswordHash(String passwordHash) { - this.passwordHash = passwordHash; - } - + @Id private String id; + private String username; + private String email; + private String passwordHash; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPasswordHash() { + return passwordHash; + } + + public void setPasswordHash(String passwordHash) { + this.passwordHash = passwordHash; + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CardRepository.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CardRepository.java new file mode 100644 index 00000000..b5c08e79 --- /dev/null +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CardRepository.java @@ -0,0 +1,11 @@ +package com.mmnaseri.utils.samples.spring.data.jpa.repository; + +import com.mmnaseri.utils.samples.spring.data.jpa.model.Card; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface CardRepository extends JpaRepository { + + List findAllByOrderByBlablaAsc(); +} diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CustomerRepository.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CustomerRepository.java index d2caa586..076f9c15 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CustomerRepository.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CustomerRepository.java @@ -14,12 +14,12 @@ */ public interface CustomerRepository extends JpaRepository { - List findByBirthdayBetween(Date from, Date to); + List findByBirthdayBetween(Date from, Date to); - @SuppressWarnings("SpringDataMethodInconsistencyInspection") // This is covered in a custom impl. - List findByExample(Example probe); + @SuppressWarnings("SpringDataMethodInconsistencyInspection") // This is covered in a custom impl. + List findByExample(Example probe); - List findByFirstNameIn(Collection firstNames); + List findByFirstNameIn(Collection firstNames); - List findByFirstNameIgnoreCaseContaining(String substring); + List findByFirstNameIgnoreCaseContaining(String substring); } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/GroupRepository.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/GroupRepository.java index 5098bf79..f6afaa96 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/GroupRepository.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/GroupRepository.java @@ -7,5 +7,4 @@ * @author Milad Naseri (milad.naseri@cdk.com) * @since 1.0 (6/29/16, 4:05 PM) */ -public interface GroupRepository extends JpaRepository { -} +public interface GroupRepository extends JpaRepository {} diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/MembershipRepository.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/MembershipRepository.java index 1a90510f..6a32516e 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/MembershipRepository.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/MembershipRepository.java @@ -6,6 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; +import java.util.Optional; /** * @author Milad Naseri (milad.naseri@cdk.com) @@ -13,9 +14,11 @@ */ public interface MembershipRepository extends JpaRepository { - List findByUser(User user); + List findByUser(User user); - List findByGroup(Group group); + List findByGroup(Group group); - Membership findByUserAndGroup(User user, Group group); + Optional findByUserAndGroup(User user, Group group); + + List findAllByUserAndActive(User user, boolean active); } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/PlaneRepository.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/PlaneRepository.java index 11a04e8c..de722131 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/PlaneRepository.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/PlaneRepository.java @@ -7,5 +7,5 @@ * @author Milad Naseri (milad.naseri@cdk.com) * @since 1.0 (6/14/16, 11:34 PM) */ -public interface PlaneRepository extends JpaRepository, SerialAwareEntityRepository { -} +public interface PlaneRepository + extends JpaRepository, SerialAwareEntityRepository {} diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/SerialAwareEntityRepository.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/SerialAwareEntityRepository.java index e415fced..bdc0497b 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/SerialAwareEntityRepository.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/SerialAwareEntityRepository.java @@ -8,6 +8,5 @@ */ public interface SerialAwareEntityRepository { - E lookupBySerial(String serial); - + E lookupBySerial(String serial); } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/UserRepository.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/UserRepository.java index 4064c84b..09dee06f 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/UserRepository.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/UserRepository.java @@ -9,10 +9,9 @@ */ public interface UserRepository extends JpaRepository { - User findByUsernameOrEmailAllIgnoreCase(String username, String email); + User findByUsernameOrEmailAllIgnoreCase(String username, String email); - User findByUsernameIgnoreCase(String username); - - User findByEmailIgnoreCase(String email); + User findByUsernameIgnoreCase(String username); + User findByEmailIgnoreCase(String email); } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/CardService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/CardService.java new file mode 100644 index 00000000..0c91a127 --- /dev/null +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/CardService.java @@ -0,0 +1,10 @@ +package com.mmnaseri.utils.samples.spring.data.jpa.service; + +import com.mmnaseri.utils.samples.spring.data.jpa.model.Card; + +import java.util.List; + +public interface CardService { + + List load(); +} diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/CustomerService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/CustomerService.java index 95dea04f..9571b035 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/CustomerService.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/CustomerService.java @@ -13,16 +13,15 @@ @SuppressWarnings("unused") public interface CustomerService { - long register(String firstName, String lastName, Date birthday); + long register(String firstName, String lastName, Date birthday); - Customer findCustomer(long id); + Customer findCustomer(long id); - List findCustomersByBirthday(Date from, Date to); + List findCustomersByBirthday(Date from, Date to); - List findCustomersByName(String firstName, String lastName); + List findCustomersByName(String firstName, String lastName); - List findCustomersByFirstNames(Collection firstNames); - - List findByFirstNamePart(String part); + List findCustomersByFirstNames(Collection firstNames); + List findByFirstNamePart(String part); } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/GroupService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/GroupService.java index 3bbf9081..b2be002f 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/GroupService.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/GroupService.java @@ -11,15 +11,19 @@ */ public interface GroupService { - Group createGroup(String name); + Group createGroup(String name); - void deleteGroup(Group group); + void deleteGroup(Group group); - void join(Group group, User user); + void join(Group group, User user); - void leave(Group group, User user); + void leave(Group group, User user); - List members(Group group); + List members(Group group); - List groups(User user); + List groups(User user); + + void deactivate(Group group, User user); + + List deactivatedGroups(User user); } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/PlaneService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/PlaneService.java index 9c5fcccb..89e6c31b 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/PlaneService.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/PlaneService.java @@ -7,10 +7,9 @@ @SuppressWarnings("unused") public interface PlaneService { - Long create(String model, String serial); + Long create(String model, String serial); - String lookup(Long id); - - String lookup(String serial); + String lookup(Long id); + String lookup(String serial); } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/UserService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/UserService.java index e105c981..d5ed7933 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/UserService.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/UserService.java @@ -1,7 +1,10 @@ package com.mmnaseri.utils.samples.spring.data.jpa.service; +import com.mmnaseri.utils.samples.spring.data.jpa.model.Group; import com.mmnaseri.utils.samples.spring.data.jpa.model.User; +import java.util.List; + /** * @author Milad Naseri (milad.naseri@cdk.com) * @since 1.0 (6/29/16, 4:06 PM) @@ -9,14 +12,15 @@ @SuppressWarnings("unused") public interface UserService { - User createUser(String username, String email, String password); + User createUser(String username, String email, String password); - void updatePassword(String handle, String oldPassword, String newPassword); + void updatePassword(String handle, String oldPassword, String newPassword); - void deleteUser(String handle); + void deleteUser(String handle); - User lookup(String handle); + User lookup(String handle); - User authenticate(String handle, String password); + User authenticate(String handle, String password); + List deactivatedGroups(User user); } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCardService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCardService.java new file mode 100644 index 00000000..94aa2a0c --- /dev/null +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCardService.java @@ -0,0 +1,21 @@ +package com.mmnaseri.utils.samples.spring.data.jpa.service.impl; + +import com.mmnaseri.utils.samples.spring.data.jpa.model.Card; +import com.mmnaseri.utils.samples.spring.data.jpa.repository.CardRepository; +import com.mmnaseri.utils.samples.spring.data.jpa.service.CardService; + +import java.util.List; + +public class DefaultCardService implements CardService { + + private final CardRepository cardRepository; + + public DefaultCardService(final CardRepository cardRepository) { + this.cardRepository = cardRepository; + } + + @Override + public List load() { + return cardRepository.findAllByOrderByBlablaAsc(); + } +} diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCustomerService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCustomerService.java index 1a1bb776..66fb3170 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCustomerService.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCustomerService.java @@ -18,46 +18,46 @@ */ public class DefaultCustomerService implements CustomerService { - private final CustomerRepository repository; - - public DefaultCustomerService(CustomerRepository repository) { - this.repository = repository; - } - - public long register(String firstName, String lastName, Date birthday) { - final Customer customer = new Customer(); - customer.setFirstName(firstName); - customer.setLastName(lastName); - customer.setBirthday(birthday); - return repository.save(customer).getId(); - } - - public Customer findCustomer(long id) { - return repository.findById(id).orElse(null); - } - - public List findCustomersByBirthday(Date from, Date to) { - return repository.findByBirthdayBetween(from, to); - } - - public List findCustomersByName(String firstName, String lastName) { - final Customer probe = new Customer(); - probe.setFirstName(firstName); - probe.setLastName(lastName); - final ExampleMatcher matcher = ExampleMatcher.matching() - .withMatcher("firstName", ignoreCase()) - .withMatcher("lastName", ignoreCase()); - final Example example = Example.of(probe, matcher); - return repository.findByExample(example); - } - - public List findCustomersByFirstNames(Collection firstNames) { - return repository.findByFirstNameIn(firstNames); - } - - @Override - public List findByFirstNamePart(final String part) { - return repository.findByFirstNameIgnoreCaseContaining(part); - } - + private final CustomerRepository repository; + + public DefaultCustomerService(CustomerRepository repository) { + this.repository = repository; + } + + public long register(String firstName, String lastName, Date birthday) { + final Customer customer = new Customer(); + customer.setFirstName(firstName); + customer.setLastName(lastName); + customer.setBirthday(birthday); + return repository.save(customer).getId(); + } + + public Customer findCustomer(long id) { + return repository.findById(id).orElse(null); + } + + public List findCustomersByBirthday(Date from, Date to) { + return repository.findByBirthdayBetween(from, to); + } + + public List findCustomersByName(String firstName, String lastName) { + final Customer probe = new Customer(); + probe.setFirstName(firstName); + probe.setLastName(lastName); + final ExampleMatcher matcher = + ExampleMatcher.matching() + .withMatcher("firstName", ignoreCase()) + .withMatcher("lastName", ignoreCase()); + final Example example = Example.of(probe, matcher); + return repository.findByExample(example); + } + + public List findCustomersByFirstNames(Collection firstNames) { + return repository.findByFirstNameIn(firstNames); + } + + @Override + public List findByFirstNamePart(final String part) { + return repository.findByFirstNameIgnoreCaseContaining(part); + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultGroupService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultGroupService.java index b982f788..003e9064 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultGroupService.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultGroupService.java @@ -9,6 +9,9 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; + +import static java.util.stream.Collectors.toList; /** * @author Milad Naseri (milad.naseri@cdk.com) @@ -16,66 +19,84 @@ */ public class DefaultGroupService implements GroupService { - private final GroupRepository groupRepository; - private final MembershipRepository membershipRepository; + private final GroupRepository groupRepository; + private final MembershipRepository membershipRepository; - public DefaultGroupService(GroupRepository groupRepository, MembershipRepository membershipRepository) { - this.groupRepository = groupRepository; - this.membershipRepository = membershipRepository; - } + public DefaultGroupService( + GroupRepository groupRepository, MembershipRepository membershipRepository) { + this.groupRepository = groupRepository; + this.membershipRepository = membershipRepository; + } - @Override - public Group createGroup(String name) { - final Group group = new Group(); - group.setName(name); - return groupRepository.save(group); - } + @Override + public Group createGroup(String name) { + final Group group = new Group(); + group.setName(name); + return groupRepository.save(group); + } + + @Override + public void deleteGroup(Group group) { + final List memberships = membershipRepository.findByGroup(group); + membershipRepository.deleteAll(memberships); + groupRepository.delete(group); + } - @Override - public void deleteGroup(Group group) { - final List memberships = membershipRepository.findByGroup(group); - membershipRepository.deleteAll(memberships); - groupRepository.delete(group); + @Override + public void join(Group group, User user) { + if (membershipRepository.findByUserAndGroup(user, group).isPresent()) { + return; } + final Membership membership = new Membership(); + membership.setGroup(group); + membership.setUser(user); + membershipRepository.save(membership); + } - @Override - public void join(Group group, User user) { - if (membershipRepository.findByUserAndGroup(user, group) != null) { - return; - } - final Membership membership = new Membership(); - membership.setGroup(group); - membership.setUser(user); - membershipRepository.save(membership); + @Override + public void leave(Group group, User user) { + final Optional membership = membershipRepository.findByUserAndGroup(user, group); + if (!membership.isPresent()) { + return; } + membershipRepository.delete(membership.get()); + } - @Override - public void leave(Group group, User user) { - final Membership membership = membershipRepository.findByUserAndGroup(user, group); - if (membership == null) { - return; - } - membershipRepository.delete(membership); + @Override + public List members(Group group) { + final List memberships = membershipRepository.findByGroup(group); + final List users = new ArrayList<>(); + for (Membership membership : memberships) { + users.add(membership.getUser()); } + return users; + } - @Override - public List members(Group group) { - final List memberships = membershipRepository.findByGroup(group); - final List users = new ArrayList<>(); - for (Membership membership : memberships) { - users.add(membership.getUser()); - } - return users; + @Override + public List groups(User user) { + final List memberships = membershipRepository.findByUser(user); + final List groups = new ArrayList<>(); + for (Membership membership : memberships) { + groups.add(membership.getGroup()); } + return groups; + } - @Override - public List groups(User user) { - final List memberships = membershipRepository.findByUser(user); - final List groups = new ArrayList<>(); - for (Membership membership : memberships) { - groups.add(membership.getGroup()); - } - return groups; + @Override + public void deactivate(final Group group, final User user) { + Optional optional = membershipRepository.findByUserAndGroup(user, group); + if (!optional.isPresent()) { + return; } + Membership membership = optional.get(); + membership.setActive(false); + membershipRepository.save(membership); + } + @Override + public List deactivatedGroups(final User user) { + return membershipRepository.findAllByUserAndActive(user, false).stream() + .map(Membership::getGroup) + .collect(toList()); + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultPlaneService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultPlaneService.java index 3c3e11fb..2240992c 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultPlaneService.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultPlaneService.java @@ -10,33 +10,32 @@ */ public class DefaultPlaneService implements PlaneService { - private final PlaneRepository repository; - - public DefaultPlaneService(PlaneRepository repository) { - this.repository = repository; - } - - @Override - public Long create(String model, String serial) { - final Plane plane = new Plane(); - plane.setModel(model); - plane.setCapacity(100); - plane.setSerial(serial); - return repository.save(plane).getId(); - } - - @Override - public String lookup(Long id) { - return repository.findById(id).map(Plane::getModel).orElse(null); - } - - @Override - public String lookup(String serial) { - final Plane plane = repository.lookupBySerial(serial); - if (plane == null) { - return null; - } - return plane.getModel(); + private final PlaneRepository repository; + + public DefaultPlaneService(PlaneRepository repository) { + this.repository = repository; + } + + @Override + public Long create(String model, String serial) { + final Plane plane = new Plane(); + plane.setModel(model); + plane.setCapacity(100); + plane.setSerial(serial); + return repository.save(plane).getId(); + } + + @Override + public String lookup(Long id) { + return repository.findById(id).map(Plane::getModel).orElse(null); + } + + @Override + public String lookup(String serial) { + final Plane plane = repository.lookupBySerial(serial); + if (plane == null) { + return null; } - + return plane.getModel(); + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultUserService.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultUserService.java index 4266c98f..cfdd5f05 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultUserService.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultUserService.java @@ -15,64 +15,69 @@ */ public class DefaultUserService implements UserService { - private final UserRepository repository; - private final GroupService groupService; + private final UserRepository repository; + private final GroupService groupService; - public DefaultUserService(UserRepository repository, GroupService groupService) { - this.repository = repository; - this.groupService = groupService; - } + public DefaultUserService(UserRepository repository, GroupService groupService) { + this.repository = repository; + this.groupService = groupService; + } - @Override - public User createUser(String username, String email, String password) { - if (repository.findByUsernameIgnoreCase(username) != null || repository.findByEmailIgnoreCase(email) != null) { - throw new IllegalArgumentException(); - } - final User user = new User(); - user.setUsername(username); - user.setEmail(email); - user.setPasswordHash(EncryptionUtils.encrypt(password)); - return repository.save(user); + @Override + public User createUser(String username, String email, String password) { + if (repository.findByUsernameIgnoreCase(username) != null + || repository.findByEmailIgnoreCase(email) != null) { + throw new IllegalArgumentException(); } + final User user = new User(); + user.setUsername(username); + user.setEmail(email); + user.setPasswordHash(EncryptionUtils.encrypt(password)); + return repository.save(user); + } - @Override - public void updatePassword(String handle, String oldPassword, String newPassword) { - final User user = authenticate(handle, oldPassword); - if (user == null) { - throw new IllegalStateException(); - } - user.setPasswordHash(EncryptionUtils.encrypt(newPassword)); - repository.save(user); + @Override + public void updatePassword(String handle, String oldPassword, String newPassword) { + final User user = authenticate(handle, oldPassword); + if (user == null) { + throw new IllegalStateException(); } + user.setPasswordHash(EncryptionUtils.encrypt(newPassword)); + repository.save(user); + } - @Override - public void deleteUser(String handle) { - final User user = lookup(handle); - if (user == null) { - throw new IllegalStateException(); - } - final List groups = groupService.groups(user); - for (Group group : groups) { - groupService.leave(group, user); - } - repository.delete(user); + @Override + public void deleteUser(String handle) { + final User user = lookup(handle); + if (user == null) { + throw new IllegalStateException(); } - - @Override - public User lookup(String handle) { - return repository.findByUsernameOrEmailAllIgnoreCase(handle, handle); + final List groups = groupService.groups(user); + for (Group group : groups) { + groupService.leave(group, user); } + repository.delete(user); + } - @Override - public User authenticate(String handle, String password) { - final User user = lookup(handle); - if (user == null) { - return null; - } - if (user.getPasswordHash().equals(EncryptionUtils.encrypt(password))) { - return user; - } - return null; + @Override + public User lookup(String handle) { + return repository.findByUsernameOrEmailAllIgnoreCase(handle, handle); + } + + @Override + public User authenticate(String handle, String password) { + final User user = lookup(handle); + if (user == null) { + return null; + } + if (user.getPasswordHash().equals(EncryptionUtils.encrypt(password))) { + return user; } + return null; + } + @Override + public List deactivatedGroups(final User user) { + return groupService.deactivatedGroups(user); + } } diff --git a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/utils/EncryptionUtils.java b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/utils/EncryptionUtils.java index d150f9f6..3c4f0f2e 100644 --- a/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/utils/EncryptionUtils.java +++ b/spring-data-mock-sample-jpa/src/main/java/com/mmnaseri/utils/samples/spring/data/jpa/utils/EncryptionUtils.java @@ -9,13 +9,12 @@ */ public class EncryptionUtils { - public static String encrypt(String text) { - try { - final MessageDigest digest = MessageDigest.getInstance("SHA-1"); - return new String(digest.digest(text.getBytes())); - } catch (NoSuchAlgorithmException e) { - return text; - } + public static String encrypt(String text) { + try { + final MessageDigest digest = MessageDigest.getInstance("SHA-1"); + return new String(digest.digest(text.getBytes())); + } catch (NoSuchAlgorithmException e) { + return text; } - + } } diff --git a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CustomerRepositoryExampleSupport.java b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CustomerRepositoryExampleSupport.java index d41fa061..4c2aa17b 100644 --- a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CustomerRepositoryExampleSupport.java +++ b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/CustomerRepositoryExampleSupport.java @@ -13,15 +13,14 @@ @SuppressWarnings("unused") public class CustomerRepositoryExampleSupport implements RepositoryAware { - private CustomerRepository repository; + private CustomerRepository repository; - public List findByExample(Example example) { - return repository.findAll(example); - } - - @Override - public void setRepository(CustomerRepository repository) { - this.repository = repository; - } + public List findByExample(Example example) { + return repository.findAll(example); + } + @Override + public void setRepository(CustomerRepository repository) { + this.repository = repository; + } } diff --git a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/SerialAwareEntityRepositorySupport.java b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/SerialAwareEntityRepositorySupport.java index 8946bfa1..f69e2417 100644 --- a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/SerialAwareEntityRepositorySupport.java +++ b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/repository/SerialAwareEntityRepositorySupport.java @@ -12,28 +12,28 @@ * @author Milad Naseri (milad.naseri@cdk.com) * @since 1.0 (6/14/16, 11:45 PM) */ -public class SerialAwareEntityRepositorySupport implements SerialAwareEntityRepository, RepositoryAware { +public class SerialAwareEntityRepositorySupport + implements SerialAwareEntityRepository, RepositoryAware { - private JpaRepository repository; + private JpaRepository repository; - @Override - public SerialAwareEntity lookupBySerial(String serial) { - final SerialAwareEntity probe = new SerialAwareEntity(); - probe.setSerial(serial); - final Example example = Example.of(probe); - final List found = repository.findAll(example); - if (found.isEmpty()) { - return null; - } - if (found.size() > 1) { - throw new DataOperationExecutionException("Expected only one instance to be found", null); - } - return (SerialAwareEntity) found.get(0); + @Override + public SerialAwareEntity lookupBySerial(String serial) { + final SerialAwareEntity probe = new SerialAwareEntity(); + probe.setSerial(serial); + final Example example = Example.of(probe); + final List found = repository.findAll(example); + if (found.isEmpty()) { + return null; } - - @Override - public void setRepository(JpaRepository repository) { - this.repository = repository; + if (found.size() > 1) { + throw new DataOperationExecutionException("Expected only one instance to be found", null); } + return (SerialAwareEntity) found.get(0); + } + @Override + public void setRepository(JpaRepository repository) { + this.repository = repository; + } } diff --git a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCardServiceTest.java b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCardServiceTest.java new file mode 100644 index 00000000..c015813a --- /dev/null +++ b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCardServiceTest.java @@ -0,0 +1,48 @@ +package com.mmnaseri.utils.samples.spring.data.jpa.service.impl; + +import com.mmnaseri.utils.samples.spring.data.jpa.model.Card; +import com.mmnaseri.utils.samples.spring.data.jpa.repository.CardRepository; +import org.hamcrest.Matchers; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.List; + +import static com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilder.builder; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.is; + +public class DefaultCardServiceTest { + + private CardRepository repository; + private DefaultCardService service; + + @BeforeMethod + public void setUp() { + repository = builder().mock(CardRepository.class); + service = new DefaultCardService(repository); + } + + @Test + public void loadAllCardsWhenEmpty() { + List list = service.load(); + + assertThat(list, is(Matchers.empty())); + } + + @Test + public void loadAllCards() { + Card a = new Card().setBlabla("a"); + Card b = new Card().setBlabla("b"); + Card c = new Card().setBlabla("c"); + repository.save(b); + repository.save(c); + repository.save(a); + + List list = service.load(); + + assertThat(list, Matchers.hasSize(3)); + assertThat(list, contains(a, b, c)); + } +} diff --git a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCustomerServiceTest.java b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCustomerServiceTest.java index 3849f072..457a2677 100644 --- a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCustomerServiceTest.java +++ b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultCustomerServiceTest.java @@ -25,118 +25,119 @@ */ public class DefaultCustomerServiceTest { - private DefaultCustomerService service; - private CustomerRepository repository; - - @BeforeMethod - public void setUp() { - repository = builder() - .usingImplementation(CustomerRepositoryExampleSupport.class) - .mock(CustomerRepository.class); - service = new DefaultCustomerService(repository); - } - - @Test - public void testCustomerRegistration() { - final Date date = date(1988, 0, 1); - //let's make sure that the database is empty - assertThat(repository.count(), is(0L)); - final String firstName = "Milad"; - final String lastName = "Naseri"; - //and then register a customer - final long id = service.register(firstName, lastName, date); - //after registration, we should have exactly one record - assertThat(repository.count(), is(1L)); - //and we should be able to load the customer by it's ID - final Customer customer = repository.findById(id).orElse(null); - //and that customer should be the one we registered - assertThat(customer, is(notNullValue())); - assertThat(customer.getId(), is(id)); - assertThat(customer.getFirstName(), is(firstName)); - assertThat(customer.getLastName(), is(lastName)); - assertThat(customer.getBirthday(), is(date)); - } - - @Test - public void testLoadingCustomerById() { - //let's save a customer to the database first - final Customer customer = createCustomer("Milad", "Naseri", date(1988, 1, 1)); - //we should be able to locate that via the service - final Customer loaded = service.findCustomer(customer.getId()); - assertThat(loaded, is(notNullValue())); - assertThat(loaded.getId(), is(customer.getId())); - assertThat(loaded.getBirthday(), is(customer.getBirthday())); - assertThat(loaded.getFirstName(), is(customer.getFirstName())); - assertThat(loaded.getLastName(), is(customer.getLastName())); - } - - @Test - public void testLoadingCustomersByBirthday() { - //let's register three customers, two of which are born within [88/1/1 .. 89/12/28] - final Customer first = createCustomer("Milad", "Naseri", date(1988, 1, 1)); - final Customer second = createCustomer("Zohreh", "Sadeghi", date(1989, 9, 22)); - createCustomer("Hassan", "Naseri", date(1962, 4, 15)); - //we should be able to look up these customers using the service - final List list = service.findCustomersByBirthday(date(1988, 1, 1), date(1989, 12, 28)); - //and the customers should be the ones indicated above - assertThat(list, is(notNullValue())); - assertThat(list, hasSize(2)); - assertThat(list, containsInAnyOrder(first, second)); - } - - @Test - public void testLoadingCustomersByFirstNameAndLastName() { - //let's save three customers ... - final Customer customer = createCustomer("Milad", "Naseri", date(1988, 1, 1)); - createCustomer("Zohreh", "Sadeghi", date(1989, 9, 22)); - createCustomer("Hassan", "Naseri", date(1962, 4, 15)); - //... and have the service look up one of them - final List list = service.findCustomersByName("Milad", "Naseri"); - assertThat(list, is(notNullValue())); - assertThat(list, hasSize(1)); - assertThat(list.get(0), is(customer)); - } - - @Test - public void testLoadingCustomersByFirstNames() { - createCustomer("Milad", "Naseri", null); - final Customer customer = createCustomer("Mateusz", "Stefek", null); - - final List list = service.findCustomersByFirstNames(Collections.singleton("Mateusz")); - assertThat(list, is(notNullValue())); - assertThat(list, hasSize(1)); - assertThat(list.get(0), is(customer)); - } - - @Test - public void testLookingUpByFirstNamePart() { - createCustomer("Milad", "Naseri", date(1988, 1, 1)); - final Customer eric = createCustomer("Eric", "Deandrea", date(1999, 1, 1)); - - final List list = service.findByFirstNamePart("IC"); - assertThat(list, is(notNullValue())); - assertThat(list, hasSize(1)); - assertThat(list.get(0), is(eric)); - } - - private Customer createCustomer(String firstName, String lastName, Date birthday) { - final Customer customer = new Customer(); - customer.setFirstName(firstName); - customer.setLastName(lastName); - customer.setBirthday(birthday); - return repository.save(customer); - } - - private Date date(int year, int month, int day) { - final Calendar calendar = new GregorianCalendar(); - calendar.set(Calendar.YEAR, year); - calendar.set(Calendar.MONTH, month - 1); - calendar.set(Calendar.DATE, day); - calendar.set(Calendar.HOUR, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MILLISECOND, 0); - return calendar.getTime(); - } - -} \ No newline at end of file + private DefaultCustomerService service; + private CustomerRepository repository; + + @BeforeMethod + public void setUp() { + repository = + builder() + .usingImplementation(CustomerRepositoryExampleSupport.class) + .mock(CustomerRepository.class); + service = new DefaultCustomerService(repository); + } + + @Test + public void testCustomerRegistration() { + final Date date = date(1988, 0, 1); + // let's make sure that the database is empty + assertThat(repository.count(), is(0L)); + final String firstName = "Milad"; + final String lastName = "Naseri"; + // and then register a customer + final long id = service.register(firstName, lastName, date); + // after registration, we should have exactly one record + assertThat(repository.count(), is(1L)); + // and we should be able to load the customer by it's ID + final Customer customer = repository.findById(id).orElse(null); + // and that customer should be the one we registered + assertThat(customer, is(notNullValue())); + assertThat(customer.getId(), is(id)); + assertThat(customer.getFirstName(), is(firstName)); + assertThat(customer.getLastName(), is(lastName)); + assertThat(customer.getBirthday(), is(date)); + } + + @Test + public void testLoadingCustomerById() { + // let's save a customer to the database first + final Customer customer = createCustomer("Milad", "Naseri", date(1988, 1, 1)); + // we should be able to locate that via the service + final Customer loaded = service.findCustomer(customer.getId()); + assertThat(loaded, is(notNullValue())); + assertThat(loaded.getId(), is(customer.getId())); + assertThat(loaded.getBirthday(), is(customer.getBirthday())); + assertThat(loaded.getFirstName(), is(customer.getFirstName())); + assertThat(loaded.getLastName(), is(customer.getLastName())); + } + + @Test + public void testLoadingCustomersByBirthday() { + // let's register three customers, two of which are born within [88/1/1 .. 89/12/28] + final Customer first = createCustomer("Milad", "Naseri", date(1988, 1, 1)); + final Customer second = createCustomer("Zohreh", "Sadeghi", date(1989, 9, 22)); + createCustomer("Hassan", "Naseri", date(1962, 4, 15)); + // we should be able to look up these customers using the service + final List list = + service.findCustomersByBirthday(date(1988, 1, 1), date(1989, 12, 28)); + // and the customers should be the ones indicated above + assertThat(list, is(notNullValue())); + assertThat(list, hasSize(2)); + assertThat(list, containsInAnyOrder(first, second)); + } + + @Test + public void testLoadingCustomersByFirstNameAndLastName() { + // let's save three customers ... + final Customer customer = createCustomer("Milad", "Naseri", date(1988, 1, 1)); + createCustomer("Zohreh", "Sadeghi", date(1989, 9, 22)); + createCustomer("Hassan", "Naseri", date(1962, 4, 15)); + // ... and have the service look up one of them + final List list = service.findCustomersByName("Milad", "Naseri"); + assertThat(list, is(notNullValue())); + assertThat(list, hasSize(1)); + assertThat(list.get(0), is(customer)); + } + + @Test + public void testLoadingCustomersByFirstNames() { + createCustomer("Milad", "Naseri", null); + final Customer customer = createCustomer("Mateusz", "Stefek", null); + + final List list = service.findCustomersByFirstNames(Collections.singleton("Mateusz")); + assertThat(list, is(notNullValue())); + assertThat(list, hasSize(1)); + assertThat(list.get(0), is(customer)); + } + + @Test + public void testLookingUpByFirstNamePart() { + createCustomer("Milad", "Naseri", date(1988, 1, 1)); + final Customer eric = createCustomer("Eric", "Deandrea", date(1999, 1, 1)); + + final List list = service.findByFirstNamePart("IC"); + assertThat(list, is(notNullValue())); + assertThat(list, hasSize(1)); + assertThat(list.get(0), is(eric)); + } + + private Customer createCustomer(String firstName, String lastName, Date birthday) { + final Customer customer = new Customer(); + customer.setFirstName(firstName); + customer.setLastName(lastName); + customer.setBirthday(birthday); + return repository.save(customer); + } + + private Date date(int year, int month, int day) { + final Calendar calendar = new GregorianCalendar(); + calendar.set(Calendar.YEAR, year); + calendar.set(Calendar.MONTH, month - 1); + calendar.set(Calendar.DATE, day); + calendar.set(Calendar.HOUR, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + return calendar.getTime(); + } +} diff --git a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultGroupServiceTest.java b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultGroupServiceTest.java index 8f3db13c..4b2a784b 100644 --- a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultGroupServiceTest.java +++ b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultGroupServiceTest.java @@ -26,120 +26,119 @@ */ public class DefaultGroupServiceTest { - private GroupService service; - private GroupRepository groupRepository; - private UserService userService; - private MembershipRepository membershipRepository; + private GroupService service; + private GroupRepository groupRepository; + private UserService userService; + private MembershipRepository membershipRepository; - @BeforeMethod - public void setUp() { - final Start builder = RepositoryFactoryBuilder.builder(); - groupRepository = builder.mock(GroupRepository.class); - membershipRepository = builder.mock(MembershipRepository.class); - final UserRepository userRepository = builder.mock(UserRepository.class); - service = new DefaultGroupService(groupRepository, membershipRepository); - userService = new DefaultUserService(userRepository, service); - } + @BeforeMethod + public void setUp() { + final Start builder = RepositoryFactoryBuilder.builder(); + groupRepository = builder.mock(GroupRepository.class); + membershipRepository = builder.mock(MembershipRepository.class); + final UserRepository userRepository = builder.mock(UserRepository.class); + service = new DefaultGroupService(groupRepository, membershipRepository); + userService = new DefaultUserService(userRepository, service); + } - @Test - public void testCreatingAGroup() { - assertThat(groupRepository.count(), is(0L)); - final String name = "My Group"; - final Group group = service.createGroup(name); - assertThat(group, is(notNullValue())); - assertThat(group.getName(), is(name)); - assertThat(groupRepository.count(), is(1L)); - final Group found = groupRepository.findById(group.getId()).orElse(null); - assertThat(found, is(notNullValue())); - assertThat(found.getName(), is(name)); - } + @Test + public void testCreatingAGroup() { + assertThat(groupRepository.count(), is(0L)); + final String name = "My Group"; + final Group group = service.createGroup(name); + assertThat(group, is(notNullValue())); + assertThat(group.getName(), is(name)); + assertThat(groupRepository.count(), is(1L)); + final Group found = groupRepository.findById(group.getId()).orElse(null); + assertThat(found, is(notNullValue())); + assertThat(found.getName(), is(name)); + } - @Test - public void testDeletingAnEmptyGroup() { - Group group = new Group(); - group.setName("My Group"); - group = groupRepository.save(group); - service.deleteGroup(group); - assertThat(groupRepository.count(), is(0L)); - } + @Test + public void testDeletingAnEmptyGroup() { + Group group = new Group(); + group.setName("My Group"); + group = groupRepository.save(group); + service.deleteGroup(group); + assertThat(groupRepository.count(), is(0L)); + } - @Test - public void testEstablishingMembership() { - Group group = new Group(); - group.setName("My Group"); - group = groupRepository.save(group); - final User user = userService.createUser("milad", "milad@domain.com", "123456"); - service.join(group, user); - assertThat(membershipRepository.count(), is(1L)); - final Membership membership = membershipRepository.findAll().get(0); - assertThat(membership, is(notNullValue())); - assertThat(membership.getGroup(), is(notNullValue())); - assertThat(membership.getGroup().getId(), is(group.getId())); - assertThat(membership.getUser(), is(notNullValue())); - assertThat(membership.getUser().getId(), is(user.getId())); - } + @Test + public void testEstablishingMembership() { + Group group = new Group(); + group.setName("My Group"); + group = groupRepository.save(group); + final User user = userService.createUser("milad", "milad@domain.com", "123456"); + service.join(group, user); + assertThat(membershipRepository.count(), is(1L)); + final Membership membership = membershipRepository.findAll().get(0); + assertThat(membership, is(notNullValue())); + assertThat(membership.getGroup(), is(notNullValue())); + assertThat(membership.getGroup().getId(), is(group.getId())); + assertThat(membership.getUser(), is(notNullValue())); + assertThat(membership.getUser().getId(), is(user.getId())); + } - @Test - public void testBreakingAMembership() { - Group group = new Group(); - group.setName("My Group"); - group = groupRepository.save(group); - final User user = userService.createUser("milad", "milad@domain.com", "123456"); - final Membership membership = new Membership(); - membership.setUser(user); - membership.setGroup(group); - membershipRepository.save(membership); - service.leave(group, user); - assertThat(membershipRepository.count(), is(0L)); - } + @Test + public void testBreakingAMembership() { + Group group = new Group(); + group.setName("My Group"); + group = groupRepository.save(group); + final User user = userService.createUser("milad", "milad@domain.com", "123456"); + final Membership membership = new Membership(); + membership.setUser(user); + membership.setGroup(group); + membershipRepository.save(membership); + service.leave(group, user); + assertThat(membershipRepository.count(), is(0L)); + } - @Test - public void testListingGroupMembers() { - Group group = new Group(); - group.setName("My Group"); - group = groupRepository.save(group); - final User user = userService.createUser("milad", "milad@domain.com", "123456"); - final Membership membership = new Membership(); - membership.setUser(user); - membership.setGroup(group); - membershipRepository.save(membership); - final List users = service.members(group); - assertThat(users, is(notNullValue())); - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(notNullValue())); - assertThat(users.get(0).getId(), is(user.getId())); - } + @Test + public void testListingGroupMembers() { + Group group = new Group(); + group.setName("My Group"); + group = groupRepository.save(group); + final User user = userService.createUser("milad", "milad@domain.com", "123456"); + final Membership membership = new Membership(); + membership.setUser(user); + membership.setGroup(group); + membershipRepository.save(membership); + final List users = service.members(group); + assertThat(users, is(notNullValue())); + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(notNullValue())); + assertThat(users.get(0).getId(), is(user.getId())); + } - @Test - public void testListingUserGroups() { - Group group = new Group(); - group.setName("My Group"); - group = groupRepository.save(group); - final User user = userService.createUser("milad", "milad@domain.com", "123456"); - final Membership membership = new Membership(); - membership.setUser(user); - membership.setGroup(group); - membershipRepository.save(membership); - final List groups = service.groups(user); - assertThat(groups, is(notNullValue())); - assertThat(groups, hasSize(1)); - assertThat(groups.get(0), is(notNullValue())); - assertThat(groups.get(0).getId(), is(group.getId())); - } - - @Test - public void testDeletingAGroupWithMembers() { - Group group = new Group(); - group.setName("My Group"); - group = groupRepository.save(group); - final User user = userService.createUser("milad", "milad@domain.com", "123456"); - final Membership membership = new Membership(); - membership.setUser(user); - membership.setGroup(group); - membershipRepository.save(membership); - service.deleteGroup(group); - assertThat(groupRepository.count(), is(0L)); - assertThat(membershipRepository.count(), is(0L)); - } + @Test + public void testListingUserGroups() { + Group group = new Group(); + group.setName("My Group"); + group = groupRepository.save(group); + final User user = userService.createUser("milad", "milad@domain.com", "123456"); + final Membership membership = new Membership(); + membership.setUser(user); + membership.setGroup(group); + membershipRepository.save(membership); + final List groups = service.groups(user); + assertThat(groups, is(notNullValue())); + assertThat(groups, hasSize(1)); + assertThat(groups.get(0), is(notNullValue())); + assertThat(groups.get(0).getId(), is(group.getId())); + } + @Test + public void testDeletingAGroupWithMembers() { + Group group = new Group(); + group.setName("My Group"); + group = groupRepository.save(group); + final User user = userService.createUser("milad", "milad@domain.com", "123456"); + final Membership membership = new Membership(); + membership.setUser(user); + membership.setGroup(group); + membershipRepository.save(membership); + service.deleteGroup(group); + assertThat(groupRepository.count(), is(0L)); + assertThat(membershipRepository.count(), is(0L)); + } } diff --git a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultPlaneServiceTest.java b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultPlaneServiceTest.java index 398772a9..056f0cc2 100644 --- a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultPlaneServiceTest.java +++ b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultPlaneServiceTest.java @@ -20,64 +20,65 @@ */ public class DefaultPlaneServiceTest { - private PlaneRepository repository; - private DefaultPlaneService service; + private PlaneRepository repository; + private DefaultPlaneService service; - @BeforeMethod - public void setUp() { - final RepositoryFactoryConfiguration configuration = RepositoryConfigUtils.getConfiguration(); - repository = new RepositoryMockBuilder() - .useConfiguration(configuration) - .mock(PlaneRepository.class); - service = new DefaultPlaneService(repository); - } + @BeforeMethod + public void setUp() { + final RepositoryFactoryConfiguration configuration = RepositoryConfigUtils.getConfiguration(); + repository = + new RepositoryMockBuilder().useConfiguration(configuration).mock(PlaneRepository.class); + service = new DefaultPlaneService(repository); + } - @AfterMethod - public void tearDown() { - final RepositoryFactoryConfiguration configuration = RepositoryConfigUtils.getConfiguration(); - //because the configuration is now shared, it means that the data store registry is shared across all - //the tests, too. - //This is the same as using a shared database for doing all the tests. So, at the end of the tests we need - //to clear the database after us like using a regular data store - final DataStore dataStore = configuration.getDataStoreRegistry().getDataStore(Plane.class); - dataStore.truncate(); - } + @AfterMethod + public void tearDown() { + final RepositoryFactoryConfiguration configuration = RepositoryConfigUtils.getConfiguration(); + // because the configuration is now shared, it means that the data store registry is shared + // across all + // the tests, too. + // This is the same as using a shared database for doing all the tests. So, at the end of the + // tests we need + // to clear the database after us like using a regular data store + final DataStore dataStore = + configuration.getDataStoreRegistry().getDataStore(Plane.class); + dataStore.truncate(); + } - @Test - public void testCreate() { - assertThat(repository.count(), is(0L)); - final String model = "F-22"; - final String serial = "123456"; - final Long id = service.create(model, serial); - assertThat(id, is(notNullValue())); - final Plane loaded = repository.findById(id).orElse(null); - assertThat(loaded, is(notNullValue())); - assertThat(loaded.getModel(), is(model)); - assertThat(loaded.getSerial(), is(serial)); - } + @Test + public void testCreate() { + assertThat(repository.count(), is(0L)); + final String model = "F-22"; + final String serial = "123456"; + final Long id = service.create(model, serial); + assertThat(id, is(notNullValue())); + final Plane loaded = repository.findById(id).orElse(null); + assertThat(loaded, is(notNullValue())); + assertThat(loaded.getModel(), is(model)); + assertThat(loaded.getSerial(), is(serial)); + } - @Test - public void testLookupById() { - final Plane entity = new Plane(); - entity.setModel("Boeing 747"); - entity.setSerial("123456"); - entity.setCapacity(1000); - final Plane saved = repository.save(entity); - final String model = service.lookup(saved.getId()); - assertThat(model, is(notNullValue())); - assertThat(model, is(entity.getModel())); - } + @Test + public void testLookupById() { + final Plane entity = new Plane(); + entity.setModel("Boeing 747"); + entity.setSerial("123456"); + entity.setCapacity(1000); + final Plane saved = repository.save(entity); + final String model = service.lookup(saved.getId()); + assertThat(model, is(notNullValue())); + assertThat(model, is(entity.getModel())); + } - @Test - public void testLookupBySerial() { - final Plane entity = new Plane(); - entity.setModel("Boeing 747"); - entity.setSerial("123456"); - entity.setCapacity(1000); - repository.save(entity); - final String model = service.lookup(entity.getSerial()); - assertThat(model, is(notNullValue())); - assertThat(model, is(entity.getModel())); - } - -} \ No newline at end of file + @Test + public void testLookupBySerial() { + final Plane entity = new Plane(); + entity.setModel("Boeing 747"); + entity.setSerial("123456"); + entity.setCapacity(1000); + repository.save(entity); + final String model = service.lookup(entity.getSerial()); + assertThat(model, is(notNullValue())); + assertThat(model, is(entity.getModel())); + } +} diff --git a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultUserServiceTest.java b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultUserServiceTest.java index 503761fe..8ec2d238 100644 --- a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultUserServiceTest.java +++ b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/service/impl/DefaultUserServiceTest.java @@ -1,5 +1,6 @@ package com.mmnaseri.utils.samples.spring.data.jpa.service.impl; +import com.mmnaseri.utils.samples.spring.data.jpa.model.Group; import com.mmnaseri.utils.samples.spring.data.jpa.model.User; import com.mmnaseri.utils.samples.spring.data.jpa.repository.GroupRepository; import com.mmnaseri.utils.samples.spring.data.jpa.repository.MembershipRepository; @@ -11,7 +12,11 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.util.List; + import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; @@ -24,126 +29,139 @@ */ public class DefaultUserServiceTest { - private DefaultUserService service; - private UserRepository repository; - private GroupService groupService; - private GroupRepository groupRepository; - - @BeforeMethod - public void setUp() { - final Start builder = RepositoryFactoryBuilder.builder(); - groupRepository = builder.mock(GroupRepository.class); - final MembershipRepository membershipRepository = builder.mock(MembershipRepository.class); - groupService = new DefaultGroupService(groupRepository, membershipRepository); - repository = builder.mock(UserRepository.class); - service = new DefaultUserService(repository, groupService); - } - - @Test - public void testCreatingAUser() { - assertThat(repository.count(), is(0L)); - final String username = "milad"; - final String email = "milad@mmnaseri.com"; - final String password = "123456"; - final User user = service.createUser(username, email, password); - assertThat(user, is(notNullValue())); - assertThat(user.getId(), is(notNullValue())); - assertThat(user.getUsername(), is(username)); - assertThat(user.getEmail(), is(email)); - assertThat(user.getPasswordHash(), is(not(password))); - assertThat(repository.count(), is(1L)); - final User found = repository.findById(user.getId()).orElse(null); - assertThat(found, is(notNullValue())); - assertThat(found.getUsername(), is(username)); - assertThat(found.getEmail(), is(email)); - assertThat(found.getPasswordHash(), is(user.getPasswordHash())); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCreatingADuplicateUser() { - service.createUser("milad", "email1", "123456"); - service.createUser("milad", "email2", "123456"); - } - - @Test - public void testLookingUpAUserByEmail() { - final String id = service.createUser("milad", "milad@domain.com", "123456").getId(); - final User found = service.lookup("MILAD@domain.com"); - assertThat(found, is(notNullValue())); - assertThat(found.getId(), is(id)); - } - - @Test - public void testLookingUpAUserByUsername() { - final String id = service.createUser("milad", "milad@domain.com", "123456").getId(); - final User found = service.lookup("MILAD"); - assertThat(found, is(notNullValue())); - assertThat(found.getId(), is(id)); - } - - @Test - public void testLookingForNonExistentUser() { - final User user = service.lookup("milad"); - assertThat(user, is(nullValue())); - } - - @Test - public void testAuthenticatingWithUsername() { - final String id = service.createUser("milad", "milad@domain.com", "123456").getId(); - final User user = service.authenticate("Milad", "123456"); - assertThat(user, is(notNullValue())); - assertThat(user.getId(), is(id)); - } - @Test - public void testAuthenticatingWithEmail() { - final String id = service.createUser("milad", "milad@domain.com", "123456").getId(); - final User user = service.authenticate("milad@DOMAIN.com", "123456"); - assertThat(user, is(notNullValue())); - assertThat(user.getId(), is(id)); - } - - @Test - public void testAuthenticatingWithWrongHandle() { - service.createUser("milad", "milad@domain.com", "123456"); - final User user = service.authenticate("milad@DOMAIN", "123456"); - assertThat(user, is(nullValue())); - } - - @Test - public void testAuthenticatingWithWrongPassword() { - service.createUser("milad", "milad@domain.com", "123456"); - final User user = service.authenticate("milad", "987654"); - assertThat(user, is(nullValue())); - } - - @Test - public void testDeletingAUser() { - service.createUser("milad", "milad@mmaseri.com", "123456"); - assertThat(repository.count(), is(1L)); - service.deleteUser("milad"); - assertThat(repository.count(), is(0L)); - } - - @Test - public void testChangingUserPassword() { - service.createUser("milad", "milad@mmnaseri.com", "123456"); - assertThat(service.authenticate("milad", "123456"), is(notNullValue())); - service.updatePassword("milad", "123456", "987654"); - assertThat(service.authenticate("milad", "123456"), is(nullValue())); - assertThat(service.authenticate("milad", "987654"), is(notNullValue())); - } - - @Test - public void testDeletingAUserThatIsPartOfMultipleGroups() { - final User user = service.createUser("milad", "milad@mmnaseri.com", "123456"); - groupService.join(groupService.createGroup("Group 1"), user); - groupService.join(groupService.createGroup("Group 2"), user); - groupService.join(groupService.createGroup("Group 3"), user); - groupService.join(groupService.createGroup("Group 4"), user); - assertThat(groupService.groups(user), hasSize(4)); - service.deleteUser(user.getUsername()); - assertThat(groupService.groups(user), is(Matchers.empty())); - assertThat(groupRepository.count(), is(4L)); - } - -} \ No newline at end of file + private DefaultUserService service; + private UserRepository repository; + private GroupService groupService; + private GroupRepository groupRepository; + + @BeforeMethod + public void setUp() { + final Start builder = RepositoryFactoryBuilder.builder(); + groupRepository = builder.mock(GroupRepository.class); + final MembershipRepository membershipRepository = builder.mock(MembershipRepository.class); + groupService = new DefaultGroupService(groupRepository, membershipRepository); + repository = builder.mock(UserRepository.class); + service = new DefaultUserService(repository, groupService); + } + + @Test + public void testCreatingAUser() { + assertThat(repository.count(), is(0L)); + final String username = "milad"; + final String email = "milad@mmnaseri.com"; + final String password = "123456"; + final User user = service.createUser(username, email, password); + assertThat(user, is(notNullValue())); + assertThat(user.getId(), is(notNullValue())); + assertThat(user.getUsername(), is(username)); + assertThat(user.getEmail(), is(email)); + assertThat(user.getPasswordHash(), is(not(password))); + assertThat(repository.count(), is(1L)); + final User found = repository.findById(user.getId()).orElse(null); + assertThat(found, is(notNullValue())); + assertThat(found.getUsername(), is(username)); + assertThat(found.getEmail(), is(email)); + assertThat(found.getPasswordHash(), is(user.getPasswordHash())); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testCreatingADuplicateUser() { + service.createUser("milad", "email1", "123456"); + service.createUser("milad", "email2", "123456"); + } + + @Test + public void testLookingUpAUserByEmail() { + final String id = service.createUser("milad", "milad@domain.com", "123456").getId(); + final User found = service.lookup("MILAD@domain.com"); + assertThat(found, is(notNullValue())); + assertThat(found.getId(), is(id)); + } + + @Test + public void testLookingUpAUserByUsername() { + final String id = service.createUser("milad", "milad@domain.com", "123456").getId(); + final User found = service.lookup("MILAD"); + assertThat(found, is(notNullValue())); + assertThat(found.getId(), is(id)); + } + + @Test + public void testLookingForNonExistentUser() { + final User user = service.lookup("milad"); + assertThat(user, is(nullValue())); + } + + @Test + public void testAuthenticatingWithUsername() { + final String id = service.createUser("milad", "milad@domain.com", "123456").getId(); + final User user = service.authenticate("Milad", "123456"); + assertThat(user, is(notNullValue())); + assertThat(user.getId(), is(id)); + } + + @Test + public void testAuthenticatingWithEmail() { + final String id = service.createUser("milad", "milad@domain.com", "123456").getId(); + final User user = service.authenticate("milad@DOMAIN.com", "123456"); + assertThat(user, is(notNullValue())); + assertThat(user.getId(), is(id)); + } + + @Test + public void testAuthenticatingWithWrongHandle() { + service.createUser("milad", "milad@domain.com", "123456"); + final User user = service.authenticate("milad@DOMAIN", "123456"); + assertThat(user, is(nullValue())); + } + + @Test + public void testAuthenticatingWithWrongPassword() { + service.createUser("milad", "milad@domain.com", "123456"); + final User user = service.authenticate("milad", "987654"); + assertThat(user, is(nullValue())); + } + + @Test + public void testDeletingAUser() { + service.createUser("milad", "milad@mmaseri.com", "123456"); + assertThat(repository.count(), is(1L)); + service.deleteUser("milad"); + assertThat(repository.count(), is(0L)); + } + + @Test + public void testChangingUserPassword() { + service.createUser("milad", "milad@mmnaseri.com", "123456"); + assertThat(service.authenticate("milad", "123456"), is(notNullValue())); + service.updatePassword("milad", "123456", "987654"); + assertThat(service.authenticate("milad", "123456"), is(nullValue())); + assertThat(service.authenticate("milad", "987654"), is(notNullValue())); + } + + @Test + public void testDeletingAUserThatIsPartOfMultipleGroups() { + final User user = service.createUser("milad", "milad@mmnaseri.com", "123456"); + groupService.join(groupService.createGroup("Group 1"), user); + groupService.join(groupService.createGroup("Group 2"), user); + groupService.join(groupService.createGroup("Group 3"), user); + groupService.join(groupService.createGroup("Group 4"), user); + assertThat(groupService.groups(user), hasSize(4)); + service.deleteUser(user.getUsername()); + assertThat(groupService.groups(user), is(Matchers.empty())); + assertThat(groupRepository.count(), is(4L)); + } + + @Test + public void testReadingDeactivatedUsers() { + User user = service.createUser("milad", "milad@mmnaseri.com", "123456"); + Group group = groupService.createGroup("Group 1"); + groupService.join(group, user); + + assertThat(service.deactivatedGroups(user), is(empty())); + + groupService.deactivate(group, user); + + assertThat(service.deactivatedGroups(user), contains(group)); + } +} diff --git a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/utils/RepositoryConfigUtils.java b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/utils/RepositoryConfigUtils.java index 40bc527a..aad4825e 100644 --- a/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/utils/RepositoryConfigUtils.java +++ b/spring-data-mock-sample-jpa/src/test/java/com/mmnaseri/utils/samples/spring/data/jpa/utils/RepositoryConfigUtils.java @@ -15,17 +15,18 @@ */ public final class RepositoryConfigUtils { - private static final RepositoryFactoryConfiguration CONFIGURATION = builder() - .honoringImplementation(SerialAwareEntityRepository.class, SerialAwareEntityRepositorySupport.class) - .withDefaultKeyGenerator(new ConfigurableSequentialLongKeyGenerator()) - .configure(); + private static final RepositoryFactoryConfiguration CONFIGURATION = + builder() + .honoringImplementation( + SerialAwareEntityRepository.class, SerialAwareEntityRepositorySupport.class) + .withDefaultKeyGenerator(new ConfigurableSequentialLongKeyGenerator()) + .configure(); - private RepositoryConfigUtils() { - throw new UnsupportedOperationException(); - } - - public static RepositoryFactoryConfiguration getConfiguration() { - return CONFIGURATION; - } + private RepositoryConfigUtils() { + throw new UnsupportedOperationException(); + } + public static RepositoryFactoryConfiguration getConfiguration() { + return CONFIGURATION; + } } diff --git a/spring-data-mock-sample-mongo/pom.xml b/spring-data-mock-sample-mongo/pom.xml index 2709eef9..f3cf8566 100644 --- a/spring-data-mock-sample-mongo/pom.xml +++ b/spring-data-mock-sample-mongo/pom.xml @@ -1,18 +1,19 @@ - 4.0.0 com.mmnaseri.utils spring-data-mock-sample-mongo - 1.0 + 1.0.0 Spring Data Mock: Samples (MongoDB) This module tries to demonstrate how Spring Data Mock could be used to test an application that - is using Spring Data JPA. + is using Spring Data JPA. + 2016 @@ -37,7 +38,7 @@ UTF-8 2.2.6.RELEASE 2.2.6.RELEASE - 2.1.0 + 2.1.1 7.1.0 1.3 3.8.1 diff --git a/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/model/Store.java b/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/model/Store.java index c386b61e..ced61574 100644 --- a/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/model/Store.java +++ b/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/model/Store.java @@ -5,25 +5,24 @@ @SuppressWarnings("unused") public class Store { - private ObjectId id; - private String name; - - public ObjectId getId() { - return id; - } - - public Store setId(final ObjectId id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Store setName(final String name) { - this.name = name; - return this; - } - + private ObjectId id; + private String name; + + public ObjectId getId() { + return id; + } + + public Store setId(final ObjectId id) { + this.id = id; + return this; + } + + public String getName() { + return name; + } + + public Store setName(final String name) { + this.name = name; + return this; + } } diff --git a/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/repository/StoreRepository.java b/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/repository/StoreRepository.java index f2f96967..27014ebc 100644 --- a/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/repository/StoreRepository.java +++ b/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/repository/StoreRepository.java @@ -4,7 +4,4 @@ import org.bson.types.ObjectId; import org.springframework.data.mongodb.repository.MongoRepository; -public interface StoreRepository extends MongoRepository { - - -} +public interface StoreRepository extends MongoRepository {} diff --git a/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/StoreService.java b/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/StoreService.java index 31df3860..a52ccd17 100644 --- a/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/StoreService.java +++ b/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/StoreService.java @@ -7,8 +7,7 @@ @SuppressWarnings("unused") public interface StoreService { - Store create(String name); - - Collection create(String... names); + Store create(String name); + Collection create(String... names); } diff --git a/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreService.java b/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreService.java index 4429c226..98fa650b 100644 --- a/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreService.java +++ b/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreService.java @@ -12,21 +12,22 @@ public class DefaultStoreService implements StoreService { - private final StoreRepository repository; - - public DefaultStoreService(final StoreRepository repository) { - this.repository = repository; - } - - @Override - public Store create(final String name) { - final Store store = new Store().setName(name); - return repository.save(store); - } - - @Override - public Collection create(final String... names) { - final List stores = Arrays.stream(names).map(name -> new Store().setName(name)).collect(toList()); - return repository.insert(stores); - } + private final StoreRepository repository; + + public DefaultStoreService(final StoreRepository repository) { + this.repository = repository; + } + + @Override + public Store create(final String name) { + final Store store = new Store().setName(name); + return repository.save(store); + } + + @Override + public Collection create(final String... names) { + final List stores = + Arrays.stream(names).map(name -> new Store().setName(name)).collect(toList()); + return repository.insert(stores); + } } diff --git a/spring-data-mock-sample-mongo/src/test/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreServiceTest.java b/spring-data-mock-sample-mongo/src/test/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreServiceTest.java index 5b9a40fa..17801307 100644 --- a/spring-data-mock-sample-mongo/src/test/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreServiceTest.java +++ b/spring-data-mock-sample-mongo/src/test/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreServiceTest.java @@ -10,34 +10,37 @@ import java.util.Collection; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isIn; +import static org.hamcrest.Matchers.notNullValue; public class DefaultStoreServiceTest { - private DefaultStoreService service; - - @BeforeMethod - public void setUp() { - final StoreRepository repository = new RepositoryMockBuilder().mock(StoreRepository.class); - service = new DefaultStoreService(repository); - } - - @Test - public void testCreateOne() { - final Store store = service.create("My Store"); - assertThat(store, is(notNullValue())); - assertThat(store.getName(), is("My Store")); - } - - @Test - public void testCreateMultiple() { - final Collection stores = service.create("Store #1", "Store #2"); - - assertThat(stores, is(notNullValue())); - assertThat(stores, hasSize(2)); - for (Store store : stores) { - assertThat(store.getId(), is(notNullValue())); - assertThat(store.getName(), isIn(Arrays.asList("Store #1", "Store #2"))); - } + private DefaultStoreService service; + + @BeforeMethod + public void setUp() { + final StoreRepository repository = new RepositoryMockBuilder().mock(StoreRepository.class); + service = new DefaultStoreService(repository); + } + + @Test + public void testCreateOne() { + final Store store = service.create("My Store"); + assertThat(store, is(notNullValue())); + assertThat(store.getName(), is("My Store")); + } + + @Test + public void testCreateMultiple() { + final Collection stores = service.create("Store #1", "Store #2"); + + assertThat(stores, is(notNullValue())); + assertThat(stores, hasSize(2)); + for (Store store : stores) { + assertThat(store.getId(), is(notNullValue())); + assertThat(store.getName(), isIn(Arrays.asList("Store #1", "Store #2"))); } -} \ No newline at end of file + } +} diff --git a/spring-data-mock/pom.xml b/spring-data-mock/pom.xml index d064675a..667acb65 100644 --- a/spring-data-mock/pom.xml +++ b/spring-data-mock/pom.xml @@ -27,7 +27,7 @@ com.mmnaseri.utils spring-data-mock - 2.1.0 + 2.1.1 Spring Data Mock A framework for mocking Spring Data repositories @@ -87,6 +87,7 @@ 2.2.6.RELEASE 4.3.1 3.3.0 + 3.23.0 1.0.2 @@ -98,6 +99,13 @@ commons-logging ${commons-logging.version} + + + org.eclipse.jdt + ecj + ${ecj.version} + true + com.querydsl diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/DataStoreAware.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/DataStoreAware.java index e6b6b711..bddb3b00 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/DataStoreAware.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/DataStoreAware.java @@ -3,14 +3,13 @@ import com.mmnaseri.utils.spring.data.store.DataStore; /** - * This interface is used to inject {@link DataStore the data store} into a concrete class aiming to provide method - * mapping for a repository. + * This interface is used to inject {@link DataStore the data store} into a concrete class aiming to + * provide method mapping for a repository. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public interface DataStoreAware { - void setDataStore(DataStore dataStore); - + void setDataStore(DataStore dataStore); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/IdPropertyResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/IdPropertyResolver.java index 5fb0bf7a..52cfdd88 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/IdPropertyResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/IdPropertyResolver.java @@ -1,23 +1,22 @@ package com.mmnaseri.utils.spring.data.domain; /** - * An id property resolver will be capable of looking at an entity class and find the name of the property that is the - * ID property of that class based on the expected type of the identifier. + * An id property resolver will be capable of looking at an entity class and find the name of the + * property that is the ID property of that class based on the expected type of the identifier. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) */ public interface IdPropertyResolver { - /** - * Resolves the name of the ID property. If the property is accessible through a getter, it will still - * return the name of the underlying property accessible by the getter by converting the name of the getter to the - * bare property name. - * - * @param entityType the type of the entity on which the key is defined - * @param idType the expected type (or supertype) for the ID property - * @return the name of the property that represents the key to the entity - */ - String resolve(Class entityType, Class idType); - + /** + * Resolves the name of the ID property. If the property is accessible through a getter, + * it will still return the name of the underlying property accessible by the getter by converting + * the name of the getter to the bare property name. + * + * @param entityType the type of the entity on which the key is defined + * @param idType the expected type (or supertype) for the ID property + * @return the name of the property that represents the key to the entity + */ + String resolve(Class entityType, Class idType); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Invocation.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Invocation.java index 4e6762cb..589d4aa8 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Invocation.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Invocation.java @@ -3,21 +3,17 @@ import java.lang.reflect.Method; /** - * This interface encapsulates a single invocation, regardless of the object on which the method was invoked. + * This interface encapsulates a single invocation, regardless of the object on which the method was + * invoked. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public interface Invocation { - /** - * @return the method that was invoked - */ - Method getMethod(); - - /** - * @return the arguments with which that method was invoked - */ - Object[] getArguments(); + /** @return the method that was invoked */ + Method getMethod(); + /** @return the arguments with which that method was invoked */ + Object[] getArguments(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/InvocationMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/InvocationMatcher.java index ca76f05a..4b72a741 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/InvocationMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/InvocationMatcher.java @@ -1,22 +1,22 @@ package com.mmnaseri.utils.spring.data.domain; /** - * This interface is defined to let us match an object to a set of predefined criteria based on the values passed - * through a method invocation. This is used to determine whether or not an entity in the data store matches the - * parameters passed to a query method according to the criteria defined by that query method. + * This interface is defined to let us match an object to a set of predefined criteria based on the + * values passed through a method invocation. This is used to determine whether or not an entity in + * the data store matches the parameters passed to a query method according to the criteria defined + * by that query method. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public interface InvocationMatcher { - /** - * Determines whether or not the entity matches the query - * - * @param entity the entity - * @param invocation the query method invocation - * @return {@literal true} if it was a match - */ - boolean matches(Object entity, Invocation invocation); - + /** + * Determines whether or not the entity matches the query + * + * @param entity the entity + * @param invocation the query method invocation + * @return {@literal true} if it was a match + */ + boolean matches(Object entity, Invocation invocation); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/KeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/KeyGenerator.java index c66189a4..530ba704 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/KeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/KeyGenerator.java @@ -1,19 +1,18 @@ package com.mmnaseri.utils.spring.data.domain; /** - * This interface encapsulates the process of keys being generated when we need a solid key generation scheme to be in - * place prior to entities being written to the data store. + * This interface encapsulates the process of keys being generated when we need a solid key + * generation scheme to be in place prior to entities being written to the data store. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/6/15) */ public interface KeyGenerator { - /** - * Generates a new key and returns the value - * - * @return the generated key - */ - S generate(); - + /** + * Generates a new key and returns the value + * + * @return the generated key + */ + S generate(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/KeyGeneratorAware.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/KeyGeneratorAware.java index cdb67c12..a72f4a10 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/KeyGeneratorAware.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/KeyGeneratorAware.java @@ -1,14 +1,13 @@ package com.mmnaseri.utils.spring.data.domain; /** - * This interface is used to inject {@link KeyGenerator the key generator} into a concrete class aiming to provide - * method mapping for a repository. + * This interface is used to inject {@link KeyGenerator the key generator} into a concrete class + * aiming to provide method mapping for a repository. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/8/15) */ public interface KeyGeneratorAware { - void setKeyGenerator(KeyGenerator keyGenerator); - + void setKeyGenerator(KeyGenerator keyGenerator); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/MatchedOperator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/MatchedOperator.java index e0bfb9da..c179d9cf 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/MatchedOperator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/MatchedOperator.java @@ -8,9 +8,6 @@ */ public interface MatchedOperator extends Operator { - /** - * @return the suffix that was matched when looking up this operator - */ - String getMatchedToken(); - + /** @return the suffix that was matched when looking up this operator */ + String getMatchedToken(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Matcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Matcher.java index 02980add..e6031723 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Matcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Matcher.java @@ -1,23 +1,23 @@ package com.mmnaseri.utils.spring.data.domain; /** - * This interface encapsulates the responsibility of matching a given entity to a set of parameters based on the - * operation defined for that parameter. + * This interface encapsulates the responsibility of matching a given entity to a set of parameters + * based on the operation defined for that parameter. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public interface Matcher { - /** - * Determines if the value matches the properties or not, based on the underlying operation. - * - * @param parameter the parameter for which the match is happening. - * @param value the value being matched against. - * @param properties the properties for the invocation - * @return {@literal true} if it was a match - */ - boolean matches(Parameter parameter, Object value, Object... properties); + /** + * Determines if the value matches the properties or not, based on the underlying operation. + * + * @param parameter the parameter for which the match is happening. + * @param value the value being matched against. + * @param properties the properties for the invocation + * @return {@literal true} if it was a match + */ + boolean matches(Parameter parameter, Object value, Object... properties); - boolean isApplicableTo(Class parameterType, Class[] propertiesTypes); + boolean isApplicableTo(Class parameterType, Class[] propertiesTypes); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Modifier.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Modifier.java index ffc12715..c893abb3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Modifier.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Modifier.java @@ -8,9 +8,6 @@ */ public enum Modifier { - /** - * Indicates that the parameter's case should be ignored. - */ - IGNORE_CASE - + /** Indicates that the parameter's case should be ignored. */ + IGNORE_CASE } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Operator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Operator.java index 6fff350a..f198db9b 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Operator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Operator.java @@ -8,25 +8,21 @@ */ public interface Operator { - /** - * @return the name of the operator. Used for error reporting and such. - */ - String getName(); + /** @return the name of the operator. Used for error reporting and such. */ + String getName(); - /** - * @return the number of operands this operator needs (besides the property on the entity). So, for instance, an - * equality check would require 1 operand. - */ - int getOperands(); + /** + * @return the number of operands this operator needs (besides the property on the entity). So, + * for instance, an equality check would require 1 operand. + */ + int getOperands(); - /** - * @return the matcher taking care of checking whether or not the operator applies to the current entity - */ - Matcher getMatcher(); - - /** - * @return the suffix tokens used to indicate this operator in the name of a query method - */ - String[] getTokens(); + /** + * @return the matcher taking care of checking whether or not the operator applies to the current + * entity + */ + Matcher getMatcher(); + /** @return the suffix tokens used to indicate this operator in the name of a query method */ + String[] getTokens(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/OperatorContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/OperatorContext.java index dba1e78e..208f6358 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/OperatorContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/OperatorContext.java @@ -8,18 +8,17 @@ */ public interface OperatorContext { - /** - * @param operator registers a new operator, taking care to avoid registration of new operators that override a - * predefined operator suffix. - */ - void register(Operator operator); - - /** - * Finds the operator that matches the given suffix - * - * @param suffix the suffix to look for - * @return the operator that matches the suffix or {@literal null} if none matches. - */ - Operator getBySuffix(String suffix); + /** + * @param operator registers a new operator, taking care to avoid registration of new operators + * that override a predefined operator suffix. + */ + void register(Operator operator); + /** + * Finds the operator that matches the given suffix + * + * @param suffix the suffix to look for + * @return the operator that matches the suffix or {@literal null} if none matches. + */ + Operator getBySuffix(String suffix); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Parameter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Parameter.java index fa71a7db..348252f3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Parameter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/Parameter.java @@ -3,32 +3,29 @@ import java.util.Set; /** - * This interface represents a "parameter" factored into matching a given entity to a preset criteria. + * This interface represents a "parameter" factored into matching a given entity to a preset + * criteria. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public interface Parameter { - /** - * @return the path leading to the property. This could be a nested property using the "dot notation" to separate - */ - String getPath(); + /** + * @return the path leading to the property. This could be a nested property using the "dot + * notation" to separate + */ + String getPath(); - /** - * @return the modifiers applying to the parameter - */ - Set getModifiers(); + /** @return the modifiers applying to the parameter */ + Set getModifiers(); - /** - * @return actual indices from the query method that map to the operands for this parameter. It should always follow - * that {@literal getIndices().length == getOperator().getOperands()}. - */ - int[] getIndices(); - - /** - * @return the operator for this parameter - */ - Operator getOperator(); + /** + * @return actual indices from the query method that map to the operands for this parameter. It + * should always follow that {@literal getIndices().length == getOperator().getOperands()}. + */ + int[] getIndices(); + /** @return the operator for this parameter */ + Operator getOperator(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryAware.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryAware.java index 1a9e6303..c106f527 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryAware.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryAware.java @@ -1,14 +1,13 @@ package com.mmnaseri.utils.spring.data.domain; /** - * This interface is used to inject the repository itself into a concrete class aiming to provide method mapping for a - * repository. + * This interface is used to inject the repository itself into a concrete class aiming to provide + * method mapping for a repository. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/9/15) */ public interface RepositoryAware { - void setRepository(R repository); - + void setRepository(R repository); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadata.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadata.java index b959f242..ff2e4fa8 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadata.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadata.java @@ -1,31 +1,26 @@ package com.mmnaseri.utils.spring.data.domain; /** - * This interface encapsulates metadata required from a repository for the rest of this framework to function. + * This interface encapsulates metadata required from a repository for the rest of this framework to + * function. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/19/15) */ public interface RepositoryMetadata { - /** - * @return the name of the property that will yield the key to the entities represented by this repository - */ - String getIdentifierProperty(); + /** + * @return the name of the property that will yield the key to the entities represented by this + * repository + */ + String getIdentifierProperty(); - /** - * @return the type of the key this repository uses - */ - Class getIdentifierType(); + /** @return the type of the key this repository uses */ + Class getIdentifierType(); - /** - * @return the type of the entities this repository represents - */ - Class getEntityType(); - - /** - * @return the interface for the repository where actual methods will be defined - */ - Class getRepositoryInterface(); + /** @return the type of the entities this repository represents */ + Class getEntityType(); + /** @return the interface for the repository where actual methods will be defined */ + Class getRepositoryInterface(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadataAware.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadataAware.java index 91170502..307ccd1c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadataAware.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadataAware.java @@ -1,14 +1,13 @@ package com.mmnaseri.utils.spring.data.domain; /** - * This interface is used to inject {@link RepositoryMetadata the repository metadata} into a concrete class aiming to - * provide method mapping for a repository. + * This interface is used to inject {@link RepositoryMetadata the repository metadata} into a + * concrete class aiming to provide method mapping for a repository. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public interface RepositoryMetadataAware { - void setRepositoryMetadata(RepositoryMetadata repositoryMetadata); - + void setRepositoryMetadata(RepositoryMetadata repositoryMetadata); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadataResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadataResolver.java index 69f2c759..108afa1a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadataResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/RepositoryMetadataResolver.java @@ -6,6 +6,5 @@ */ public interface RepositoryMetadataResolver { - RepositoryMetadata resolve(Class repositoryInterface); - + RepositoryMetadata resolve(Class repositoryInterface); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGenerator.java index ee4b3b0d..4b171f07 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGenerator.java @@ -6,31 +6,29 @@ import java.util.Set; /** - * This implementation will wrap the key generation process in a procedure that prevents duplicate keys from being - * generated. Since the {@link #generate() generate} method on this class is synchronized it protects - * multi-threading and race issues from messing up the key generation, so the extending classes can easily generate keys - * without having to worry about such issues. + * This implementation will wrap the key generation process in a procedure that prevents duplicate + * keys from being generated. Since the {@link #generate() generate} method on this class is + * synchronized it protects multi-threading and race issues from messing up the key + * generation, so the extending classes can easily generate keys without having to worry about such + * issues. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/8/15) */ public abstract class AbstractRandomKeyGenerator implements KeyGenerator { - private final Set used = new HashSet<>(); + private final Set used = new HashSet<>(); - @Override - public final synchronized S generate() { - S value; - do { - value = getNext(); - } while (used.contains(value)); - used.add(value); - return value; - } - - /** - * @return the next key in the sequence. This needs not be reproducible. - */ - protected abstract S getNext(); + @Override + public final synchronized S generate() { + S value; + do { + value = getNext(); + } while (used.contains(value)); + used.add(value); + return value; + } + /** @return the next key in the sequence. This needs not be reproducible. */ + protected abstract S getNext(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRepositoryMetadataResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRepositoryMetadataResolver.java index 5327be5a..70a2a89a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRepositoryMetadataResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRepositoryMetadataResolver.java @@ -9,68 +9,67 @@ import java.lang.reflect.Modifier; /** - *

This class will first check for common errors in a repository's definition before letting the resolution - * proceed any further.

+ * This class will first check for common errors in a repository's definition before letting the + * resolution proceed any further. * - *

A repository must:

+ *

A repository must: * *

    - *
  • Not be {@literal null}
  • - *
  • Be an interface
  • - *
  • Be declared as {@literal public}
  • + *
  • Not be {@literal null} + *
  • Be an interface + *
  • Be declared as {@literal public} *
* - *

Once these checks are completed, it will call {@link #resolveFromInterface(Class)} to determine the - * actual metadata.

+ *

Once these checks are completed, it will call {@link #resolveFromInterface(Class)} to + * determine the actual metadata. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) */ public abstract class AbstractRepositoryMetadataResolver implements RepositoryMetadataResolver { - private final IdPropertyResolver idPropertyResolver; + private final IdPropertyResolver idPropertyResolver; - protected AbstractRepositoryMetadataResolver() { - idPropertyResolver = new EntityIdPropertyResolver(); - } + protected AbstractRepositoryMetadataResolver() { + idPropertyResolver = new EntityIdPropertyResolver(); + } - @Override - public final RepositoryMetadata resolve(Class repositoryInterface) { - if (repositoryInterface == null) { - throw new RepositoryDefinitionException(null, "Repository interface must not be null"); - } - if (!Modifier.isInterface(repositoryInterface.getModifiers())) { - throw new RepositoryDefinitionException(repositoryInterface, - "Cannot resolve repository metadata for a class object that isn't" - + " an interface"); - } - if (!Modifier.isPublic(repositoryInterface.getModifiers())) { - throw new RepositoryDefinitionException(repositoryInterface, - "Repository interface needs to be declared as public"); - } - return resolveFromInterface(repositoryInterface); + @Override + public final RepositoryMetadata resolve(Class repositoryInterface) { + if (repositoryInterface == null) { + throw new RepositoryDefinitionException(null, "Repository interface must not be null"); } - - /** - * Determines the metadata from the given repository interface, knowing that the assumptions declared {@link - * AbstractRepositoryMetadataResolver the head of this class} now hold. - * - * @param repositoryInterface the repository interface. - * @return the resolved metadata for the given repository interface. - */ - protected abstract RepositoryMetadata resolveFromInterface(Class repositoryInterface); - - /** - * Given the type of the entity, it will determine the ID property for that entity through calling to {@link - * EntityIdPropertyResolver} - * - * @param entityType the type of the entity - * @param idType the type of the ID property - * @return the name of the ID property - */ - @SuppressWarnings("WeakerAccess") - protected String resolveIdProperty(Class entityType, Class idType) { - return idPropertyResolver.resolve(entityType, idType); + if (!Modifier.isInterface(repositoryInterface.getModifiers())) { + throw new RepositoryDefinitionException( + repositoryInterface, + "Cannot resolve repository metadata for a class object that isn't" + " an interface"); } + if (!Modifier.isPublic(repositoryInterface.getModifiers())) { + throw new RepositoryDefinitionException( + repositoryInterface, "Repository interface needs to be declared as public"); + } + return resolveFromInterface(repositoryInterface); + } + + /** + * Determines the metadata from the given repository interface, knowing that the assumptions + * declared {@link AbstractRepositoryMetadataResolver the head of this class} now hold. + * + * @param repositoryInterface the repository interface. + * @return the resolved metadata for the given repository interface. + */ + protected abstract RepositoryMetadata resolveFromInterface(Class repositoryInterface); + /** + * Given the type of the entity, it will determine the ID property for that entity through calling + * to {@link EntityIdPropertyResolver} + * + * @param entityType the type of the entity + * @param idType the type of the ID property + * @return the name of the ID property + */ + @SuppressWarnings("WeakerAccess") + protected String resolveIdProperty(Class entityType, Class idType) { + return idPropertyResolver.resolve(entityType, idType); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AnnotationRepositoryMetadataResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AnnotationRepositoryMetadataResolver.java index 76b1e6e7..9ecd21b5 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AnnotationRepositoryMetadataResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AnnotationRepositoryMetadataResolver.java @@ -5,27 +5,27 @@ import org.springframework.data.repository.RepositoryDefinition; /** - * This class will try to resolve metadata from a repository interface that has been annotated with Spring's {@link - * RepositoryDefinition @RepositoryDefinition}. If the annotation is not found, it will throw a {@link - * RepositoryDefinitionException RepositoryDefinitionException}. + * This class will try to resolve metadata from a repository interface that has been annotated with + * Spring's {@link RepositoryDefinition @RepositoryDefinition}. If the annotation is not found, it + * will throw a {@link RepositoryDefinitionException RepositoryDefinitionException}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) */ public class AnnotationRepositoryMetadataResolver extends AbstractRepositoryMetadataResolver { - @Override - protected RepositoryMetadata resolveFromInterface(Class repositoryInterface) { - final RepositoryDefinition definition = repositoryInterface.getAnnotation(RepositoryDefinition.class); - if (definition == null) { - throw new RepositoryDefinitionException(repositoryInterface, - "Expected the repository to be annotated with " - + "@RepositoryDefinition"); - } - final Class entityType = definition.domainClass(); - final Class idType = definition.idClass(); - String idProperty = resolveIdProperty(entityType, idType); - return new ImmutableRepositoryMetadata(idType, entityType, repositoryInterface, idProperty); + @Override + protected RepositoryMetadata resolveFromInterface(Class repositoryInterface) { + final RepositoryDefinition definition = + repositoryInterface.getAnnotation(RepositoryDefinition.class); + if (definition == null) { + throw new RepositoryDefinitionException( + repositoryInterface, + "Expected the repository to be annotated with " + "@RepositoryDefinition"); } - + final Class entityType = definition.domainClass(); + final Class idType = definition.idClass(); + String idProperty = resolveIdProperty(entityType, idType); + return new ImmutableRepositoryMetadata(idType, entityType, repositoryInterface, idProperty); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AssignableRepositoryMetadataResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AssignableRepositoryMetadataResolver.java index 15fd635b..66be4a08 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AssignableRepositoryMetadataResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/AssignableRepositoryMetadataResolver.java @@ -8,25 +8,27 @@ import java.util.Objects; /** - * This class will try to determine the repository metadata from the generic arguments defined by the repository - * interface, assuming that it has extended the {@link Repository Repository} interface from Spring Data Commons. + * This class will try to determine the repository metadata from the generic arguments defined by + * the repository interface, assuming that it has extended the {@link Repository Repository} + * interface from Spring Data Commons. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) */ public class AssignableRepositoryMetadataResolver extends AbstractRepositoryMetadataResolver { - @Override - protected RepositoryMetadata resolveFromInterface(Class repositoryInterface) { - if (!Repository.class.isAssignableFrom(repositoryInterface)) { - throw new RepositoryDefinitionException(repositoryInterface, - "Expected interface to extend " + Repository.class); - } - final Class[] arguments = Objects.requireNonNull(GenericTypeResolver.resolveTypeArguments(repositoryInterface, Repository.class)); - final Class entityType = arguments[0]; - final Class idType = arguments[1]; - final String idProperty = resolveIdProperty(entityType, idType); - return new ImmutableRepositoryMetadata(idType, entityType, repositoryInterface, idProperty); + @Override + protected RepositoryMetadata resolveFromInterface(Class repositoryInterface) { + if (!Repository.class.isAssignableFrom(repositoryInterface)) { + throw new RepositoryDefinitionException( + repositoryInterface, "Expected interface to extend " + Repository.class); } - + final Class[] arguments = + Objects.requireNonNull( + GenericTypeResolver.resolveTypeArguments(repositoryInterface, Repository.class)); + final Class entityType = arguments[0]; + final Class idType = arguments[1]; + final String idProperty = resolveIdProperty(entityType, idType); + return new ImmutableRepositoryMetadata(idType, entityType, repositoryInterface, idProperty); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContext.java index e1f9771a..be140bff 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContext.java @@ -2,7 +2,26 @@ import com.mmnaseri.utils.spring.data.domain.Operator; import com.mmnaseri.utils.spring.data.domain.OperatorContext; -import com.mmnaseri.utils.spring.data.domain.impl.matchers.*; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.ContainingMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.EndingWithMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsBetweenMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsEqualToMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsFalseMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsGreaterThanMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsGreaterThanOrEqualToMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsInMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsLessThanMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsLessThanOrEqualToMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsLikeMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsNotBetweenMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsNotInMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsNotLikeMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsNotMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsNotNullMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsNullMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsTrueMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.RegexMatcher; +import com.mmnaseri.utils.spring.data.domain.impl.matchers.StartingWithMatcher; import com.mmnaseri.utils.spring.data.error.DuplicateOperatorException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -12,86 +31,118 @@ import java.util.concurrent.CopyOnWriteArraySet; /** - * This class is used to store the operators used in the name of a query method. Operators are matched by the "suffixes" - * eagerly (meaning that "EqualTo" will precede over "To"). + * This class is used to store the operators used in the name of a query method. Operators are + * matched by the "suffixes" eagerly (meaning that "EqualTo" will precede over "To"). * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class DefaultOperatorContext implements OperatorContext { - private static final Log log = LogFactory.getLog(DefaultOperatorContext.class); - private final Set operators; + private static final Log log = LogFactory.getLog(DefaultOperatorContext.class); + private final Set operators; - public DefaultOperatorContext() { - this(true); - } + public DefaultOperatorContext() { + this(true); + } - public DefaultOperatorContext(boolean registerDefaults) { - operators = new CopyOnWriteArraySet<>(); - if (registerDefaults) { - log.info("Registering all the default operators"); - operators.add(new ImmutableOperator("AFTER", 1, new IsGreaterThanMatcher(), "After", "IsAfter")); - operators.add(new ImmutableOperator("BEFORE", 1, new IsLessThanMatcher(), "Before", "IsBefore")); - operators.add(new ImmutableOperator("CONTAINING", 1, new ContainingMatcher(), "Containing", "IsContaining", - "Contains")); - operators.add(new ImmutableOperator("BETWEEN", 2, new IsBetweenMatcher(), "Between", "IsBetween")); - operators.add( - new ImmutableOperator("NOT_BETWEEN", 2, new IsNotBetweenMatcher(), "NotBetween", "IsNotBetween")); - operators.add(new ImmutableOperator("ENDING_WITH", 1, new EndingWithMatcher(), "EndingWith", "IsEndingWith", - "EndsWith")); - operators.add(new ImmutableOperator("FALSE", 0, new IsFalseMatcher(), "False", "IsFalse")); - operators.add(new ImmutableOperator("GREATER_THAN", 1, new IsGreaterThanMatcher(), "GreaterThan", - "IsGreaterThan")); - operators.add(new ImmutableOperator("GREATER_THAN_EQUALS", 1, new IsGreaterThanOrEqualToMatcher(), - "GreaterThanEqual", "IsGreaterThanEqual")); - operators.add(new ImmutableOperator("IN", 1, new IsInMatcher(), "In", "IsIn")); - operators.add( - new ImmutableOperator("IS", 1, new IsEqualToMatcher(), "Is", "EqualTo", "IsEqualTo", "Equals")); - operators.add(new ImmutableOperator("NOT_NULL", 0, new IsNotNullMatcher(), "NotNull", "IsNotNull")); - operators.add(new ImmutableOperator("NULL", 0, new IsNullMatcher(), "Null", "IsNull")); - operators.add(new ImmutableOperator("LESS_THAN", 1, new IsLessThanMatcher(), "LessThan", "IsLessThan")); - operators.add(new ImmutableOperator("LESS_THAN_EQUAL", 1, new IsLessThanOrEqualToMatcher(), "LessThanEqual", - "IsLessThanEqual")); - operators.add(new ImmutableOperator("LIKE", 1, new IsLikeMatcher(), "Like", "IsLike")); - operators.add(new ImmutableOperator("NEAR", 1, null, "Near", "IsNear")); - operators.add(new ImmutableOperator("NOT", 1, new IsNotMatcher(), "IsNot", "Not", "IsNotEqualTo", - "DoesNotEqual")); - operators.add(new ImmutableOperator("NOT_IN", 1, new IsNotInMatcher(), "NotIn", "IsNotIn")); - operators.add(new ImmutableOperator("NOT_LIKE", 1, new IsNotLikeMatcher(), "NotLike", "IsNotLike")); - operators.add(new ImmutableOperator("REGEX", 1, new RegexMatcher(), "Regex", "MatchesRegex", "Matches")); - operators.add(new ImmutableOperator("STARTING_WITH", 1, new StartingWithMatcher(), "StartingWith", - "IsStartingWith", "StartsWith")); - operators.add(new ImmutableOperator("TRUE", 0, new IsTrueMatcher(), "True", "IsTrue")); - } + public DefaultOperatorContext(boolean registerDefaults) { + operators = new CopyOnWriteArraySet<>(); + if (registerDefaults) { + log.info("Registering all the default operators"); + operators.add( + new ImmutableOperator("AFTER", 1, new IsGreaterThanMatcher(), "After", "IsAfter")); + operators.add( + new ImmutableOperator("BEFORE", 1, new IsLessThanMatcher(), "Before", "IsBefore")); + operators.add( + new ImmutableOperator( + "CONTAINING", 1, new ContainingMatcher(), "Containing", "IsContaining", "Contains")); + operators.add( + new ImmutableOperator("BETWEEN", 2, new IsBetweenMatcher(), "Between", "IsBetween")); + operators.add( + new ImmutableOperator( + "NOT_BETWEEN", 2, new IsNotBetweenMatcher(), "NotBetween", "IsNotBetween")); + operators.add( + new ImmutableOperator( + "ENDING_WITH", 1, new EndingWithMatcher(), "EndingWith", "IsEndingWith", "EndsWith")); + operators.add(new ImmutableOperator("FALSE", 0, new IsFalseMatcher(), "False", "IsFalse")); + operators.add( + new ImmutableOperator( + "GREATER_THAN", 1, new IsGreaterThanMatcher(), "GreaterThan", "IsGreaterThan")); + operators.add( + new ImmutableOperator( + "GREATER_THAN_EQUALS", + 1, + new IsGreaterThanOrEqualToMatcher(), + "GreaterThanEqual", + "IsGreaterThanEqual")); + operators.add(new ImmutableOperator("IN", 1, new IsInMatcher(), "In", "IsIn")); + operators.add( + new ImmutableOperator( + "IS", 1, new IsEqualToMatcher(), "Is", "EqualTo", "IsEqualTo", "Equals")); + operators.add( + new ImmutableOperator("NOT_NULL", 0, new IsNotNullMatcher(), "NotNull", "IsNotNull")); + operators.add(new ImmutableOperator("NULL", 0, new IsNullMatcher(), "Null", "IsNull")); + operators.add( + new ImmutableOperator("LESS_THAN", 1, new IsLessThanMatcher(), "LessThan", "IsLessThan")); + operators.add( + new ImmutableOperator( + "LESS_THAN_EQUAL", + 1, + new IsLessThanOrEqualToMatcher(), + "LessThanEqual", + "IsLessThanEqual")); + operators.add(new ImmutableOperator("LIKE", 1, new IsLikeMatcher(), "Like", "IsLike")); + operators.add(new ImmutableOperator("NEAR", 1, null, "Near", "IsNear")); + operators.add( + new ImmutableOperator( + "NOT", 1, new IsNotMatcher(), "IsNot", "Not", "IsNotEqualTo", "DoesNotEqual")); + operators.add(new ImmutableOperator("NOT_IN", 1, new IsNotInMatcher(), "NotIn", "IsNotIn")); + operators.add( + new ImmutableOperator("NOT_LIKE", 1, new IsNotLikeMatcher(), "NotLike", "IsNotLike")); + operators.add( + new ImmutableOperator( + "REGEX", 1, new RegexMatcher(), "Regex", "MatchesRegex", "Matches")); + operators.add( + new ImmutableOperator( + "STARTING_WITH", + 1, + new StartingWithMatcher(), + "StartingWith", + "IsStartingWith", + "StartsWith")); + operators.add(new ImmutableOperator("TRUE", 0, new IsTrueMatcher(), "True", "IsTrue")); } + } - @Override - public void register(Operator operator) { - log.info("Registering operator " + operator.getName() + " which will respond to suffixes " + Arrays - .toString(operator.getTokens())); - for (Operator item : operators) { - for (String token : item.getTokens()) { - for (String newToken : operator.getTokens()) { - if (newToken.equals(token)) { - throw new DuplicateOperatorException(item, token); - } - } - } + @Override + public void register(Operator operator) { + log.info( + "Registering operator " + + operator.getName() + + " which will respond to suffixes " + + Arrays.toString(operator.getTokens())); + for (Operator item : operators) { + for (String token : item.getTokens()) { + for (String newToken : operator.getTokens()) { + if (newToken.equals(token)) { + throw new DuplicateOperatorException(item, token); + } } - operators.add(operator); + } } + operators.add(operator); + } - @Override - public Operator getBySuffix(String suffix) { - for (Operator operator : operators) { - for (String token : operator.getTokens()) { - if (token.equals(suffix)) { - return operator; - } - } + @Override + public Operator getBySuffix(String suffix) { + for (Operator operator : operators) { + for (String token : operator.getTokens()) { + if (token.equals(suffix)) { + return operator; } - return null; + } } - + return null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultRepositoryMetadataResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultRepositoryMetadataResolver.java index 1982d638..a3f5f902 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultRepositoryMetadataResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultRepositoryMetadataResolver.java @@ -6,15 +6,16 @@ import org.springframework.data.repository.RepositoryDefinition; /** - *

This resolver will combine generic based and annotation based metadata resolution and deliver both in a single - * package.

+ * This resolver will combine generic based and annotation based metadata resolution and deliver + * both in a single package. * - *

This is the order in which the resolution will take place:

+ *

This is the order in which the resolution will take place: * *

    - *
  1. It will first try to determine the definition by looking at {@link AnnotationRepositoryMetadataResolver - * annotations}.
  2. - *
  3. It will then try to resolve the metadata using {@link AssignableRepositoryMetadataResolver inheritance}.
  4. + *
  5. It will first try to determine the definition by looking at {@link + * AnnotationRepositoryMetadataResolver annotations}. + *
  6. It will then try to resolve the metadata using {@link AssignableRepositoryMetadataResolver + * inheritance}. *
* * @author Milad Naseri (m.m.naseri@gmail.com) @@ -22,24 +23,23 @@ */ public class DefaultRepositoryMetadataResolver extends AbstractRepositoryMetadataResolver { - private static final Log log = LogFactory.getLog(DefaultRepositoryMetadataResolver.class); - private final AssignableRepositoryMetadataResolver assignableRepositoryMetadataResolver = - new AssignableRepositoryMetadataResolver(); - private final AnnotationRepositoryMetadataResolver annotationRepositoryMetadataResolver = - new AnnotationRepositoryMetadataResolver(); + private static final Log log = LogFactory.getLog(DefaultRepositoryMetadataResolver.class); + private final AssignableRepositoryMetadataResolver assignableRepositoryMetadataResolver = + new AssignableRepositoryMetadataResolver(); + private final AnnotationRepositoryMetadataResolver annotationRepositoryMetadataResolver = + new AnnotationRepositoryMetadataResolver(); - @Override - protected RepositoryMetadata resolveFromInterface(Class repositoryInterface) { - if (repositoryInterface.isAnnotationPresent(RepositoryDefinition.class)) { - log.info( - "Since the repository interface was annotated with @RepositoryDefinition we will try to resolve " - + "the metadata using the provided annotation"); - return annotationRepositoryMetadataResolver.resolve(repositoryInterface); - } - log.info( - "Since no annotation was found on the repository, we will try to read the metadata from the generic " - + "type parameters derived from the Repository interface"); - return assignableRepositoryMetadataResolver.resolve(repositoryInterface); + @Override + protected RepositoryMetadata resolveFromInterface(Class repositoryInterface) { + if (repositoryInterface.isAnnotationPresent(RepositoryDefinition.class)) { + log.info( + "Since the repository interface was annotated with @RepositoryDefinition we will try to resolve " + + "the metadata using the provided annotation"); + return annotationRepositoryMetadataResolver.resolve(repositoryInterface); } - + log.info( + "Since no annotation was found on the repository, we will try to read the metadata from the generic " + + "type parameters derived from the Repository interface"); + return assignableRepositoryMetadataResolver.resolve(repositoryInterface); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DescribedDataStoreOperation.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DescribedDataStoreOperation.java index bb87ed96..dc7d2e89 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DescribedDataStoreOperation.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/DescribedDataStoreOperation.java @@ -13,41 +13,42 @@ import java.util.List; /** - * This is a data store operation that has a description attached to it. This means that it is a select operation that - * is capable of taking care of applying a function to a given selection of objects. + * This is a data store operation that has a description attached to it. This means that it is a + * select operation that is capable of taking care of applying a function to a given selection of + * objects. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class DescribedDataStoreOperation implements DataStoreOperation { - private static final Log log = LogFactory.getLog(DescribedDataStoreOperation.class); - private final SelectDataStoreOperation selectOperation; - private final DataFunctionRegistry functionRegistry; - - public DescribedDataStoreOperation(SelectDataStoreOperation selectOperation, - DataFunctionRegistry functionRegistry) { - this.selectOperation = selectOperation; - this.functionRegistry = functionRegistry; - } - - @Override - public Object execute(DataStore store, RepositoryConfiguration configuration, Invocation invocation) { - log.info("Trying to select the data from the data store"); - final List selection = selectOperation.execute(store, configuration, invocation); - final QueryDescriptor descriptor = selectOperation.getDescriptor(); - if (descriptor.getFunction() == null) { - log.info("No function was specified for the current selection"); - return selection; - } - log.info("Executing function " + descriptor.getFunction() + " on the selected items"); - final DataFunction function = functionRegistry.getFunction(descriptor.getFunction()); - return function.apply(store, descriptor, configuration, selection); + private static final Log log = LogFactory.getLog(DescribedDataStoreOperation.class); + private final SelectDataStoreOperation selectOperation; + private final DataFunctionRegistry functionRegistry; + + public DescribedDataStoreOperation( + SelectDataStoreOperation selectOperation, DataFunctionRegistry functionRegistry) { + this.selectOperation = selectOperation; + this.functionRegistry = functionRegistry; + } + + @Override + public Object execute( + DataStore store, RepositoryConfiguration configuration, Invocation invocation) { + log.info("Trying to select the data from the data store"); + final List selection = selectOperation.execute(store, configuration, invocation); + final QueryDescriptor descriptor = selectOperation.getDescriptor(); + if (descriptor.getFunction() == null) { + log.info("No function was specified for the current selection"); + return selection; } - - @Override - public String toString() { - return selectOperation.toString(); - } - + log.info("Executing function " + descriptor.getFunction() + " on the selected items"); + final DataFunction function = functionRegistry.getFunction(descriptor.getFunction()); + return function.apply(store, descriptor, configuration, selection); + } + + @Override + public String toString() { + return selectOperation.toString(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableInvocation.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableInvocation.java index 9045a8cf..756674f5 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableInvocation.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableInvocation.java @@ -13,27 +13,26 @@ */ public class ImmutableInvocation implements Invocation { - private final Method method; - private final Object[] arguments; - - public ImmutableInvocation(Method method, Object[] arguments) { - this.method = method; - this.arguments = arguments; - } - - @Override - public Method getMethod() { - return method; - } - - @Override - public Object[] getArguments() { - return arguments; - } - - @Override - public String toString() { - return method + ", " + Arrays.toString(arguments); - } - + private final Method method; + private final Object[] arguments; + + public ImmutableInvocation(Method method, Object[] arguments) { + this.method = method; + this.arguments = arguments; + } + + @Override + public Method getMethod() { + return method; + } + + @Override + public Object[] getArguments() { + return arguments; + } + + @Override + public String toString() { + return method + ", " + Arrays.toString(arguments); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperator.java index d099f3dd..1e90aee4 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperator.java @@ -11,37 +11,36 @@ @SuppressWarnings("WeakerAccess") public class ImmutableMatchedOperator implements MatchedOperator { - private final Operator original; - private final String matchedToken; - - public ImmutableMatchedOperator(Operator original, String matchedToken) { - this.original = original; - this.matchedToken = matchedToken; - } - - @Override - public String getName() { - return original.getName(); - } - - @Override - public int getOperands() { - return original.getOperands(); - } - - @Override - public Matcher getMatcher() { - return original.getMatcher(); - } - - @Override - public String[] getTokens() { - return original.getTokens(); - } - - @Override - public String getMatchedToken() { - return matchedToken; - } - + private final Operator original; + private final String matchedToken; + + public ImmutableMatchedOperator(Operator original, String matchedToken) { + this.original = original; + this.matchedToken = matchedToken; + } + + @Override + public String getName() { + return original.getName(); + } + + @Override + public int getOperands() { + return original.getOperands(); + } + + @Override + public Matcher getMatcher() { + return original.getMatcher(); + } + + @Override + public String[] getTokens() { + return original.getTokens(); + } + + @Override + public String getMatchedToken() { + return matchedToken; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableOperator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableOperator.java index e8065d9d..1a42118d 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableOperator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableOperator.java @@ -11,40 +11,39 @@ */ public class ImmutableOperator implements Operator { - private final String name; - private final int operands; - private final Matcher matcher; - private final String[] tokens; - - public ImmutableOperator(String name, int operands, Matcher matcher, String... tokens) { - this.name = name; - this.operands = operands; - this.matcher = matcher; - this.tokens = tokens; - } - - public String getName() { - return name; - } - - @Override - public int getOperands() { - return operands; - } - - @Override - public Matcher getMatcher() { - return matcher; - } - - @Override - public String[] getTokens() { - return tokens; - } - - @Override - public String toString() { - return name; - } - + private final String name; + private final int operands; + private final Matcher matcher; + private final String[] tokens; + + public ImmutableOperator(String name, int operands, Matcher matcher, String... tokens) { + this.name = name; + this.operands = operands; + this.matcher = matcher; + this.tokens = tokens; + } + + public String getName() { + return name; + } + + @Override + public int getOperands() { + return operands; + } + + @Override + public Matcher getMatcher() { + return matcher; + } + + @Override + public String[] getTokens() { + return tokens; + } + + @Override + public String toString() { + return name; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameter.java index cbccebc3..7f1da538 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameter.java @@ -17,41 +17,41 @@ */ public class ImmutableParameter implements Parameter { - private final String path; - private final Set modifiers; - private final int[] indices; - private final Operator operator; - - public ImmutableParameter(String path, Set modifiers, int[] indices, Operator operator) { - this.path = path; - this.operator = operator; - this.modifiers = modifiers == null ? Collections.emptySet() : new HashSet<>(modifiers); - this.indices = indices; - } - - @Override - public String getPath() { - return path; - } - - @Override - public Set getModifiers() { - return Collections.unmodifiableSet(modifiers); - } - - @Override - public int[] getIndices() { - return indices; - } - - @Override - public Operator getOperator() { - return operator; - } - - @Override - public String toString() { - return "(" + path + "," + operator + "," + Arrays.toString(indices) + "," + modifiers + ")"; - } - + private final String path; + private final Set modifiers; + private final int[] indices; + private final Operator operator; + + public ImmutableParameter( + String path, Set modifiers, int[] indices, Operator operator) { + this.path = path; + this.operator = operator; + this.modifiers = modifiers == null ? Collections.emptySet() : new HashSet<>(modifiers); + this.indices = indices; + } + + @Override + public String getPath() { + return path; + } + + @Override + public Set getModifiers() { + return Collections.unmodifiableSet(modifiers); + } + + @Override + public int[] getIndices() { + return indices; + } + + @Override + public Operator getOperator() { + return operator; + } + + @Override + public String toString() { + return "(" + path + "," + operator + "," + Arrays.toString(indices) + "," + modifiers + ")"; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableRepositoryMetadata.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableRepositoryMetadata.java index 3fa89ec6..4fb997db 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableRepositoryMetadata.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableRepositoryMetadata.java @@ -10,37 +10,39 @@ */ public class ImmutableRepositoryMetadata implements RepositoryMetadata { - private final Class identifierType; - private final Class entityType; - private final Class repositoryInterface; - private final String identifier; - - public ImmutableRepositoryMetadata(Class identifierType, Class entityType, Class repositoryInterface, - String identifier) { - this.identifierType = identifierType; - this.entityType = entityType; - this.repositoryInterface = repositoryInterface; - this.identifier = identifier; - } - - @Override - public String getIdentifierProperty() { - return identifier; - } - - @Override - public Class getIdentifierType() { - return identifierType; - } - - @Override - public Class getEntityType() { - return entityType; - } - - @Override - public Class getRepositoryInterface() { - return repositoryInterface; - } - + private final Class identifierType; + private final Class entityType; + private final Class repositoryInterface; + private final String identifier; + + public ImmutableRepositoryMetadata( + Class identifierType, + Class entityType, + Class repositoryInterface, + String identifier) { + this.identifierType = identifierType; + this.entityType = entityType; + this.repositoryInterface = repositoryInterface; + this.identifier = identifier; + } + + @Override + public String getIdentifierProperty() { + return identifier; + } + + @Override + public Class getIdentifierType() { + return identifierType; + } + + @Override + public Class getEntityType() { + return entityType; + } + + @Override + public Class getRepositoryInterface() { + return repositoryInterface; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/MethodInvocationDataStoreOperation.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/MethodInvocationDataStoreOperation.java index 37c86291..e55f37a6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/MethodInvocationDataStoreOperation.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/MethodInvocationDataStoreOperation.java @@ -12,48 +12,49 @@ import java.lang.reflect.Method; /** - * This is a data store operation that delivers the operation by calling to a delegate method. This means that the - * results of the operation are the same as what was returned by the method itself. + * This is a data store operation that delivers the operation by calling to a delegate method. This + * means that the results of the operation are the same as what was returned by the method itself. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class MethodInvocationDataStoreOperation implements DataStoreOperation { - private static final Log log = LogFactory.getLog(MethodInvocationDataStoreOperation.class); - private final Object instance; - private final Method method; - - public MethodInvocationDataStoreOperation(Object instance, Method method) { - this.instance = instance; - this.method = method; - } - - @Override - public Object execute(DataStore store, RepositoryConfiguration configuration, Invocation invocation) { - final Object result; - try { - log.info("Invoking method " + method + " to handle invocation " + invocation); - result = method.invoke(instance, invocation.getArguments()); - } catch (IllegalAccessException e) { - throw new DataOperationExecutionException("Failed to access target method: " + method, e); - } catch (InvocationTargetException e) { - throw new DataOperationExecutionException("Method call resulted in internal error: " + method, - e.getTargetException()); - } - return result; + private static final Log log = LogFactory.getLog(MethodInvocationDataStoreOperation.class); + private final Object instance; + private final Method method; + + public MethodInvocationDataStoreOperation(Object instance, Method method) { + this.instance = instance; + this.method = method; + } + + @Override + public Object execute( + DataStore store, RepositoryConfiguration configuration, Invocation invocation) { + final Object result; + try { + log.info("Invoking method " + method + " to handle invocation " + invocation); + result = method.invoke(instance, invocation.getArguments()); + } catch (IllegalAccessException e) { + throw new DataOperationExecutionException("Failed to access target method: " + method, e); + } catch (InvocationTargetException e) { + throw new DataOperationExecutionException( + "Method call resulted in internal error: " + method, e.getTargetException()); } + return result; + } - public Object getInstance() { - return instance; - } + public Object getInstance() { + return instance; + } - public Method getMethod() { - return method; - } + public Method getMethod() { + return method; + } - @Override - public String toString() { - return method + " on " + instance; - } + @Override + public String toString() { + return method + " on " + instance; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/MethodQueryDescriptionExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/MethodQueryDescriptionExtractor.java index 9ed8ecaf..367d3634 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/MethodQueryDescriptionExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/MethodQueryDescriptionExtractor.java @@ -1,11 +1,28 @@ package com.mmnaseri.utils.spring.data.domain.impl; import com.google.common.base.Joiner; -import com.mmnaseri.utils.spring.data.domain.*; +import com.mmnaseri.utils.spring.data.domain.MatchedOperator; +import com.mmnaseri.utils.spring.data.domain.Modifier; +import com.mmnaseri.utils.spring.data.domain.Operator; +import com.mmnaseri.utils.spring.data.domain.OperatorContext; +import com.mmnaseri.utils.spring.data.domain.Parameter; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata; import com.mmnaseri.utils.spring.data.error.QueryParserException; import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration; -import com.mmnaseri.utils.spring.data.query.*; -import com.mmnaseri.utils.spring.data.query.impl.*; +import com.mmnaseri.utils.spring.data.query.NullHandling; +import com.mmnaseri.utils.spring.data.query.Order; +import com.mmnaseri.utils.spring.data.query.PageParameterExtractor; +import com.mmnaseri.utils.spring.data.query.PropertyDescriptor; +import com.mmnaseri.utils.spring.data.query.QueryDescriptor; +import com.mmnaseri.utils.spring.data.query.SortDirection; +import com.mmnaseri.utils.spring.data.query.SortParameterExtractor; +import com.mmnaseri.utils.spring.data.query.impl.DefaultQueryDescriptor; +import com.mmnaseri.utils.spring.data.query.impl.DirectSortParameterExtractor; +import com.mmnaseri.utils.spring.data.query.impl.ImmutableOrder; +import com.mmnaseri.utils.spring.data.query.impl.ImmutableSort; +import com.mmnaseri.utils.spring.data.query.impl.PageablePageParameterExtractor; +import com.mmnaseri.utils.spring.data.query.impl.PageableSortParameterExtractor; +import com.mmnaseri.utils.spring.data.query.impl.WrappedSortParameterExtractor; import com.mmnaseri.utils.spring.data.string.DocumentReader; import com.mmnaseri.utils.spring.data.string.impl.DefaultDocumentReader; import com.mmnaseri.utils.spring.data.tools.PropertyUtils; @@ -14,91 +31,88 @@ import org.springframework.data.domain.Sort; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; import java.util.regex.Pattern; /** - *

This class will parse a query method's name and extract a - * {@link com.mmnaseri.utils.spring.data.dsl.factory.QueryDescription query description} from that name.

+ * This class will parse a query method's name and extract a {@link + * com.mmnaseri.utils.spring.data.dsl.factory.QueryDescription query description} from that name. * - *

In parsing the name, words are considered as being tokens in a camel case name.

+ *

In parsing the name, words are considered as being tokens in a camel case name. * - *

Here is how a query method's name is parsed:

+ *

Here is how a query method's name is parsed: * *

    - *
  1. We will look at the first word in the name until we reach one of the keywords that says we are specifying - * a limit, or - * we are going over the criteria defined by the method. This prefix will be called the "function name" for the - * operation - * defined by the query method. If the function name is one of "read", "find", "query", "get", "load", or - * "select", we will - * set the function name to {@literal null} to indicate that no special function should be applied to the result - * set. We - * are only looking at the first word to let you be more verbose about the purpose of your query (e.g. - * {@literal findAllGreatPeopleByGreatnessGreaterThan(Integer greatness)} will still resolve to the function - * {@literal find}, which will ultimately be returned as {@literal null}
  2. - *
  3. We will then look for any of these patterns: - *
      - *
    • The word {@literal By}, signifying that we are ready to start parsing the query criteria
    • - *
    • One of the words {@literal First} or {@literal Top}, signifying that we should look for a limit on the - * number - * of results returned.
    • - *
    • The word {@literal Distinct}, signifying that the results should include no duplicates.
    • - *
    - *
  4. - *
  5. If the word {@literal First} had appeared, we will see if it is followed by an integer. If it is, that - * will be the limit. - * If not, a limit of {@literal 1} is assumed.
  6. - *
  7. If the word {@literal Top} had appeared, we will look for the limit number, which should be an integer - * value.
  8. - *
  9. At this point, we will continue until we see 'By'. In the above, steps, we will look for the keywords in - * any order, - * and there can be any words in between. So, {@literal getTop5StudentsWhoAreAwesomeDistinct} is the same as - * {@literal getTop5Distinct}
  10. - *
  11. Once we reach the word "By", we will read the query in terms of "decision branches". Branches are - * separated using the keyword - * "Or", and each branch is a series of conjunctions. So, while you are separating your conditions with "And", - * you are in the same branch.
  12. - *
  13. A single branch consists of the pattern: "(Property)(Operator)?((And)(Property)(Operator)?)*". If the - * operator is missing, "Is" is assumed. - * Properties must match a proper property in the domain object. So, if you have "AddressZipPrefix" in your query - * method name, there must be a property - * reachable by one of the following paths in your domain class (in the given order): - *
      - *
    • {@literal addressZipPrefix}
    • - *
    • {@literal addressZip.prefix}
    • - *
    • {@literal address.zipPrefix}
    • - *
    • {@literal address.zip.prefix}
    • - *
    - * Note that if you have both the "addressZip" and "address.zip" in your entity, the first will be taken up. To - * force the parser to choose the former, use - * the underscore character ({@literal _}) in place of the dot, like so: "{@literal Address_Zip}"
    - * Depending on the operator that was matched to the suffix provided (e.g. GreaterThan, Is, etc.), a given number - * of method parameters will be matched - * as the operands to that operator. For instance, "Is" requires two values to determine equality, one if the - * property found on the domain object, and - * the other must be provided by the query method.
    - * The operators themselves are scanned eagerly and based on the set of operators defined in the - * {@link OperatorContext}. - *
  14. - *
  15. We continue the pattern indicated above, until we reach the end of the method name, or we reach the - * "OrderBy" pattern. Once we see "OrderBy" - * we expect the following pattern: "((Property)(Direction))+", wherein "Property" must follow the same rule as - * above, and "Direction" is one of - * "Asc" and "Desc" to indicate "ascending" and "descending" ordering, respectively.
  16. - *
  17. Finally, we look to see if the keyword "AllIgnoreCase" or {@link #ALL_IGNORE_CASE_SUFFIX one of its - * variations} is present at the end of the - * query name, which will indicate all applicable comparisons should be case-insensitive.
  18. - *
  19. At the end, we allow one additional parameter for the query method, which can be of either of these types: - *
      - *
    • {@link Sort Sort}: to indicate a dynamic sort defined at runtime. If a static sort is already - * indicated via the pattern above, this will - * result in an error.
    • - *
    • {@link Pageable Pageable}: to indicate a paging (and, possibly, sorting) at runtime. If a static sort - * is already indicated via the pattern - * above, the sort portion of this parameter will be always ignored.
    • - *
    - *
  20. + *
  21. We will look at the first word in the name until we reach one of the keywords that says we + * are specifying a limit, or we are going over the criteria defined by the method. This + * prefix will be called the "function name" for the operation defined by the query method. If + * the function name is one of "read", "find", "query", "get", "load", or "select", we will + * set the function name to {@literal null} to indicate that no special function should be + * applied to the result set. We are only looking at the first word to let you be more verbose + * about the purpose of your query (e.g. {@literal + * findAllGreatPeopleByGreatnessGreaterThan(Integer greatness)} will still resolve to the + * function {@literal find}, which will ultimately be returned as {@literal null} + *
  22. We will then look for any of these patterns: + *
      + *
    • The word {@literal By}, signifying that we are ready to start parsing the query + * criteria + *
    • One of the words {@literal First} or {@literal Top}, signifying that we should look + * for a limit on the number of results returned. + *
    • The word {@literal Distinct}, signifying that the results should include no + * duplicates. + *
    + *
  23. If the word {@literal First} had appeared, we will see if it is followed by an integer. If + * it is, that will be the limit. If not, a limit of {@literal 1} is assumed. + *
  24. If the word {@literal Top} had appeared, we will look for the limit number, which should be + * an integer value. + *
  25. At this point, we will continue until we see 'By'. In the above, steps, we will look for + * the keywords in any order, and there can be any words in between. So, {@literal + * getTop5StudentsWhoAreAwesomeDistinct} is the same as {@literal getTop5Distinct} + *
  26. Once we reach the word "By", we will read the query in terms of "decision branches". + * Branches are separated using the keyword "Or", and each branch is a series of conjunctions. + * So, while you are separating your conditions with "And", you are in the same branch. + *
  27. A single branch consists of the pattern: + * "(Property)(Operator)?((And)(Property)(Operator)?)*". If the operator is missing, "Is" is + * assumed. Properties must match a proper property in the domain object. So, if you have + * "AddressZipPrefix" in your query method name, there must be a property reachable by one of + * the following paths in your domain class (in the given order): + *
      + *
    • {@literal addressZipPrefix} + *
    • {@literal addressZip.prefix} + *
    • {@literal address.zipPrefix} + *
    • {@literal address.zip.prefix} + *
    + * Note that if you have both the "addressZip" and "address.zip" in your entity, the first + * will be taken up. To force the parser to choose the former, use the underscore character + * ({@literal _}) in place of the dot, like so: "{@literal Address_Zip}"
    + * Depending on the operator that was matched to the suffix provided (e.g. GreaterThan, Is, + * etc.), a given number of method parameters will be matched as the operands to that + * operator. For instance, "Is" requires two values to determine equality, one if the property + * found on the domain object, and the other must be provided by the query method.
    + * The operators themselves are scanned eagerly and based on the set of operators defined in + * the {@link OperatorContext}. + *
  28. We continue the pattern indicated above, until we reach the end of the method name, or we + * reach the "OrderBy" pattern. Once we see "OrderBy" we expect the following pattern: + * "((Property)(Direction))+", wherein "Property" must follow the same rule as above, and + * "Direction" is one of "Asc" and "Desc" to indicate "ascending" and "descending" ordering, + * respectively. + *
  29. Finally, we look to see if the keyword "AllIgnoreCase" or {@link #ALL_IGNORE_CASE_SUFFIX + * one of its variations} is present at the end of the query name, which will indicate all + * applicable comparisons should be case-insensitive. + *
  30. At the end, we allow one additional parameter for the query method, which can be of either + * of these types: + *
      + *
    • {@link Sort Sort}: to indicate a dynamic sort defined at runtime. If a static sort is + * already indicated via the pattern above, this will result in an error. + *
    • {@link Pageable Pageable}: to indicate a paging (and, possibly, sorting) at runtime. + * If a static sort is already indicated via the pattern above, the sort portion of this + * parameter will be always ignored. + *
    *
* * @author Milad Naseri (m.m.naseri@gmail.com) @@ -106,349 +120,416 @@ */ public class MethodQueryDescriptionExtractor implements QueryDescriptionExtractor { - private static final String ALL_IGNORE_CASE_SUFFIX = "(AllIgnoreCase|AllIgnoresCase|AllIgnoringCase)$"; - private static final String IGNORE_CASE_PARTIAL = "(IgnoreCase|IgnoresCase|IgnoringCase)"; - private static final String ASC_SUFFIX = "Asc"; - private static final String DESC_SUFFIX = "Desc"; - private static final String DEFAULT_OPERATOR_SUFFIX = "Is"; + private static final String ALL_IGNORE_CASE_SUFFIX = + "(AllIgnoreCase|AllIgnoresCase|AllIgnoringCase)$"; + private static final String IGNORE_CASE_PARTIAL = "(IgnoreCase|IgnoresCase|IgnoringCase)"; + private static final String ASC_SUFFIX = "Asc"; + private static final String DESC_SUFFIX = "Desc"; + private static final String DEFAULT_OPERATOR_SUFFIX = "Is"; - private final OperatorContext operatorContext; + private final OperatorContext operatorContext; - public MethodQueryDescriptionExtractor(OperatorContext operatorContext) { - this.operatorContext = operatorContext; - } + public MethodQueryDescriptionExtractor(OperatorContext operatorContext) { + this.operatorContext = operatorContext; + } - /** - * Extracts query description from a method's name. This will be done according to {@link - * MethodQueryDescriptionExtractor the parsing rules} for this extractor. - * - * @param repositoryMetadata the repository metadata for this method. - * @param configuration the repository factory configuration. This will be passed down through the - * description. - * @param method the query method - * @return the description for the query - */ - @Override - public QueryDescriptor extract(RepositoryMetadata repositoryMetadata, RepositoryFactoryConfiguration configuration, - Method method) { - String methodName = method.getName(); - //check to see if the AllIgnoreCase flag is set - boolean allIgnoreCase = methodName.matches(".*" + ALL_IGNORE_CASE_SUFFIX); - //we need to unify method name afterwards - methodName = allIgnoreCase ? methodName.replaceFirst(ALL_IGNORE_CASE_SUFFIX, "") : methodName; - //create a document reader for processing method name - final DocumentReader reader = new DefaultDocumentReader(methodName); - String function = parseFunctionName(method, reader); - final QueryModifiers queryModifiers = parseQueryModifiers(method, reader); - //this is the extractor used for getting paging data - final PageParameterExtractor pageExtractor; - //this is the extractor used for getting sorting data - SortParameterExtractor sortExtractor = null; - //these are decision branches, each of which denoting an AND clause - final List> branches = new ArrayList<>(); - //if the method name simply was the function name, no metadata can be extracted - if (!reader.hasMore()) { - pageExtractor = null; - } else { - reader.expect("By"); - if (!reader.hasMore()) { - throw new QueryParserException(method.getDeclaringClass(), "Query method name cannot end with `By`"); - } - //current parameter index - int index = parseExpression(repositoryMetadata, method, allIgnoreCase, reader, branches); - final com.mmnaseri.utils.spring.data.query.Sort sort = parseSort(repositoryMetadata, method, reader); - pageExtractor = getPageParameterExtractor(method, index, sort); - sortExtractor = getSortParameterExtractor(method, index, sort); - } - return new DefaultQueryDescriptor(queryModifiers.isDistinct(), function, queryModifiers.getLimit(), - pageExtractor, sortExtractor, branches, configuration, repositoryMetadata); + /** + * Extracts query description from a method's name. This will be done according to {@link + * MethodQueryDescriptionExtractor the parsing rules} for this extractor. + * + * @param repositoryMetadata the repository metadata for this method. + * @param configuration the repository factory configuration. This will be passed down through the + * description. + * @param method the query method + * @return the description for the query + */ + @Override + public QueryDescriptor extract( + RepositoryMetadata repositoryMetadata, + RepositoryFactoryConfiguration configuration, + Method method) { + String methodName = method.getName(); + // check to see if the AllIgnoreCase flag is set + boolean allIgnoreCase = methodName.matches(".*" + ALL_IGNORE_CASE_SUFFIX); + // we need to unify method name afterwards + methodName = allIgnoreCase ? methodName.replaceFirst(ALL_IGNORE_CASE_SUFFIX, "") : methodName; + // create a document reader for processing method name + final DocumentReader reader = new DefaultDocumentReader(methodName); + String function = parseFunctionName(method, reader); + final QueryModifiers queryModifiers = parseQueryModifiers(method, reader); + // this is the extractor used for getting paging data + final PageParameterExtractor pageExtractor; + // this is the extractor used for getting sorting data + SortParameterExtractor sortExtractor; + // these are decision branches, each of which denoting an AND clause + final List> branches = new ArrayList<>(); + // if the method name simply was the function name, no metadata can be extracted + if (!reader.hasMore()) { + pageExtractor = null; + sortExtractor = null; + } else { + reader.expect("By"); + if (!reader.hasMore()) { + throw new QueryParserException( + method.getDeclaringClass(), "Query method name cannot end with `By`"); + } + // current parameter index + int index = parseExpression(repositoryMetadata, method, allIgnoreCase, reader, branches); + final com.mmnaseri.utils.spring.data.query.Sort sort = + parseSort(repositoryMetadata, method, reader); + pageExtractor = getPageParameterExtractor(method, index, sort); + sortExtractor = getSortParameterExtractor(method, index, sort); } + return new DefaultQueryDescriptor( + queryModifiers.isDistinct(), + function, + queryModifiers.getLimit(), + pageExtractor, + sortExtractor, + branches(branches), + configuration, + repositoryMetadata); + } - private SortParameterExtractor getSortParameterExtractor(Method method, int index, - com.mmnaseri.utils.spring.data.query.Sort sort) { - SortParameterExtractor sortExtractor = null; - if (method.getParameterTypes().length == index) { - sortExtractor = sort == null ? null : new WrappedSortParameterExtractor(sort); - } else if (method.getParameterTypes().length == index + 1) { - if (Pageable.class.isAssignableFrom(method.getParameterTypes()[index])) { - sortExtractor = sort == null ? new PageableSortParameterExtractor(index) - : new WrappedSortParameterExtractor(sort); - } else if (Sort.class.isAssignableFrom(method.getParameterTypes()[index])) { - sortExtractor = new DirectSortParameterExtractor(index); - } - } - return sortExtractor; + private SortParameterExtractor getSortParameterExtractor( + Method method, int index, com.mmnaseri.utils.spring.data.query.Sort sort) { + SortParameterExtractor sortExtractor = null; + if (method.getParameterTypes().length == index) { + sortExtractor = sort == null ? null : new WrappedSortParameterExtractor(sort); + } else if (method.getParameterTypes().length == index + 1) { + if (Pageable.class.isAssignableFrom(method.getParameterTypes()[index])) { + sortExtractor = + sort == null + ? new PageableSortParameterExtractor(index) + : new WrappedSortParameterExtractor(sort); + } else if (Sort.class.isAssignableFrom(method.getParameterTypes()[index])) { + sortExtractor = new DirectSortParameterExtractor(index); + } } + return sortExtractor; + } - private PageParameterExtractor getPageParameterExtractor(Method method, int index, - com.mmnaseri.utils.spring.data.query.Sort sort) { - PageParameterExtractor pageExtractor; - if (method.getParameterTypes().length == index) { - pageExtractor = null; - } else if (method.getParameterTypes().length == index + 1) { - if (Pageable.class.isAssignableFrom(method.getParameterTypes()[index])) { - pageExtractor = new PageablePageParameterExtractor(index); - } else if (Sort.class.isAssignableFrom(method.getParameterTypes()[index])) { - if (sort != null) { - throw new QueryParserException(method.getDeclaringClass(), - "You cannot specify both an order-by clause and a dynamic ordering"); - } - pageExtractor = null; - } else { - throw new QueryParserException(method.getDeclaringClass(), - "Invalid last argument: expected paging or sorting " + method); - } - } else { - throw new QueryParserException(method.getDeclaringClass(), - "Too many parameters declared for query method " + method); + private PageParameterExtractor getPageParameterExtractor( + Method method, int index, com.mmnaseri.utils.spring.data.query.Sort sort) { + PageParameterExtractor pageExtractor; + if (method.getParameterTypes().length == index) { + pageExtractor = null; + } else if (method.getParameterTypes().length == index + 1) { + if (Pageable.class.isAssignableFrom(method.getParameterTypes()[index])) { + pageExtractor = new PageablePageParameterExtractor(index); + } else if (Sort.class.isAssignableFrom(method.getParameterTypes()[index])) { + if (sort != null) { + throw new QueryParserException( + method.getDeclaringClass(), + "You cannot specify both an order-by clause and a dynamic ordering"); } - return pageExtractor; + pageExtractor = null; + } else { + throw new QueryParserException( + method.getDeclaringClass(), + "Invalid last argument: expected paging or sorting " + method); + } + } else { + throw new QueryParserException( + method.getDeclaringClass(), "Too many parameters declared for query method " + method); } + return pageExtractor; + } - private int parseExpression(RepositoryMetadata repositoryMetadata, Method method, - boolean allIgnoreCase, DocumentReader reader, List> branches) { - int index = 0; + private int parseExpression( + RepositoryMetadata repositoryMetadata, + Method method, + boolean allIgnoreCase, + DocumentReader reader, + List> branches) { + int index = 0; + branches.add(new LinkedList<>()); + while (reader.hasMore()) { + final Parameter parameter; + // read a full expression + String expression = parseInitialExpression(reader); + // If we have encountered an OrderBy as the first thing in the expression, then we have no + // properties to + // filter on and we only want to order. + if (expression.startsWith("OrderBy")) { + reader.backtrack(expression.length()); + break; + } + // if the expression ended in Or, this is the end of this branch + boolean branchEnd = expression.endsWith("Or"); + // if the expression contains an OrderBy, it is not only the end of the branch, but also the + // end of the query + boolean expressionEnd = expression.matches(".+[a-z]OrderBy[A-Z].+"); + expression = handleExpressionEnd(reader, expression, expressionEnd); + final Set modifiers = new HashSet<>(); + expression = parseModifiers(allIgnoreCase, expression, modifiers); + // if the expression ends in And/Or, we expect there to be more + if (expression.matches(".*?(And|Or)$") && !reader.hasMore()) { + throw new QueryParserException( + method.getDeclaringClass(), "Expected more tokens to follow AND/OR operator"); + } + expression = expression.replaceFirst("(And|Or)$", ""); + String foundProperty = null; + Operator operator = parseOperator(expression); + if (operator != null) { + foundProperty = + expression.substring( + 0, expression.length() - ((MatchedOperator) operator).getMatchedToken().length()); + } + // if no operator was found, it is the implied "IS" operator + if (operator == null || foundProperty.isEmpty()) { + foundProperty = expression; + operator = operatorContext.getBySuffix(DEFAULT_OPERATOR_SUFFIX); + } + final PropertyDescriptor propertyDescriptor = + getPropertyDescriptor(repositoryMetadata, method, foundProperty); + final String property = propertyDescriptor.getPath(); + // we need to match the method parameters with the operands for the designated operator + final int[] indices = new int[operator.getOperands()]; + index = parseParameterIndices(method, index, operator, propertyDescriptor, indices); + // create a parameter definition for the given expression + parameter = new ImmutableParameter(property, modifiers, indices, operator); + // get the current branch + final List currentBranch = branches.get(branches.size() - 1); + // add this parameter to the latest branch + currentBranch.add(parameter); + // if the branch has ended with "OR", we set up a new branch + if (branchEnd) { branches.add(new LinkedList<>()); - while (reader.hasMore()) { - final Parameter parameter; - //read a full expression - String expression = parseInitialExpression(reader); - //if the expression ended in Or, this is the end of this branch - boolean branchEnd = expression.endsWith("Or"); - //if the expression contains an OrderBy, it is not only the end of the branch, but also the end of the query - boolean expressionEnd = expression.matches(".+[a-z]OrderBy[A-Z].+"); - expression = handleExpressionEnd(reader, expression, expressionEnd); - final Set modifiers = new HashSet<>(); - expression = parseModifiers(allIgnoreCase, expression, modifiers); - //if the expression ends in And/Or, we expect there to be more - if (expression.matches(".*?(And|Or)$") && !reader.hasMore()) { - throw new QueryParserException(method.getDeclaringClass(), - "Expected more tokens to follow AND/OR operator"); - } - expression = expression.replaceFirst("(And|Or)$", ""); - String foundProperty = null; - Operator operator = parseOperator(expression); - if (operator != null) { - foundProperty = expression.substring(0, expression.length() - ((MatchedOperator) operator) - .getMatchedToken().length()); - } - //if no operator was found, it is the implied "IS" operator - if (operator == null || foundProperty.isEmpty()) { - foundProperty = expression; - operator = operatorContext.getBySuffix(DEFAULT_OPERATOR_SUFFIX); - } - final PropertyDescriptor propertyDescriptor = getPropertyDescriptor(repositoryMetadata, method, - foundProperty); - final String property = propertyDescriptor.getPath(); - //we need to match the method parameters with the operands for the designated operator - final int[] indices = new int[operator.getOperands()]; - index = parseParameterIndices(method, index, operator, propertyDescriptor, indices); - //create a parameter definition for the given expression - parameter = new ImmutableParameter(property, modifiers, indices, operator); - //get the current branch - final List currentBranch = branches.get(branches.size() - 1); - //add this parameter to the latest branch - currentBranch.add(parameter); - //if the branch has ended with "OR", we set up a new branch - if (branchEnd) { - branches.add(new LinkedList<>()); - } - //if this is the end of expression, so we need to jump out - if (expressionEnd) { - break; - } - } - return index; + } + // if this is the end of expression, so we need to jump out + if (expressionEnd) { + break; + } } + return index; + } - private com.mmnaseri.utils.spring.data.query.Sort parseSort(RepositoryMetadata repositoryMetadata, Method method, - DocumentReader reader) { - final com.mmnaseri.utils.spring.data.query.Sort sort; - //let's figure out if there is a sort requirement embedded in the query definition - if (reader.read("OrderBy") != null) { - final List orders = new ArrayList<>(); - while (reader.hasMore()) { - orders.add(parseOrder(method, reader, repositoryMetadata)); - } - sort = new ImmutableSort(orders); - } else { - sort = null; - } - return sort; + private com.mmnaseri.utils.spring.data.query.Sort parseSort( + RepositoryMetadata repositoryMetadata, Method method, DocumentReader reader) { + final com.mmnaseri.utils.spring.data.query.Sort sort; + // let's figure out if there is a sort requirement embedded in the query definition + if (reader.read("OrderBy") != null) { + final List orders = new ArrayList<>(); + while (reader.hasMore()) { + orders.add(parseOrder(method, reader, repositoryMetadata)); + } + sort = new ImmutableSort(orders); + } else { + sort = null; } + return sort; + } - private int parseParameterIndices(Method method, int index, Operator operator, - PropertyDescriptor propertyDescriptor, int[] indices) { - int parameterIndex = index; - Class[] parameterTypes = new Class[operator.getOperands()]; - for (int i = 0; i < operator.getOperands(); i++) { - if (parameterIndex >= method.getParameterTypes().length) { - throw new QueryParserException(method.getDeclaringClass(), - "Expected to see parameter with index " + parameterIndex); - } - parameterTypes[i] = method.getParameterTypes()[parameterIndex]; - indices[i] = parameterIndex++; - } - if (!operator.getMatcher().isApplicableTo(propertyDescriptor.getType(), parameterTypes)) { - throw new QueryParserException(method.getDeclaringClass(), - String.format("Invalid parameter types for operator %s on property %s: [%s]", - operator.getName(), - propertyDescriptor.getPath(), - Joiner.on(",").join(parameterTypes))); - } - return parameterIndex; + private int parseParameterIndices( + Method method, + int index, + Operator operator, + PropertyDescriptor propertyDescriptor, + int[] indices) { + int parameterIndex = index; + Class[] parameterTypes = new Class[operator.getOperands()]; + for (int i = 0; i < operator.getOperands(); i++) { + if (parameterIndex >= method.getParameterTypes().length) { + throw new QueryParserException( + method.getDeclaringClass(), "Expected to see parameter with index " + parameterIndex); + } + parameterTypes[i] = method.getParameterTypes()[parameterIndex]; + indices[i] = parameterIndex++; } + if (!operator.getMatcher().isApplicableTo(propertyDescriptor.getType(), parameterTypes)) { + throw new QueryParserException( + method.getDeclaringClass(), + String.format( + "Invalid parameter types for operator %s on property %s: [%s]", + operator.getName(), + propertyDescriptor.getPath(), + Joiner.on(",").join(parameterTypes))); + } + return parameterIndex; + } - private PropertyDescriptor getPropertyDescriptor(RepositoryMetadata repositoryMetadata, Method method, - String property) { - //let's get the property descriptor - final PropertyDescriptor propertyDescriptor; - try { - propertyDescriptor = PropertyUtils.getPropertyDescriptor(repositoryMetadata.getEntityType(), property); - } catch (Exception e) { - throw new QueryParserException(method.getDeclaringClass(), - "Could not find property `" + StringUtils.uncapitalize(property) + "` on `" - + repositoryMetadata.getEntityType() + "`", e); - } - return propertyDescriptor; + private PropertyDescriptor getPropertyDescriptor( + RepositoryMetadata repositoryMetadata, Method method, String property) { + // let's get the property descriptor + final PropertyDescriptor propertyDescriptor; + try { + propertyDescriptor = + PropertyUtils.getPropertyDescriptor(repositoryMetadata.getEntityType(), property); + } catch (Exception e) { + throw new QueryParserException( + method.getDeclaringClass(), + "Could not find property `" + + StringUtils.uncapitalize(property) + + "` on `" + + repositoryMetadata.getEntityType() + + "`", + e); } + return propertyDescriptor; + } - private Operator parseOperator(String expression) { - Operator operator = null; - //let's find out the operator that covers the longest suffix of the operation - for (int i = 1; i < expression.length(); i++) { - final String suffix = expression.substring(i); - operator = operatorContext.getBySuffix(suffix); - if (operator != null) { - operator = new ImmutableMatchedOperator(operator, suffix); - break; - } - } - return operator; + private Operator parseOperator(String expression) { + Operator operator = null; + // let's find out the operator that covers the longest suffix of the operation + for (int i = 1; i < expression.length(); i++) { + final String suffix = expression.substring(i); + operator = operatorContext.getBySuffix(suffix); + if (operator != null) { + operator = new ImmutableMatchedOperator(operator, suffix); + break; + } } + return operator; + } - private String parseModifiers(boolean allIgnoreCase, String originalExpression, Set modifiers) { - String expression = originalExpression; - if (expression.matches(".*" + IGNORE_CASE_PARTIAL + ".*")) { - //if the expression contains IgnoreCase, we need to strip that off - modifiers.add(Modifier.IGNORE_CASE); - expression = expression.replaceFirst(IGNORE_CASE_PARTIAL, ""); - } else if (allIgnoreCase) { - //if we had already set "AllIgnoreCase", we will still add the modifier - modifiers.add(Modifier.IGNORE_CASE); - } - return expression; + private String parseModifiers( + boolean allIgnoreCase, String originalExpression, Set modifiers) { + String expression = originalExpression; + if (expression.matches(".*" + IGNORE_CASE_PARTIAL + ".*")) { + // if the expression contains IgnoreCase, we need to strip that off + modifiers.add(Modifier.IGNORE_CASE); + expression = expression.replaceFirst(IGNORE_CASE_PARTIAL, ""); + } else if (allIgnoreCase) { + // if we had already set "AllIgnoreCase", we will still add the modifier + modifiers.add(Modifier.IGNORE_CASE); } + return expression; + } - private String handleExpressionEnd(DocumentReader reader, String originalExpression, boolean expressionEnd) { - String expression = originalExpression; - if (expressionEnd) { - //if that is the case, we need to put back the entirety of the order by clause - int length = expression.length(); - expression = expression.replaceFirst("^(.+[a-z])OrderBy[A-Z].+$", "$1"); - length -= expression.length(); - reader.backtrack(length); - } - return expression; + private String handleExpressionEnd( + DocumentReader reader, String originalExpression, boolean expressionEnd) { + String expression = originalExpression; + if (expressionEnd) { + // if that is the case, we need to put back the entirety of the order by clause + int length = expression.length(); + expression = expression.replaceFirst("^(.+[a-z])OrderBy[A-Z].+$", "$1"); + length -= expression.length(); + reader.backtrack(length); } + return expression; + } - private String parseInitialExpression(DocumentReader reader) { - String expression = reader.expect("(.*?)(And[A-Z]|Or[A-Z]|$)"); - if (expression.matches(".*?(And|Or)[A-Z]")) { - //if the expression ended in And/Or, we need to put the one extra character we scanned back - //we scan one extra character because we don't want anything like "Order" to be mistaken for "Or" - reader.backtrack(1); - expression = expression.substring(0, expression.length() - 1); - } - return expression; + private String parseInitialExpression(DocumentReader reader) { + String expression = reader.expect("(.*?)(And[A-Z]|Or[A-Z]|$)"); + if (expression.matches(".*?(And|Or)[A-Z]")) { + // if the expression ended in And/Or, we need to put the one extra character we scanned back + // we scan one extra character because we don't want anything like "Order" to be mistaken for + // "Or" + reader.backtrack(1); + expression = expression.substring(0, expression.length() - 1); } + return expression; + } - private Order parseOrder(Method method, DocumentReader reader, RepositoryMetadata repositoryMetadata) { - String expression = reader.expect(".*?(Asc|Desc)"); - final SortDirection direction; - if (expression.endsWith(ASC_SUFFIX)) { - direction = SortDirection.ASCENDING; - expression = expression.substring(0, expression.length() - ASC_SUFFIX.length()); - } else { - direction = SortDirection.DESCENDING; - expression = expression.substring(0, expression.length() - DESC_SUFFIX.length()); - } - final PropertyDescriptor propertyDescriptor; - try { - propertyDescriptor = PropertyUtils.getPropertyDescriptor(repositoryMetadata.getEntityType(), expression); - } catch (Exception e) { - throw new QueryParserException(method.getDeclaringClass(), - "Failed to get a property descriptor for expression: " + expression, e); - } - if (!Comparable.class.isAssignableFrom(propertyDescriptor.getType())) { - throw new QueryParserException(method.getDeclaringClass(), - "Sort property `" + propertyDescriptor.getPath() + "` is not comparable in `" - + method.getName() + "`"); - } - return new ImmutableOrder(direction, propertyDescriptor.getPath(), NullHandling.DEFAULT); + private Order parseOrder( + Method method, DocumentReader reader, RepositoryMetadata repositoryMetadata) { + String expression = reader.expect(".*?(Asc|Desc)"); + final SortDirection direction; + if (expression.endsWith(ASC_SUFFIX)) { + direction = SortDirection.ASCENDING; + expression = expression.substring(0, expression.length() - ASC_SUFFIX.length()); + } else { + direction = SortDirection.DESCENDING; + expression = expression.substring(0, expression.length() - DESC_SUFFIX.length()); } + final PropertyDescriptor propertyDescriptor; + try { + propertyDescriptor = + PropertyUtils.getPropertyDescriptor(repositoryMetadata.getEntityType(), expression); + } catch (Exception e) { + throw new QueryParserException( + method.getDeclaringClass(), + "Failed to get a property descriptor for expression: " + expression, + e); + } + if (!Comparable.class.isAssignableFrom(propertyDescriptor.getType())) { + throw new QueryParserException( + method.getDeclaringClass(), + "Sort property `" + + propertyDescriptor.getPath() + + "` is not comparable in `" + + method.getName() + + "`"); + } + return new ImmutableOrder(direction, propertyDescriptor.getPath(), NullHandling.DEFAULT); + } - private String parseFunctionName(Method method, DocumentReader reader) { - //the first word in the method name is the function name - String function = reader.read(Pattern.compile("^[a-z]+")); - if (function == null) { - throw new QueryParserException(method.getDeclaringClass(), "Malformed query method name: " + method); - } - //if the method name is one of the following, it is a simple read, and no function is required - if (Arrays.asList("read", "find", "query", "get", "load", "select").contains(function)) { - function = null; - } - return function; + private String parseFunctionName(Method method, DocumentReader reader) { + // the first word in the method name is the function name + String function = reader.read(Pattern.compile("^[a-z]+")); + if (function == null) { + throw new QueryParserException( + method.getDeclaringClass(), "Malformed query method name: " + method); } + // if the method name is one of the following, it is a simple read, and no function is required + if (Arrays.asList("read", "find", "query", "get", "load", "select").contains(function)) { + function = null; + } + return function; + } - private QueryModifiers parseQueryModifiers(Method method, DocumentReader reader) { - //this is the limit set on the number of items being returned - int limit = 0; - //this is the flag that determines whether or not the result should be sifted for distinct values - boolean distinct = false; - //we are still reading the function name if we haven't gotten to `By` and we haven't seen - //any of the magic keywords `First`, `Top`, and `Distinct`. - //scan for words prior to 'By' - while (reader.hasMore() && !reader.has("By")) { - //if the next word is Top, then we are setting a limit - if (reader.has("First")) { - if (limit > 0) { - throw new QueryParserException(method.getDeclaringClass(), "There is already a limit of " + limit - + " specified for this query: " + method); - } - reader.expect("First"); - if (reader.has("\\d+")) { - limit = Integer.parseInt(reader.expect("\\d+")); - } else { - limit = 1; - } - continue; - } else if (reader.has("Top")) { - if (limit > 0) { - throw new QueryParserException(method.getDeclaringClass(), "There is already a limit of " + limit - + " specified for this query: " + method); - } - reader.expect("Top"); - limit = Integer.parseInt(reader.expect("\\d+")); - continue; - } else if (reader.has("Distinct")) { - //if the next word is 'Distinct', we are saying we should return distinct results - if (distinct) { - throw new QueryParserException(method.getDeclaringClass(), - "You have already stated that this query should return distinct " - + "items: " - + method); - } - distinct = true; - } - //we read the words until we reach "By". - reader.expect("[A-Z][a-z]+"); + private QueryModifiers parseQueryModifiers(Method method, DocumentReader reader) { + // this is the limit set on the number of items being returned + int limit = 0; + // this is the flag that determines whether or not the result should be sifted for distinct + // values + boolean distinct = false; + // we are still reading the function name if we haven't gotten to `By` and we haven't seen + // any of the magic keywords `First`, `Top`, and `Distinct`. + // scan for words prior to 'By' + while (reader.hasMore() && !reader.has("By")) { + // if the next word is Top, then we are setting a limit + if (reader.has("First")) { + if (limit > 0) { + throw new QueryParserException( + method.getDeclaringClass(), + "There is already a limit of " + limit + " specified for this query: " + method); + } + reader.expect("First"); + if (reader.has("\\d+")) { + limit = Integer.parseInt(reader.expect("\\d+")); + } else { + limit = 1; + } + continue; + } else if (reader.has("Top")) { + if (limit > 0) { + throw new QueryParserException( + method.getDeclaringClass(), + "There is already a limit of " + limit + " specified for this query: " + method); } - return new QueryModifiers(limit, distinct); + reader.expect("Top"); + limit = Integer.parseInt(reader.expect("\\d+")); + continue; + } else if (reader.has("Distinct")) { + // if the next word is 'Distinct', we are saying we should return distinct results + if (distinct) { + throw new QueryParserException( + method.getDeclaringClass(), + "You have already stated that this query should return distinct " + + "items: " + + method); + } + distinct = true; + } + // we read the words until we reach "By". + reader.expect("[A-Z][a-z]+"); } + return new QueryModifiers(limit, distinct); + } - public OperatorContext getOperatorContext() { - return operatorContext; - } + public OperatorContext getOperatorContext() { + return operatorContext; + } + private static List> branches(List> original) { + List> branches = new ArrayList<>(); + for (List branch : original) { + if (!branch.isEmpty()) { + branches.add(branch); + } + } + return branches; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparator.java index ddec8ea1..430f69ac 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparator.java @@ -11,119 +11,123 @@ import java.util.List; /** - * This is a comparator that will compare two objects based on a common property. The property should be defined as an - * expression such as "x.y.z". + * This is a comparator that will compare two objects based on a common property. The property + * should be defined as an expression such as "x.y.z". * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public class PropertyComparator implements Comparator { - private static final NullHandling DEFAULT_NULL_HANDLING = NullHandling.NULLS_LAST; - private final NullHandling nullHandling; - private final String property; - private final SortDirection direction; + private static final NullHandling DEFAULT_NULL_HANDLING = NullHandling.NULLS_LAST; + private final NullHandling nullHandling; + private final String property; + private final SortDirection direction; - PropertyComparator(Order order) { - this.nullHandling = order.getNullHandling() == null || NullHandling.DEFAULT.equals(order.getNullHandling()) - ? DEFAULT_NULL_HANDLING : order.getNullHandling(); - property = order.getProperty(); - direction = order.getDirection(); - } + PropertyComparator(Order order) { + this.nullHandling = + order.getNullHandling() == null || NullHandling.DEFAULT.equals(order.getNullHandling()) + ? DEFAULT_NULL_HANDLING + : order.getNullHandling(); + property = order.getProperty(); + direction = order.getDirection(); + } - @Override - public int compare(Object first, Object second) { - final Object firstValue = safeReadPropertyValue(first); - final Object secondValue = safeReadPropertyValue(second); - int comparison; - if (firstValue == null || secondValue == null) { - comparison = compareIfEitherIsNull(firstValue, secondValue); - } else { - comparison = compareIfCompatible(firstValue, secondValue); - } - return comparison * (SortDirection.DESCENDING.equals(direction) ? -1 : 1); + @Override + public int compare(Object first, Object second) { + final Object firstValue = safeReadPropertyValue(first); + final Object secondValue = safeReadPropertyValue(second); + int comparison; + if (firstValue == null || secondValue == null) { + comparison = compareIfEitherIsNull(firstValue, secondValue); + } else { + comparison = compareIfCompatible(firstValue, secondValue); } + return comparison * (SortDirection.DESCENDING.equals(direction) ? -1 : 1); + } - /** - * Returns the value of the specified {@link #property property} from the object, given that it exists. Otherwise, - * it throws an {@link InvalidArgumentException}. - * - * @param object the object to read the property from - * @return the value of the property - * @throws InvalidArgumentException If the value of the property cannot be read. - */ - private Object safeReadPropertyValue(Object object) { - Object firstValue; - try { - firstValue = PropertyUtils.getPropertyValue(object, property); - } catch (Exception e) { - throw new InvalidArgumentException("Failed to read property value for " + property + " on " + object, e); - } - return firstValue; + /** + * Returns the value of the specified {@link #property property} from the object, given that it + * exists. Otherwise, it throws an {@link InvalidArgumentException}. + * + * @param object the object to read the property from + * @return the value of the property + * @throws InvalidArgumentException If the value of the property cannot be read. + */ + private Object safeReadPropertyValue(Object object) { + Object firstValue; + try { + firstValue = PropertyUtils.getPropertyValue(object, property); + } catch (Exception e) { + throw new InvalidArgumentException( + "Failed to read property value for " + property + " on " + object, e); } + return firstValue; + } - /** - * If either of the two values is {@literal null}, this will compare them by taking {@link NullHandling} into - * account. - * - * @param first the first value - * @param second the second value - * @return comparison results as defined by {@link Comparable#compareTo(Object)} - */ - private int compareIfEitherIsNull(Object first, Object second) { - if (first == null && second != null) { - return NullHandling.NULLS_FIRST.equals(nullHandling) ? -1 : 1; - } else if (first != null) { - return NullHandling.NULLS_FIRST.equals(nullHandling) ? 1 : -1; - } else { - return 0; - } + /** + * If either of the two values is {@literal null}, this will compare them by taking {@link + * NullHandling} into account. + * + * @param first the first value + * @param second the second value + * @return comparison results as defined by {@link Comparable#compareTo(Object)} + */ + private int compareIfEitherIsNull(Object first, Object second) { + if (first == null && second != null) { + return NullHandling.NULLS_FIRST.equals(nullHandling) ? -1 : 1; + } else if (first != null) { + return NullHandling.NULLS_FIRST.equals(nullHandling) ? 1 : -1; + } else { + return 0; } + } - /** - * This will compare the two values if their are compatible, meaning one of them is of a type that is a - * super type or is the same type as the other one. - * - * @param first the first item - * @param second the second item - * @return comparison results as defined by {@link Comparable#compareTo(Object)} - * @throws InvalidArgumentException If the values of the two properties are not of the same type. - */ - @SuppressWarnings("unchecked") - private int compareIfCompatible(Object first, Object second) { - checkForComparable(first, second); - if (first.getClass().isInstance(second)) { - return ((Comparable) first).compareTo(second); - } else if (second.getClass().isInstance(first)) { - return ((Comparable) second).compareTo(first) * -1; - } else { - throw new InvalidArgumentException("Values for were not of the same type for property: " + property); - } + /** + * This will compare the two values if their are compatible, meaning one of them is of a + * type that is a super type or is the same type as the other one. + * + * @param first the first item + * @param second the second item + * @return comparison results as defined by {@link Comparable#compareTo(Object)} + * @throws InvalidArgumentException If the values of the two properties are not of the same type. + */ + @SuppressWarnings("unchecked") + private int compareIfCompatible(Object first, Object second) { + checkForComparable(first, second); + if (first.getClass().isInstance(second)) { + return ((Comparable) first).compareTo(second); + } else if (second.getClass().isInstance(first)) { + return ((Comparable) second).compareTo(first) * -1; + } else { + throw new InvalidArgumentException( + "Values for were not of the same type for property: " + property); } + } - /** - * This method checks to make sure both values are of type {@link Comparable} - * - * @param first the first value - * @param second the second value - * @throws InvalidArgumentException if they are not - */ - private void checkForComparable(Object first, Object second) { - if (!(first instanceof Comparable) || !(second instanceof Comparable)) { - throw new InvalidArgumentException("Expected both values to be comparable for property: " + property); - } + /** + * This method checks to make sure both values are of type {@link Comparable} + * + * @param first the first value + * @param second the second value + * @throws InvalidArgumentException if they are not + */ + private void checkForComparable(Object first, Object second) { + if (!(first instanceof Comparable) || !(second instanceof Comparable)) { + throw new InvalidArgumentException( + "Expected both values to be comparable for property: " + property); } + } - /** - * Given a collection of objects, will sort them by taking the sort property into account. - * - * @param collection the collection of items - * @param sort the sort specification - */ - public static void sort(List collection, Sort sort) { - for (int i = sort.getOrders().size() - 1; i >= 0; i--) { - collection.sort(new PropertyComparator(sort.getOrders().get(i))); - } + /** + * Given a collection of objects, will sort them by taking the sort property into account. + * + * @param collection the collection of items + * @param sort the sort specification + */ + public static void sort(List collection, Sort sort) { + for (int i = sort.getOrders().size() - 1; i >= 0; i--) { + collection.sort(new PropertyComparator(sort.getOrders().get(i))); } - + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/QueryDescriptionExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/QueryDescriptionExtractor.java index e172a7ae..8ad9ff53 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/QueryDescriptionExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/QueryDescriptionExtractor.java @@ -10,7 +10,8 @@ */ public interface QueryDescriptionExtractor { - QueryDescriptor extract(RepositoryMetadata repositoryMetadata, RepositoryFactoryConfiguration configuration, - T target); - + QueryDescriptor extract( + RepositoryMetadata repositoryMetadata, + RepositoryFactoryConfiguration configuration, + T target); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/QueryModifiers.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/QueryModifiers.java index a9d7b125..741911d4 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/QueryModifiers.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/QueryModifiers.java @@ -1,8 +1,8 @@ package com.mmnaseri.utils.spring.data.domain.impl; /** - * This class contains a query's modifiers: the limit put on the number of results, and whether or not the values should - * be distinct. + * This class contains a query's modifiers: the limit put on the number of results, and whether or + * not the values should be distinct. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (4/13/16, 9:25 AM) @@ -10,20 +10,19 @@ @SuppressWarnings("WeakerAccess") class QueryModifiers { - private final int limit; - private final boolean distinct; + private final int limit; + private final boolean distinct; - QueryModifiers(int limit, boolean distinct) { - this.limit = limit; - this.distinct = distinct; - } + QueryModifiers(int limit, boolean distinct) { + this.limit = limit; + this.distinct = distinct; + } - public int getLimit() { - return limit; - } - - public boolean isDistinct() { - return distinct; - } + public int getLimit() { + return limit; + } + public boolean isDistinct() { + return distinct; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperation.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperation.java index 3e9866a2..9d4b6e47 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperation.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperation.java @@ -10,76 +10,83 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; /** - * This is a data store operation that will read values from the underlying data store and match them up against the - * query description's different decision branches. Once all the values are loaded and filtered, it will then sort them - * according to the sort instruction, and then paginate them if necessary. + * This is a data store operation that will read values from the underlying data store and match + * them up against the query description's different decision branches. Once all the values are + * loaded and filtered, it will then sort them according to the sort instruction, and then paginate + * them if necessary. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public class SelectDataStoreOperation implements DataStoreOperation, K, E> { - private static final Log log = LogFactory.getLog(SelectDataStoreOperation.class); - private final QueryDescriptor descriptor; + private static final Log log = LogFactory.getLog(SelectDataStoreOperation.class); + private final QueryDescriptor descriptor; - public SelectDataStoreOperation(QueryDescriptor descriptor) { - this.descriptor = descriptor; - } + public SelectDataStoreOperation(QueryDescriptor descriptor) { + this.descriptor = descriptor; + } - public QueryDescriptor getDescriptor() { - return descriptor; - } + public QueryDescriptor getDescriptor() { + return descriptor; + } - @Override - public List execute(DataStore store, RepositoryConfiguration configuration, Invocation invocation) { - log.info("Selecting the data according to the provided selection descriptor: " + descriptor); - final List selection = new LinkedList<>(); - final Collection all = new LinkedList<>(store.retrieveAll()); - for (E entity : all) { - if (descriptor.matches(entity, invocation)) { - selection.add(entity); - } - } - log.info("Matched " + selection.size() + " items from the data store"); - if (descriptor.isDistinct()) { - final Set distinctValues = new HashSet<>(selection); - selection.clear(); - selection.addAll(distinctValues); - log.info("After clearing up duplicates, " + selection.size() + " items remained"); - } - final Sort sort = descriptor.getSort(invocation); - final Page page = descriptor.getPage(invocation); - if (sort != null) { - log.info("Sorting the selected items according to the provided ordering"); - PropertyComparator.sort(selection, sort); - } - if (page != null) { - log.info("We need to paginate the selection to fit the selection criteria"); - int start = page.getPageSize() * page.getPageNumber(); - int finish = Math.min(start + page.getPageSize(), selection.size()); - if (start > selection.size()) { - selection.clear(); - } else { - final List view = new ArrayList<>(selection.subList(start, finish)); - selection.clear(); - selection.addAll(view); - } - } - if (descriptor.getLimit() > 0) { - log.info("Going to limit the result to " + descriptor.getLimit() + " items"); - final List view = new ArrayList<>(selection.subList(0, Math.min(selection.size(), descriptor.getLimit()))); - selection.clear(); - selection.addAll(view); - } - return selection; + @Override + public List execute( + DataStore store, RepositoryConfiguration configuration, Invocation invocation) { + log.info("Selecting the data according to the provided selection descriptor: " + descriptor); + final List selection = new LinkedList<>(); + final Collection all = new LinkedList<>(store.retrieveAll()); + for (E entity : all) { + if (descriptor.matches(entity, invocation)) { + selection.add(entity); + } } - - @Override - public String toString() { - return descriptor.toString(); + log.info("Matched " + selection.size() + " items from the data store"); + if (descriptor.isDistinct()) { + final Set distinctValues = new HashSet<>(selection); + selection.clear(); + selection.addAll(distinctValues); + log.info("After clearing up duplicates, " + selection.size() + " items remained"); + } + final Sort sort = descriptor.getSort(invocation); + final Page page = descriptor.getPage(invocation); + if (sort != null) { + log.info("Sorting the selected items according to the provided ordering"); + PropertyComparator.sort(selection, sort); + } + if (page != null) { + log.info("We need to paginate the selection to fit the selection criteria"); + int start = page.getPageSize() * page.getPageNumber(); + int finish = Math.min(start + page.getPageSize(), selection.size()); + if (start > selection.size()) { + selection.clear(); + } else { + final List view = new ArrayList<>(selection.subList(start, finish)); + selection.clear(); + selection.addAll(view); + } + } + if (descriptor.getLimit() > 0) { + log.info("Going to limit the result to " + descriptor.getLimit() + " items"); + final List view = + new ArrayList<>(selection.subList(0, Math.min(selection.size(), descriptor.getLimit()))); + selection.clear(); + selection.addAll(view); } + return selection; + } + @Override + public String toString() { + return descriptor.toString(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedFieldIdPropertyResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedFieldIdPropertyResolver.java index d83adbd0..222f9f18 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedFieldIdPropertyResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedFieldIdPropertyResolver.java @@ -13,7 +13,8 @@ import static com.mmnaseri.utils.spring.data.domain.impl.id.IdPropertyResolverUtils.isAnnotated; /** - * This class will help resolve ID property name if the entity has a field that is annotated with {@link Id @Id} + * This class will help resolve ID property name if the entity has a field that is annotated with + * {@link Id @Id} * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) @@ -21,31 +22,32 @@ @SuppressWarnings("WeakerAccess") public class AnnotatedFieldIdPropertyResolver implements IdPropertyResolver { - @Override - public String resolve(final Class entityType, Class idType) { - final AtomicReference found = new AtomicReference<>(); - //try to find the ID field - ReflectionUtils.doWithFields(entityType, field -> { - if (isAnnotated(field)) { - if (found.get() == null) { - found.set(field); - } else { - throw new MultipleIdPropertiesException(entityType); - } - } - }); - final Field idAnnotatedField = found.get(); - //if a field was found, try to get the ID property name - if (idAnnotatedField != null) { - if (!PropertyUtils.getTypeOf(idType).isAssignableFrom( - PropertyUtils.getTypeOf(idAnnotatedField.getType()))) { - throw new PropertyTypeMismatchException(entityType, idAnnotatedField.getName(), idType, - idAnnotatedField.getType()); + @Override + public String resolve(final Class entityType, Class idType) { + final AtomicReference found = new AtomicReference<>(); + // try to find the ID field + ReflectionUtils.doWithFields( + entityType, + field -> { + if (isAnnotated(field)) { + if (found.get() == null) { + found.set(field); } else { - return idAnnotatedField.getName(); + throw new MultipleIdPropertiesException(entityType); } - } - return null; + } + }); + final Field idAnnotatedField = found.get(); + // if a field was found, try to get the ID property name + if (idAnnotatedField != null) { + if (!PropertyUtils.getTypeOf(idType) + .isAssignableFrom(PropertyUtils.getTypeOf(idAnnotatedField.getType()))) { + throw new PropertyTypeMismatchException( + entityType, idAnnotatedField.getName(), idType, idAnnotatedField.getType()); + } else { + return idAnnotatedField.getName(); + } } - + return null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedGetterIdPropertyResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedGetterIdPropertyResolver.java index c235bed6..66d9a304 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedGetterIdPropertyResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedGetterIdPropertyResolver.java @@ -13,7 +13,8 @@ import static com.mmnaseri.utils.spring.data.domain.impl.id.IdPropertyResolverUtils.isAnnotated; /** - * This class will resolve ID property name from a getter method that is annotated with {@link Id @Id}. + * This class will resolve ID property name from a getter method that is annotated with {@link + * Id @Id}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) @@ -21,20 +22,22 @@ @SuppressWarnings("WeakerAccess") public class AnnotatedGetterIdPropertyResolver implements IdPropertyResolver { - @Override - public String resolve(final Class entityType, Class idType) { - final AtomicReference found = new AtomicReference<>(); - ReflectionUtils.doWithMethods(entityType, method -> { - if (isAnnotated(method)) { - if (found.get() == null) { - found.set(method); - } else { - throw new MultipleIdPropertiesException(entityType); - } + @Override + public String resolve(final Class entityType, Class idType) { + final AtomicReference found = new AtomicReference<>(); + ReflectionUtils.doWithMethods( + entityType, + method -> { + if (isAnnotated(method)) { + if (found.get() == null) { + found.set(method); + } else { + throw new MultipleIdPropertiesException(entityType); } - }, new GetterMethodFilter()); - final Method idAnnotatedMethod = found.get(); - return getPropertyNameFromAnnotatedMethod(entityType, idType, idAnnotatedMethod); - } - + } + }, + new GetterMethodFilter()); + final Method idAnnotatedMethod = found.get(); + return getPropertyNameFromAnnotatedMethod(entityType, idType, idAnnotatedMethod); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/EntityIdPropertyResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/EntityIdPropertyResolver.java index db25c913..47a41a60 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/EntityIdPropertyResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/EntityIdPropertyResolver.java @@ -10,60 +10,71 @@ import org.apache.commons.logging.LogFactory; /** - *

This class will use all the magic implemented in the other ID property resolvers to find out the ID property - * for an entity.

+ * This class will use all the magic implemented in the other ID property resolvers to find out the + * ID property for an entity. * - *

The order in which conditions are considered is:

+ *

The order in which conditions are considered is: * *

    - *
  1. {@link AnnotatedGetterIdPropertyResolver Annotated getter}
  2. - *
  3. {@link AnnotatedFieldIdPropertyResolver Annotated field}
  4. - *
  5. {@link NamedGetterIdPropertyResolver Getter for ID property using name}
  6. - *
  7. {@link NamedFieldIdPropertyResolver Field having proper name}
  8. + *
  9. {@link AnnotatedGetterIdPropertyResolver Annotated getter} + *
  10. {@link AnnotatedFieldIdPropertyResolver Annotated field} + *
  11. {@link NamedGetterIdPropertyResolver Getter for ID property using name} + *
  12. {@link NamedFieldIdPropertyResolver Field having proper name} *
* - *

After all the above are considered, if nothing is found, a {@link NoIdPropertyException NoIdPropertyException} - * is thrown to show that the promised ID property was not found on the entity class.

+ *

After all the above are considered, if nothing is found, a {@link NoIdPropertyException + * NoIdPropertyException} is thrown to show that the promised ID property was not found on the + * entity class. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) */ public class EntityIdPropertyResolver implements IdPropertyResolver { - private static final Log log = LogFactory.getLog(EntityIdPropertyResolver.class); - private final AnnotatedGetterIdPropertyResolver annotatedGetterIdPropertyResolver = - new AnnotatedGetterIdPropertyResolver(); - private final AnnotatedFieldIdPropertyResolver annotatedFieldIdPropertyResolver = - new AnnotatedFieldIdPropertyResolver(); - private final NamedGetterIdPropertyResolver namedGetterIdPropertyResolver = new NamedGetterIdPropertyResolver(); - private final NamedFieldIdPropertyResolver namedFieldIdPropertyResolver = new NamedFieldIdPropertyResolver(); + private static final Log log = LogFactory.getLog(EntityIdPropertyResolver.class); + private final AnnotatedGetterIdPropertyResolver annotatedGetterIdPropertyResolver = + new AnnotatedGetterIdPropertyResolver(); + private final AnnotatedFieldIdPropertyResolver annotatedFieldIdPropertyResolver = + new AnnotatedFieldIdPropertyResolver(); + private final NamedGetterIdPropertyResolver namedGetterIdPropertyResolver = + new NamedGetterIdPropertyResolver(); + private final NamedFieldIdPropertyResolver namedFieldIdPropertyResolver = + new NamedFieldIdPropertyResolver(); - @Override - public String resolve(Class entityType, Class idType) { - log.info("Trying to resolve the ID property for entity " + entityType + " using the annotated getter method"); - String idProperty = annotatedGetterIdPropertyResolver.resolve(entityType, idType); - if (idProperty == null) { - log.info("Trying to resolve the ID property for entity " + entityType + " using the annotated ID field"); - idProperty = annotatedFieldIdPropertyResolver.resolve(entityType, idType); - } - if (idProperty == null) { - log.info("Trying to resolve the ID property for entity " + entityType + " using the getter method"); - idProperty = namedGetterIdPropertyResolver.resolve(entityType, idType); - } - if (idProperty == null) { - log.info("Trying to resolve the ID property for entity " + entityType + " using the field"); - idProperty = namedFieldIdPropertyResolver.resolve(entityType, idType); - } - if (idProperty == null) { - log.error("No ID property was found for entity " + entityType); - throw new NoIdPropertyException(entityType); - } - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(entityType, - StringUtils.capitalize(idProperty)); - if (descriptor.getType().isPrimitive()) { - throw new PrimitiveIdTypeException(entityType, idProperty); - } - return idProperty; + @Override + public String resolve(Class entityType, Class idType) { + log.info( + "Trying to resolve the ID property for entity " + + entityType + + " using the annotated getter method"); + String idProperty = annotatedGetterIdPropertyResolver.resolve(entityType, idType); + if (idProperty == null) { + log.info( + "Trying to resolve the ID property for entity " + + entityType + + " using the annotated ID field"); + idProperty = annotatedFieldIdPropertyResolver.resolve(entityType, idType); } - + if (idProperty == null) { + log.info( + "Trying to resolve the ID property for entity " + + entityType + + " using the getter method"); + idProperty = namedGetterIdPropertyResolver.resolve(entityType, idType); + } + if (idProperty == null) { + log.info("Trying to resolve the ID property for entity " + entityType + " using the field"); + idProperty = namedFieldIdPropertyResolver.resolve(entityType, idType); + } + if (idProperty == null) { + log.error("No ID property was found for entity " + entityType); + throw new NoIdPropertyException(entityType); + } + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(entityType, StringUtils.capitalize(idProperty)); + if (descriptor.getType().isPrimitive()) { + throw new PrimitiveIdTypeException(entityType, idProperty); + } + return idProperty; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/IdPropertyResolverUtils.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/IdPropertyResolverUtils.java index 49ab80f0..6be63bcb 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/IdPropertyResolverUtils.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/IdPropertyResolverUtils.java @@ -22,78 +22,79 @@ @SuppressWarnings("WeakerAccess") public final class IdPropertyResolverUtils { - private static final List ID_ANNOTATIONS = new ArrayList<>(); - private static final Log log = LogFactory.getLog(IdPropertyResolverUtils.class); + private static final List ID_ANNOTATIONS = new ArrayList<>(); + private static final Log log = LogFactory.getLog(IdPropertyResolverUtils.class); - static { - ID_ANNOTATIONS.add("org.springframework.data.annotation.Id"); - ID_ANNOTATIONS.add("javax.persistence.Id"); - ID_ANNOTATIONS.add("javax.persistence.EmbeddedId"); - } + static { + ID_ANNOTATIONS.add("org.springframework.data.annotation.Id"); + ID_ANNOTATIONS.add("javax.persistence.Id"); + ID_ANNOTATIONS.add("javax.persistence.EmbeddedId"); + } - private IdPropertyResolverUtils() { - throw new UnsupportedOperationException(); - } + private IdPropertyResolverUtils() { + throw new UnsupportedOperationException(); + } - /** - * Returns the name of the property as represented by the method given - * - * @param entityType the type of the entity that the ID is being resolved for - * @param idType the type of the ID expected for the entity - * @param idAnnotatedMethod the method that will return the ID (e.g. getter for the ID property) - * @return the name of the property, or {@literal null} if the method is {@literal null} - */ - public static String getPropertyNameFromAnnotatedMethod(Class entityType, Class idType, - Method idAnnotatedMethod) { - if (idAnnotatedMethod != null) { - final String name = PropertyUtils.getPropertyName(idAnnotatedMethod); - if (!PropertyUtils.getTypeOf(idType).isAssignableFrom( - PropertyUtils.getTypeOf(idAnnotatedMethod.getReturnType()))) { - throw new PropertyTypeMismatchException(entityType, name, idType, idAnnotatedMethod.getReturnType()); - } else { - return name; - } - } - return null; + /** + * Returns the name of the property as represented by the method given + * + * @param entityType the type of the entity that the ID is being resolved for + * @param idType the type of the ID expected for the entity + * @param idAnnotatedMethod the method that will return the ID (e.g. getter for the ID property) + * @return the name of the property, or {@literal null} if the method is {@literal null} + */ + public static String getPropertyNameFromAnnotatedMethod( + Class entityType, Class idType, Method idAnnotatedMethod) { + if (idAnnotatedMethod != null) { + final String name = PropertyUtils.getPropertyName(idAnnotatedMethod); + if (!PropertyUtils.getTypeOf(idType) + .isAssignableFrom(PropertyUtils.getTypeOf(idAnnotatedMethod.getReturnType()))) { + throw new PropertyTypeMismatchException( + entityType, name, idType, idAnnotatedMethod.getReturnType()); + } else { + return name; + } } + return null; + } - /** - * Determines whether or not the given element is annotated with the annotations specified by {@link - * #getIdAnnotations()} - * - * @param element the element to be examined - * @return {@literal true} if the element has any of the ID annotations - */ - public static boolean isAnnotated(AnnotatedElement element) { - final List> annotations = getIdAnnotations(); - for (Class annotation : annotations) { - if (AnnotationUtils.findAnnotation(element, annotation) != null) { - return true; - } - } - return false; + /** + * Determines whether or not the given element is annotated with the annotations specified by + * {@link #getIdAnnotations()} + * + * @param element the element to be examined + * @return {@literal true} if the element has any of the ID annotations + */ + public static boolean isAnnotated(AnnotatedElement element) { + final List> annotations = getIdAnnotations(); + for (Class annotation : annotations) { + if (AnnotationUtils.findAnnotation(element, annotation) != null) { + return true; + } } + return false; + } - /** - * Lists all the annotations that can be used to mark a property as the ID property based on the libraries that can - * be found in the classpath - * - * @return the list of annotations - */ - private static List> getIdAnnotations() { - final List> annotations = new ArrayList<>(); - final ClassLoader classLoader = ClassUtils.getDefaultClassLoader(); - for (String idAnnotation : ID_ANNOTATIONS) { - try { - final Class type = ClassUtils.forName(idAnnotation, classLoader); - final Class annotationType = type.asSubclass(Annotation.class); - annotations.add(annotationType); - } catch (ClassNotFoundException ignored) { - //if the class for the annotation wasn't found, we just ignore it - log.debug("Requested ID annotation type " + idAnnotation + " is not present in the classpath"); - } - } - return annotations; + /** + * Lists all the annotations that can be used to mark a property as the ID property based on the + * libraries that can be found in the classpath + * + * @return the list of annotations + */ + private static List> getIdAnnotations() { + final List> annotations = new ArrayList<>(); + final ClassLoader classLoader = ClassUtils.getDefaultClassLoader(); + for (String idAnnotation : ID_ANNOTATIONS) { + try { + final Class type = ClassUtils.forName(idAnnotation, classLoader); + final Class annotationType = type.asSubclass(Annotation.class); + annotations.add(annotationType); + } catch (ClassNotFoundException ignored) { + // if the class for the annotation wasn't found, we just ignore it + log.debug( + "Requested ID annotation type " + idAnnotation + " is not present in the classpath"); + } } - + return annotations; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedFieldIdPropertyResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedFieldIdPropertyResolver.java index 1a47a9f4..58b61043 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedFieldIdPropertyResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedFieldIdPropertyResolver.java @@ -16,17 +16,18 @@ @SuppressWarnings("WeakerAccess") public class NamedFieldIdPropertyResolver implements IdPropertyResolver { - @Override - public String resolve(Class entityType, Class idType) { - final Field field = ReflectionUtils.findField(entityType, "id"); - if (field != null) { - if (PropertyUtils.getTypeOf(idType).isAssignableFrom(PropertyUtils.getTypeOf(field.getType()))) { - return field.getName(); - } else { - throw new PropertyTypeMismatchException(entityType, field.getName(), idType, field.getType()); - } - } - return null; + @Override + public String resolve(Class entityType, Class idType) { + final Field field = ReflectionUtils.findField(entityType, "id"); + if (field != null) { + if (PropertyUtils.getTypeOf(idType) + .isAssignableFrom(PropertyUtils.getTypeOf(field.getType()))) { + return field.getName(); + } else { + throw new PropertyTypeMismatchException( + entityType, field.getName(), idType, field.getType()); + } } - + return null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedGetterIdPropertyResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedGetterIdPropertyResolver.java index 3f1f2bbd..beee5b62 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedGetterIdPropertyResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedGetterIdPropertyResolver.java @@ -11,8 +11,8 @@ import static com.mmnaseri.utils.spring.data.domain.impl.id.IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod; /** - * This class is for resolving an ID based on the getter. It will try to find a getter for a property named {@literal - * "id"} -- i.e., it will look for a getter named "getId". + * This class is for resolving an ID based on the getter. It will try to find a getter for a + * property named {@literal "id"} -- i.e., it will look for a getter named "getId". * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) @@ -20,16 +20,18 @@ @SuppressWarnings("WeakerAccess") public class NamedGetterIdPropertyResolver implements IdPropertyResolver { - @Override - public String resolve(Class entityType, final Class idType) { - final AtomicReference found = new AtomicReference<>(); - ReflectionUtils.doWithMethods(entityType, method -> { - if (PropertyUtils.getPropertyName(method).equals("id")) { - found.set(method); - } - }, new GetterMethodFilter()); - final Method idAnnotatedMethod = found.get(); - return getPropertyNameFromAnnotatedMethod(entityType, idType, idAnnotatedMethod); - } - + @Override + public String resolve(Class entityType, final Class idType) { + final AtomicReference found = new AtomicReference<>(); + ReflectionUtils.doWithMethods( + entityType, + method -> { + if (PropertyUtils.getPropertyName(method).equals("id")) { + found.set(method); + } + }, + new GetterMethodFilter()); + final Method idAnnotatedMethod = found.get(); + return getPropertyNameFromAnnotatedMethod(entityType, idType, idAnnotatedMethod); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGenerator.java index 0ac42f83..c97dee31 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGenerator.java @@ -5,9 +5,8 @@ public class BsonObjectIdKeyGenerator implements KeyGenerator { - @Override - public ObjectId generate() { - return ObjectId.get(); - } - + @Override + public ObjectId generate() { + return ObjectId.get(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGenerator.java index 54ca23bb..5fd87e6a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGenerator.java @@ -10,25 +10,24 @@ */ public class ConfigurableSequentialIntegerKeyGenerator extends AbstractRandomKeyGenerator { - private final AtomicInteger current; - private final int step; - - public ConfigurableSequentialIntegerKeyGenerator() { - this(1); - } - - public ConfigurableSequentialIntegerKeyGenerator(int initialValue) { - this(initialValue, 1); - } - - public ConfigurableSequentialIntegerKeyGenerator(int initialValue, int step) { - current = new AtomicInteger(initialValue); - this.step = step; - } - - @Override - protected Integer getNext() { - return current.getAndAdd(step); - } - + private final AtomicInteger current; + private final int step; + + public ConfigurableSequentialIntegerKeyGenerator() { + this(1); + } + + public ConfigurableSequentialIntegerKeyGenerator(int initialValue) { + this(initialValue, 1); + } + + public ConfigurableSequentialIntegerKeyGenerator(int initialValue, int step) { + current = new AtomicInteger(initialValue); + this.step = step; + } + + @Override + protected Integer getNext() { + return current.getAndAdd(step); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGenerator.java index 086d72c9..39fed20f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGenerator.java @@ -10,26 +10,24 @@ */ public class ConfigurableSequentialLongKeyGenerator extends AbstractRandomKeyGenerator { - private final AtomicLong current; - private final long step; - - public ConfigurableSequentialLongKeyGenerator() { - this(1L); - } - - - public ConfigurableSequentialLongKeyGenerator(long initialValue) { - this(initialValue, 1L); - } - - public ConfigurableSequentialLongKeyGenerator(long initialValue, long step) { - current = new AtomicLong(initialValue); - this.step = step; - } - - @Override - protected Long getNext() { - return current.getAndAdd(step); - } - + private final AtomicLong current; + private final long step; + + public ConfigurableSequentialLongKeyGenerator() { + this(1L); + } + + public ConfigurableSequentialLongKeyGenerator(long initialValue) { + this(initialValue, 1L); + } + + public ConfigurableSequentialLongKeyGenerator(long initialValue, long step) { + current = new AtomicLong(initialValue); + this.step = step; + } + + @Override + protected Long getNext() { + return current.getAndAdd(step); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/NoOpKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/NoOpKeyGenerator.java index 59c02687..873cfe61 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/NoOpKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/NoOpKeyGenerator.java @@ -3,16 +3,16 @@ import com.mmnaseri.utils.spring.data.domain.KeyGenerator; /** - * This is a key generator that should be used to indicate that we do not want automatic key generation. + * This is a key generator that should be used to indicate that we do not want automatic key + * generation. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (6/14/16, 12:51 PM) */ public class NoOpKeyGenerator implements KeyGenerator { - @Override - public S generate() { - return null; - } - + @Override + public S generate() { + return null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/RandomIntegerKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/RandomIntegerKeyGenerator.java index a49fed0d..6ad7b954 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/RandomIntegerKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/RandomIntegerKeyGenerator.java @@ -13,11 +13,10 @@ */ public class RandomIntegerKeyGenerator extends AbstractRandomKeyGenerator { - private final Random random = ThreadLocalRandom.current(); - - @Override - protected Integer getNext() { - return random.nextInt(); - } + private final Random random = ThreadLocalRandom.current(); + @Override + protected Integer getNext() { + return random.nextInt(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/RandomLongKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/RandomLongKeyGenerator.java index 626a2dab..5bb3d9ba 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/RandomLongKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/RandomLongKeyGenerator.java @@ -13,11 +13,10 @@ */ public class RandomLongKeyGenerator extends AbstractRandomKeyGenerator { - private final Random seed = ThreadLocalRandom.current(); - - @Override - protected Long getNext() { - return seed.nextLong(); - } + private final Random seed = ThreadLocalRandom.current(); + @Override + protected Long getNext() { + return seed.nextLong(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/SequentialIntegerKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/SequentialIntegerKeyGenerator.java index 74b1b1b7..afa73d6f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/SequentialIntegerKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/SequentialIntegerKeyGenerator.java @@ -12,11 +12,10 @@ */ public class SequentialIntegerKeyGenerator implements KeyGenerator { - private final AtomicInteger seed = new AtomicInteger(1); - - @Override - public Integer generate() { - return seed.getAndIncrement(); - } + private final AtomicInteger seed = new AtomicInteger(1); + @Override + public Integer generate() { + return seed.getAndIncrement(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/SequentialLongKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/SequentialLongKeyGenerator.java index 39deed41..dd4c9983 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/SequentialLongKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/SequentialLongKeyGenerator.java @@ -12,11 +12,10 @@ */ public class SequentialLongKeyGenerator implements KeyGenerator { - private final AtomicLong seed = new AtomicLong(1); - - @Override - public Long generate() { - return seed.getAndIncrement(); - } + private final AtomicLong seed = new AtomicLong(1); + @Override + public Long generate() { + return seed.getAndIncrement(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/UUIDKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/UUIDKeyGenerator.java index 233b9664..2c61ba57 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/UUIDKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/key/UUIDKeyGenerator.java @@ -12,9 +12,8 @@ */ public class UUIDKeyGenerator implements KeyGenerator { - @Override - public String generate() { - return UUID.randomUUID().toString(); - } - + @Override + public String generate() { + return UUID.randomUUID().toString(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryComparableMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryComparableMatcher.java index ff6e3f97..b148352b 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryComparableMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryComparableMatcher.java @@ -4,30 +4,32 @@ import com.mmnaseri.utils.spring.data.error.InvalidArgumentException; /** - * This class is the base class used for doing binary operations when both operands are {@link Comparable Comparable} - * objects + * This class is the base class used for doing binary operations when both operands are {@link + * Comparable Comparable} objects * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public abstract class AbstractBinaryComparableMatcher extends AbstractBinaryMatcher { - @Override - protected final boolean matches(Parameter parameter, Object value, Object first, Object second) { - if (!(value instanceof Comparable) || !(first instanceof Comparable) || !(second instanceof Comparable)) { - throw new InvalidArgumentException("Expected values to be comparable: " + parameter.getPath()); - } - return matches((Comparable) value, (Comparable) first, (Comparable) second); + @Override + protected final boolean matches(Parameter parameter, Object value, Object first, Object second) { + if (!(value instanceof Comparable) + || !(first instanceof Comparable) + || !(second instanceof Comparable)) { + throw new InvalidArgumentException( + "Expected values to be comparable: " + parameter.getPath()); } + return matches((Comparable) value, (Comparable) first, (Comparable) second); + } - /** - * Is called to determine when the two comparable items fit the criteria of this matcher - * - * @param value the value against which the comparison is being performed - * @param first the first value - * @param second the second value - * @return {@literal true} if it was a match - */ - protected abstract boolean matches(Comparable value, Comparable first, Comparable second); - + /** + * Is called to determine when the two comparable items fit the criteria of this matcher + * + * @param value the value against which the comparison is being performed + * @param first the first value + * @param second the second value + * @return {@literal true} if it was a match + */ + protected abstract boolean matches(Comparable value, Comparable first, Comparable second); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryMatcher.java index 1dd4ad88..6db55e3f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryMatcher.java @@ -3,6 +3,7 @@ import com.mmnaseri.utils.spring.data.domain.Matcher; import com.mmnaseri.utils.spring.data.domain.Parameter; import com.mmnaseri.utils.spring.data.error.InvalidArgumentException; +import com.mmnaseri.utils.spring.data.tools.PropertyUtils; /** * Used for matching operands to a binary operator @@ -12,31 +13,36 @@ */ public abstract class AbstractBinaryMatcher implements Matcher { - @Override - public final boolean matches(Parameter parameter, Object value, Object... properties) { - if (properties.length != 2) { - throw new InvalidArgumentException( - "Expected two values to be passed to operator " + parameter.getOperator().getName() + " at " - + parameter.getPath()); - } - return matches(parameter, value, properties[0], properties[1]); + @Override + public final boolean matches(Parameter parameter, Object value, Object... properties) { + if (properties.length != 2) { + throw new InvalidArgumentException( + "Expected two values to be passed to operator " + + parameter.getOperator().getName() + + " at " + + parameter.getPath()); } + return matches(parameter, value, properties[0], properties[1]); + } - /** - * Called to see if two objects match the criteria set by this matcher - * - * @param parameter the parameter against which the matching is being performed - * @param value the value bound to the matching - * @param first the first operand - * @param second the second operand - * @return {@literal true} if it was a match - */ - protected abstract boolean matches(Parameter parameter, Object value, Object first, Object second); + /** + * Called to see if two objects match the criteria set by this matcher + * + * @param parameter the parameter against which the matching is being performed + * @param value the value bound to the matching + * @param first the first operand + * @param second the second operand + * @return {@literal true} if it was a match + */ + protected abstract boolean matches( + Parameter parameter, Object value, Object first, Object second); - @Override - public boolean isApplicableTo(Class parameterType, Class... propertiesTypes) { - return propertiesTypes.length == 2 - && parameterType.isAssignableFrom(propertiesTypes[0]) - && parameterType.isAssignableFrom(propertiesTypes[1]); - } + @Override + public boolean isApplicableTo(Class parameterType, Class... propertiesTypes) { + return propertiesTypes.length == 2 + && PropertyUtils.getTypeOf(parameterType) + .isAssignableFrom(PropertyUtils.getTypeOf(propertiesTypes[0])) + && PropertyUtils.getTypeOf(parameterType) + .isAssignableFrom(PropertyUtils.getTypeOf(propertiesTypes[1])); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcher.java index f423c444..2a033a46 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcher.java @@ -16,56 +16,57 @@ */ public abstract class AbstractCollectionMatcher extends AbstractSimpleMatcher { - @Override - protected final boolean matches(Parameter parameter, Object actual, Object property) { - if (property == null) { - throw new InvalidArgumentException("Comparison property cannot be null: " + parameter.getPath()); - } - final Collection collection; - if (property.getClass().isArray()) { - // if it was an array, we do array to collection conversion, which is pretty straightforward - collection = new LinkedList(); - for (int i = 0; i < Array.getLength(property); i++) { - final Object item = Array.get(property, i); - //noinspection unchecked - collection.add(item); - } - } else if (property instanceof Iterator) { - // if it is an iterator, we just iterate it forward - collection = new LinkedList(); - final Iterator iterator = (Iterator) property; - while (iterator.hasNext()) { - //noinspection unchecked - collection.add(iterator.next()); - } - } else if (property instanceof Iterable) { - //if it is already an iterable object, we just iterate over it. - collection = new LinkedList(); - for (Object item : ((Iterable) property)) { - //noinspection unchecked - collection.add(item); - } - } else { - //otherwise, we just don't know how to convert it! - throw new InvalidArgumentException("Expected an array, an iterator, or an iterable object"); - } - return matches(actual, collection); + @Override + protected final boolean matches(Parameter parameter, Object actual, Object property) { + if (property == null) { + throw new InvalidArgumentException( + "Comparison property cannot be null: " + parameter.getPath()); } + final Collection collection; + if (property.getClass().isArray()) { + // if it was an array, we do array to collection conversion, which is pretty straightforward + collection = new LinkedList(); + for (int i = 0; i < Array.getLength(property); i++) { + final Object item = Array.get(property, i); + //noinspection unchecked + collection.add(item); + } + } else if (property instanceof Iterator) { + // if it is an iterator, we just iterate it forward + collection = new LinkedList(); + final Iterator iterator = (Iterator) property; + while (iterator.hasNext()) { + //noinspection unchecked + collection.add(iterator.next()); + } + } else if (property instanceof Iterable) { + // if it is already an iterable object, we just iterate over it. + collection = new LinkedList(); + for (Object item : ((Iterable) property)) { + //noinspection unchecked + collection.add(item); + } + } else { + // otherwise, we just don't know how to convert it! + throw new InvalidArgumentException("Expected an array, an iterator, or an iterable object"); + } + return matches(actual, collection); + } - /** - * Used to find out if a collection satisfies the condition set forth by this matcher - * - * @param actual the actual value - * @param collection the collection - * @return {@literal true} if the match was a success - */ - protected abstract boolean matches(Object actual, Collection collection); + /** + * Used to find out if a collection satisfies the condition set forth by this matcher + * + * @param actual the actual value + * @param collection the collection + * @return {@literal true} if the match was a success + */ + protected abstract boolean matches(Object actual, Collection collection); - @Override - public boolean isApplicableTo(Class parameterType, Class... propertiesTypes) { - Class propertyType = propertiesTypes[0]; - return Collection.class.isAssignableFrom(propertyType) - || Iterator.class.isAssignableFrom(propertyType) - || Iterable.class.isAssignableFrom(propertyType); - } + @Override + public boolean isApplicableTo(Class parameterType, Class... propertiesTypes) { + Class propertyType = propertiesTypes[0]; + return Collection.class.isAssignableFrom(propertyType) + || Iterator.class.isAssignableFrom(propertyType) + || Iterable.class.isAssignableFrom(propertyType); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcher.java index 37edb10f..94e086c1 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcher.java @@ -11,21 +11,21 @@ */ public abstract class AbstractSimpleComparableMatcher extends AbstractSimpleMatcher { - @Override - protected final boolean matches(Parameter parameter, Object actual, Object expected) { - if (!(actual instanceof Comparable) || !(expected instanceof Comparable)) { - throw new InvalidArgumentException("Expected property to be comparable: " + parameter.getPath()); - } - return matches((Comparable) actual, (Comparable) expected); + @Override + protected final boolean matches(Parameter parameter, Object actual, Object expected) { + if (!(actual instanceof Comparable) || !(expected instanceof Comparable)) { + throw new InvalidArgumentException( + "Expected property to be comparable: " + parameter.getPath()); } + return matches((Comparable) actual, (Comparable) expected); + } - /** - * Does comparison and returns the result. - * - * @param actual the actual value - * @param pivot the pivot - * @return {@literal true} if the match succeeded - */ - protected abstract boolean matches(Comparable actual, Comparable pivot); - + /** + * Does comparison and returns the result. + * + * @param actual the actual value + * @param pivot the pivot + * @return {@literal true} if the match succeeded + */ + protected abstract boolean matches(Comparable actual, Comparable pivot); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleMatcher.java index 6520a479..1a7a0713 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleMatcher.java @@ -3,6 +3,7 @@ import com.mmnaseri.utils.spring.data.domain.Matcher; import com.mmnaseri.utils.spring.data.domain.Parameter; import com.mmnaseri.utils.spring.data.error.InvalidArgumentException; +import com.mmnaseri.utils.spring.data.tools.PropertyUtils; /** * This matcher is used to determine if a condition holds for a single parameter @@ -12,27 +13,29 @@ */ public abstract class AbstractSimpleMatcher implements Matcher { - @Override - public final boolean matches(Parameter parameter, Object value, Object... properties) { - if (properties.length != 1) { - throw new InvalidArgumentException( - "Expected exactly one parameter to be passed down: " + parameter.getPath()); - } - return matches(parameter, value, properties[0]); + @Override + public final boolean matches(Parameter parameter, Object value, Object... properties) { + if (properties.length != 1) { + throw new InvalidArgumentException( + "Expected exactly one parameter to be passed down: " + parameter.getPath()); } + return matches(parameter, value, properties[0]); + } - /** - * Called to see if the condition holds - * - * @param parameter the parameter - * @param actual the actual value - * @param expected the expectation - * @return {@literal true} if the condition holds - */ - protected abstract boolean matches(Parameter parameter, Object actual, Object expected); + /** + * Called to see if the condition holds + * + * @param parameter the parameter + * @param actual the actual value + * @param expected the expectation + * @return {@literal true} if the condition holds + */ + protected abstract boolean matches(Parameter parameter, Object actual, Object expected); - @Override - public boolean isApplicableTo(Class parameterType, Class... propertiesTypes) { - return propertiesTypes.length == 1 && parameterType.isAssignableFrom(propertiesTypes[0]); - } + @Override + public boolean isApplicableTo(Class parameterType, Class... propertiesTypes) { + return propertiesTypes.length == 1 + && PropertyUtils.getTypeOf(parameterType) + .isAssignableFrom(PropertyUtils.getTypeOf(propertiesTypes[0])); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcher.java index 06f55e80..6d2c933c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcher.java @@ -12,27 +12,27 @@ */ public abstract class AbstractSimpleStringMatcher extends AbstractSimpleMatcher { - @Override - protected final boolean matches(Parameter parameter, Object actual, Object expected) { - if (!(actual instanceof String) || !(expected instanceof String)) { - throw new InvalidArgumentException("Expected string values for property: " + parameter.getPath()); - } - String first = (String) actual; - String second = (String) expected; - if (parameter.getModifiers().contains(Modifier.IGNORE_CASE)) { - first = first.toLowerCase(); - second = second.toLowerCase(); - } - return matches(first, second); + @Override + protected final boolean matches(Parameter parameter, Object actual, Object expected) { + if (!(actual instanceof String) || !(expected instanceof String)) { + throw new InvalidArgumentException( + "Expected string values for property: " + parameter.getPath()); } + String first = (String) actual; + String second = (String) expected; + if (parameter.getModifiers().contains(Modifier.IGNORE_CASE)) { + first = first.toLowerCase(); + second = second.toLowerCase(); + } + return matches(first, second); + } - /** - * Called when we want to check the expectation - * - * @param actual the actual value - * @param argument the argument to the operator - * @return {@literal true} if the match succeeded - */ - protected abstract boolean matches(String actual, String argument); - + /** + * Called when we want to check the expectation + * + * @param actual the actual value + * @param argument the argument to the operator + * @return {@literal true} if the match succeeded + */ + protected abstract boolean matches(String actual, String argument); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractUnaryMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractUnaryMatcher.java index ead026b0..5d02d6cd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractUnaryMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractUnaryMatcher.java @@ -12,26 +12,28 @@ */ public abstract class AbstractUnaryMatcher implements Matcher { - @Override - public final boolean matches(Parameter parameter, Object value, Object... properties) { - if (properties.length != 0) { - throw new InvalidArgumentException( - "This operator does not take any operands: " + parameter.getOperator().getName() + " at " - + parameter.getPath()); - } - return matches(value); + @Override + public final boolean matches(Parameter parameter, Object value, Object... properties) { + if (properties.length != 0) { + throw new InvalidArgumentException( + "This operator does not take any operands: " + + parameter.getOperator().getName() + + " at " + + parameter.getPath()); } + return matches(value); + } - /** - * Called to determine the match - * - * @param value the expected value - * @return {@literal true} if the match applies - */ - protected abstract boolean matches(Object value); + /** + * Called to determine the match + * + * @param value the expected value + * @return {@literal true} if the match applies + */ + protected abstract boolean matches(Object value); - @Override - public boolean isApplicableTo(Class parameterType, Class... propertiesTypes) { - return propertiesTypes.length == 0; - } + @Override + public boolean isApplicableTo(Class parameterType, Class... propertiesTypes) { + return propertiesTypes.length == 0; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/ContainingMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/ContainingMatcher.java index 9df541ce..d7e3e724 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/ContainingMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/ContainingMatcher.java @@ -1,17 +1,18 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This class will look for a substring in the passed string value by converting both the needle and the haystack to - * lower case. + * This class will look for a substring in the passed string value by converting both the needle and + * the haystack to lower case. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class ContainingMatcher extends AbstractSimpleStringMatcher { - @Override - protected boolean matches(String actual, String argument) { - return actual != null && argument != null && actual.toLowerCase().contains(argument.toLowerCase()); - } - + @Override + protected boolean matches(String actual, String argument) { + return actual != null + && argument != null + && actual.toLowerCase().contains(argument.toLowerCase()); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/EndingWithMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/EndingWithMatcher.java index c87b7bb1..e83ff45b 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/EndingWithMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/EndingWithMatcher.java @@ -1,17 +1,19 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This class is used to find out if the given value ends with the passed argument. Remember that this will convert both - * the needle and the haystack to lower case, so the search is case-insensitive. + * This class is used to find out if the given value ends with the passed argument. Remember that + * this will convert both the needle and the haystack to lower case, so the search is + * case-insensitive. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class EndingWithMatcher extends AbstractSimpleStringMatcher { - @Override - protected boolean matches(String actual, String argument) { - return actual != null && argument != null && actual.toLowerCase().endsWith(argument.toLowerCase()); - } - + @Override + protected boolean matches(String actual, String argument) { + return actual != null + && argument != null + && actual.toLowerCase().endsWith(argument.toLowerCase()); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsBetweenMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsBetweenMatcher.java index a380016a..9d27139a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsBetweenMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsBetweenMatcher.java @@ -1,23 +1,27 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - *

This comparing matcher will determine if the passed value is larger or equal to the first passed argument and - * smaller or equal to the second passed argument, thus determining if it falls between the two values.

+ * This comparing matcher will determine if the passed value is larger or equal to the first passed + * argument and smaller or equal to the second passed argument, thus determining if it falls between + * the two values. * - *

NB: This matcher does not check whether or not the two values passed are in the - * right order, as a normal database wouldn't. If you need this functionality, you will need to define a new {@link - * com.mmnaseri.utils.spring.data.domain.Operator operator} and add your own matcher.

+ *

NB: This matcher does not check whether or not the two values passed are in + * the right order, as a normal database wouldn't. If you need this functionality, you will need to + * define a new {@link com.mmnaseri.utils.spring.data.domain.Operator operator} and add your own + * matcher. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsBetweenMatcher extends AbstractBinaryComparableMatcher { - @Override - protected boolean matches(Comparable value, Comparable first, Comparable second) { - //noinspection unchecked - return value != null && first != null && second != null && first.compareTo(value) <= 0 && second.compareTo( - value) >= 0; - } - + @Override + protected boolean matches(Comparable value, Comparable first, Comparable second) { + //noinspection unchecked + return value != null + && first != null + && second != null + && first.compareTo(value) <= 0 + && second.compareTo(value) >= 0; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsEqualToMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsEqualToMatcher.java index c316f5ff..3da277ef 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsEqualToMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsEqualToMatcher.java @@ -5,17 +5,16 @@ import java.util.Objects; /** - * This matcher will check to see if the value is strictly equal to the value passed as the argument of the query - * method. This also includes equating null values. + * This matcher will check to see if the value is strictly equal to the value passed as the argument + * of the query method. This also includes equating null values. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public class IsEqualToMatcher extends AbstractSimpleMatcher { - @Override - protected boolean matches(Parameter parameter, Object actual, Object expected) { - return Objects.equals(actual, expected); - } - + @Override + protected boolean matches(Parameter parameter, Object actual, Object expected) { + return Objects.equals(actual, expected); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsFalseMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsFalseMatcher.java index e61a1d1a..00150021 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsFalseMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsFalseMatcher.java @@ -8,9 +8,8 @@ */ public class IsFalseMatcher extends AbstractUnaryMatcher { - @Override - protected boolean matches(Object value) { - return Boolean.FALSE.equals(value); - } - + @Override + protected boolean matches(Object value) { + return Boolean.FALSE.equals(value); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanMatcher.java index 32e9499b..cd6ca2c4 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanMatcher.java @@ -1,17 +1,17 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This will check to see if the value on the object is greater than the argument being passed (the pivot). + * This will check to see if the value on the object is greater than the argument being passed (the + * pivot). * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsGreaterThanMatcher extends AbstractSimpleComparableMatcher { - @Override - protected boolean matches(Comparable actual, Comparable pivot) { - //noinspection unchecked - return actual != null && pivot != null && pivot.compareTo(actual) < 0; - } - + @Override + protected boolean matches(Comparable actual, Comparable pivot) { + //noinspection unchecked + return actual != null && pivot != null && pivot.compareTo(actual) < 0; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanOrEqualToMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanOrEqualToMatcher.java index 8b5f0697..e2231fde 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanOrEqualToMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanOrEqualToMatcher.java @@ -1,18 +1,17 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This will check to see if the value on the object is greater than or equal to the argument being passed (the - * pivot). + * This will check to see if the value on the object is greater than or equal to the argument being + * passed (the pivot). * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsGreaterThanOrEqualToMatcher extends AbstractSimpleComparableMatcher { - @Override - protected boolean matches(Comparable actual, Comparable pivot) { - //noinspection unchecked - return actual != null && pivot != null && pivot.compareTo(actual) <= 0; - } - + @Override + protected boolean matches(Comparable actual, Comparable pivot) { + //noinspection unchecked + return actual != null && pivot != null && pivot.compareTo(actual) <= 0; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsInMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsInMatcher.java index b4853de9..589b9f13 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsInMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsInMatcher.java @@ -3,16 +3,16 @@ import java.util.Collection; /** - * This matcher checks to see if the argument being passed (the collection) contains the value on the object. + * This matcher checks to see if the argument being passed (the collection) contains the value on + * the object. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsInMatcher extends AbstractCollectionMatcher { - @Override - protected boolean matches(Object actual, Collection collection) { - return actual != null && collection.contains(actual); - } - + @Override + protected boolean matches(Object actual, Collection collection) { + return actual != null && collection.contains(actual); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanMatcher.java index 4e478255..50e022f3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanMatcher.java @@ -1,17 +1,17 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This will check to see if the value on the object is less than the argument being passed (the pivot). + * This will check to see if the value on the object is less than the argument being passed (the + * pivot). * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsLessThanMatcher extends AbstractSimpleComparableMatcher { - @Override - protected boolean matches(Comparable actual, Comparable pivot) { - //noinspection unchecked - return actual != null && pivot != null && pivot.compareTo(actual) > 0; - } - + @Override + protected boolean matches(Comparable actual, Comparable pivot) { + //noinspection unchecked + return actual != null && pivot != null && pivot.compareTo(actual) > 0; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanOrEqualToMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanOrEqualToMatcher.java index fa2774a5..a8997e8c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanOrEqualToMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanOrEqualToMatcher.java @@ -1,17 +1,17 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This will check to see if the value on the object is less than the or equal to argument being passed (the pivot). + * This will check to see if the value on the object is less than the or equal to argument being + * passed (the pivot). * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsLessThanOrEqualToMatcher extends AbstractSimpleComparableMatcher { - @Override - protected boolean matches(Comparable actual, Comparable pivot) { - //noinspection unchecked - return actual != null && pivot != null && pivot.compareTo(actual) >= 0; - } - + @Override + protected boolean matches(Comparable actual, Comparable pivot) { + //noinspection unchecked + return actual != null && pivot != null && pivot.compareTo(actual) >= 0; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLikeMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLikeMatcher.java index 446f9eb2..85552a25 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLikeMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLikeMatcher.java @@ -8,9 +8,8 @@ */ public class IsLikeMatcher extends AbstractSimpleStringMatcher { - @Override - protected boolean matches(String actual, String argument) { - return actual != null && actual.equalsIgnoreCase(argument); - } - + @Override + protected boolean matches(String actual, String argument) { + return actual != null && actual.equalsIgnoreCase(argument); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcher.java index 2561fe88..b48f9042 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcher.java @@ -1,24 +1,25 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - *

This comparing matcher will determine if the passed value is smaller or equal to the first passed argument and - * larger or equal to the second passed argument, thus determining if it does not fall between the two values (if they - * are in in ascending order themselves).

+ * This comparing matcher will determine if the passed value is smaller or equal to the first passed + * argument and larger or equal to the second passed argument, thus determining if it does not fall + * between the two values (if they are in in ascending order themselves). * - *

NB: This matcher does not check whether or not the two values passed are in the - * right order, as a normal database wouldn't. If you need this functionality, you will need to define a new {@link - * com.mmnaseri.utils.spring.data.domain.Operator operator} and add your own matcher.

+ *

NB: This matcher does not check whether or not the two values passed are in + * the right order, as a normal database wouldn't. If you need this functionality, you will need to + * define a new {@link com.mmnaseri.utils.spring.data.domain.Operator operator} and add your own + * matcher. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsNotBetweenMatcher extends AbstractBinaryComparableMatcher { - @Override - protected boolean matches(Comparable value, Comparable first, Comparable second) { - //noinspection unchecked - return first != null && second != null && (value == null || first.compareTo(value) > 0 || second.compareTo( - value) < 0); - } - + @Override + protected boolean matches(Comparable value, Comparable first, Comparable second) { + //noinspection unchecked + return first != null + && second != null + && (value == null || first.compareTo(value) > 0 || second.compareTo(value) < 0); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcher.java index f6286a95..3677dbe9 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcher.java @@ -3,17 +3,16 @@ import java.util.Collection; /** - * This matcher checks whether or not the argument passed to the query method (the collection) contains the value on the - * object itself and fails the check if it does. + * This matcher checks whether or not the argument passed to the query method (the collection) + * contains the value on the object itself and fails the check if it does. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsNotInMatcher extends AbstractCollectionMatcher { - @Override - protected boolean matches(Object actual, Collection collection) { - return !collection.contains(actual); - } - + @Override + protected boolean matches(Object actual, Collection collection) { + return !collection.contains(actual); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcher.java index db10ec49..8302555c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcher.java @@ -1,18 +1,18 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This matcher will return {@literal true} if the argument passed is not equal to the value on the object, even when - * their case differences are ignored. + * This matcher will return {@literal true} if the argument passed is not equal to the value on the + * object, even when their case differences are ignored. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class IsNotLikeMatcher extends AbstractSimpleStringMatcher { - @Override - protected boolean matches(String actual, String argument) { - return (actual == null && argument != null) || (actual != null && argument == null) || (actual != null - && !actual.equalsIgnoreCase(argument)); - } - + @Override + protected boolean matches(String actual, String argument) { + return (actual == null && argument != null) + || (actual != null && argument == null) + || (actual != null && !actual.equalsIgnoreCase(argument)); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotMatcher.java index 9a770309..36ab7440 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotMatcher.java @@ -12,8 +12,8 @@ */ public class IsNotMatcher extends AbstractSimpleMatcher { - @Override - protected boolean matches(Parameter parameter, Object actual, Object expected) { - return !Objects.equals(actual, expected); - } + @Override + protected boolean matches(Parameter parameter, Object actual, Object expected) { + return !Objects.equals(actual, expected); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotNullMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotNullMatcher.java index 98f2b1de..61aaeca6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotNullMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotNullMatcher.java @@ -8,9 +8,8 @@ */ public class IsNotNullMatcher extends AbstractUnaryMatcher { - @Override - protected boolean matches(Object value) { - return value != null; - } - + @Override + protected boolean matches(Object value) { + return value != null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNullMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNullMatcher.java index 59aeaafc..be5aada8 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNullMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNullMatcher.java @@ -8,8 +8,8 @@ */ public class IsNullMatcher extends AbstractUnaryMatcher { - @Override - protected boolean matches(Object value) { - return value == null; - } + @Override + protected boolean matches(Object value) { + return value == null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsTrueMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsTrueMatcher.java index 2bc6c0fd..aef6848a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsTrueMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsTrueMatcher.java @@ -8,9 +8,8 @@ */ public class IsTrueMatcher extends AbstractUnaryMatcher { - @Override - protected boolean matches(Object value) { - return Boolean.TRUE.equals(value); - } - + @Override + protected boolean matches(Object value) { + return Boolean.TRUE.equals(value); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcher.java index 56381b7d..a1d5b735 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcher.java @@ -1,16 +1,16 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This matcher will determine if the value on the object (a string) matches the pattern being passed. + * This matcher will determine if the value on the object (a string) matches the pattern being + * passed. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class RegexMatcher extends AbstractSimpleStringMatcher { - @Override - protected boolean matches(String actual, String argument) { - return actual != null && argument != null && actual.matches(argument); - } - + @Override + protected boolean matches(String actual, String argument) { + return actual != null && argument != null && actual.matches(argument); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/StartingWithMatcher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/StartingWithMatcher.java index 69e6901e..b4e87593 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/StartingWithMatcher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/StartingWithMatcher.java @@ -1,17 +1,19 @@ package com.mmnaseri.utils.spring.data.domain.impl.matchers; /** - * This class is used to find out if the given value starts with the passed argument. Remember that this will convert - * both the needle and the haystack to lower case, so the search is case-insensitive. + * This class is used to find out if the given value starts with the passed argument. Remember that + * this will convert both the needle and the haystack to lower case, so the search is + * case-insensitive. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class StartingWithMatcher extends AbstractSimpleStringMatcher { - @Override - protected boolean matches(String actual, String argument) { - return actual != null && argument != null && actual.toLowerCase().startsWith(argument.toLowerCase()); - } - + @Override + protected boolean matches(String actual, String argument) { + return actual != null + && argument != null + && actual.toLowerCase().startsWith(argument.toLowerCase()); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Auditing.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Auditing.java index 01d09b0f..f67aa5d6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Auditing.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Auditing.java @@ -11,21 +11,20 @@ @SuppressWarnings("WeakerAccess") public interface Auditing extends End { - /** - * Enables auditing by using the provided auditor aware - * - * @param auditorAware the auditor aware providing auditor - * @return the rest of the configuration - */ - End enableAuditing(AuditorAware auditorAware); - - /** - * Enables auditing by setting the auditor to - * {@link com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilder.DefaultAuditorAware - * the default} value. - * - * @return the rest of the configuration - */ - End enableAuditing(); + /** + * Enables auditing by using the provided auditor aware + * + * @param auditorAware the auditor aware providing auditor + * @return the rest of the configuration + */ + End enableAuditing(AuditorAware auditorAware); + /** + * Enables auditing by setting the auditor to {@link + * com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilder.DefaultAuditorAware the + * default} value. + * + * @return the rest of the configuration + */ + End enableAuditing(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataFunctions.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataFunctions.java index b5f2c183..5062d3bb 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataFunctions.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataFunctions.java @@ -12,22 +12,21 @@ @SuppressWarnings("WeakerAccess") public interface DataFunctions extends DataStores { - /** - * Tells the builder which data function registry it should use - * - * @param registry the registry that should be used - * @return the rest of the configuration - */ - DataStores withDataFunctions(DataFunctionRegistry registry); - - /** - * Registers a function and lets you add more functions - * - * @param name the name under which this function is recognized - * @param function the function - * @param the type of the result - * @return the rest of the configuration - */ - DataFunctionsAnd registerFunction(String name, DataFunction function); + /** + * Tells the builder which data function registry it should use + * + * @param registry the registry that should be used + * @return the rest of the configuration + */ + DataStores withDataFunctions(DataFunctionRegistry registry); + /** + * Registers a function and lets you add more functions + * + * @param name the name under which this function is recognized + * @param function the function + * @param the type of the result + * @return the rest of the configuration + */ + DataFunctionsAnd registerFunction(String name, DataFunction function); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataFunctionsAnd.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataFunctionsAnd.java index 29b5c1c4..5b768760 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataFunctionsAnd.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataFunctionsAnd.java @@ -11,14 +11,13 @@ @SuppressWarnings("WeakerAccess") public interface DataFunctionsAnd extends DataStores { - /** - * adds an additional function - * - * @param name the name of the function - * @param function the function - * @param the type of the result - * @return the rest of the configuration - */ - DataFunctionsAnd and(String name, DataFunction function); - + /** + * adds an additional function + * + * @param name the name of the function + * @param function the function + * @param the type of the result + * @return the rest of the configuration + */ + DataFunctionsAnd and(String name, DataFunction function); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataStores.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataStores.java index a51d1be3..028922b9 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataStores.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataStores.java @@ -12,22 +12,21 @@ @SuppressWarnings("WeakerAccess") public interface DataStores extends ResultAdapters { - /** - * Tells the builder to use a different registry - * - * @param registry the registry - * @return the rest of the configuration - */ - ResultAdapters withDataStores(DataStoreRegistry registry); - - /** - * Registers a new data store - * - * @param dataStore the data store - * @param the entity type - * @param the key type - * @return the rest of the configuration - */ - DataStoresAnd registerDataStore(DataStore dataStore); + /** + * Tells the builder to use a different registry + * + * @param registry the registry + * @return the rest of the configuration + */ + ResultAdapters withDataStores(DataStoreRegistry registry); + /** + * Registers a new data store + * + * @param dataStore the data store + * @param the entity type + * @param the key type + * @return the rest of the configuration + */ + DataStoresAnd registerDataStore(DataStore dataStore); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataStoresAnd.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataStoresAnd.java index 64fc491a..34c3288e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataStoresAnd.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/DataStoresAnd.java @@ -11,14 +11,13 @@ @SuppressWarnings("WeakerAccess") public interface DataStoresAnd extends ResultAdapters { - /** - * Adds another data store - * - * @param dataStore the data store - * @param the type of the entity - * @param the type of the key - * @return the rest of the configuration - */ - DataStoresAnd and(DataStore dataStore); - + /** + * Adds another data store + * + * @param dataStore the data store + * @param the type of the entity + * @param the type of the key + * @return the rest of the configuration + */ + DataStoresAnd and(DataStore dataStore); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/End.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/End.java index 43643dff..d8a3df31 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/End.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/End.java @@ -5,9 +5,9 @@ import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration; /** - * Finalizes the DSL by providing a way to either choose to {@link #build() build} the factory or to {@link - * KeyGeneration continue} with the DSL and mock a repository instead, thus complementing the grammar for the repository - * factory build DSL with that of the repository mock builder. + * Finalizes the DSL by providing a way to either choose to {@link #build() build} the factory or to + * {@link KeyGeneration continue} with the DSL and mock a repository instead, thus complementing the + * grammar for the repository factory build DSL with that of the repository mock builder. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/14/15) @@ -15,16 +15,15 @@ @SuppressWarnings("WeakerAccess") public interface End extends KeyGeneration { - /** - * @return an instance of the repository factory as configured up to this point. - * @see Start for configuration options. - */ - RepositoryFactory build(); - - /** - * @return the {@link RepositoryFactoryConfiguration repository factory configuration} instance that has been - * created as a result of method calls via this DSL - */ - RepositoryFactoryConfiguration configure(); + /** + * @return an instance of the repository factory as configured up to this point. + * @see Start for configuration options. + */ + RepositoryFactory build(); + /** + * @return the {@link RepositoryFactoryConfiguration repository factory configuration} instance + * that has been created as a result of method calls via this DSL + */ + RepositoryFactoryConfiguration configure(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/EventListener.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/EventListener.java index b4b4a14a..c5d91b03 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/EventListener.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/EventListener.java @@ -13,21 +13,20 @@ @SuppressWarnings("WeakerAccess") public interface EventListener extends Auditing { - /** - * Tells the build to use this listener context - * - * @param context the context - * @return the rest of the configuration - */ - End withListeners(DataStoreEventListenerContext context); - - /** - * Tells the context to register this listener - * - * @param listener the listener - * @param the (super-)type of the events the listener is going to react to - * @return the rest of the configuration - */ - EventListenerAnd withListener(DataStoreEventListener listener); + /** + * Tells the build to use this listener context + * + * @param context the context + * @return the rest of the configuration + */ + End withListeners(DataStoreEventListenerContext context); + /** + * Tells the context to register this listener + * + * @param listener the listener + * @param the (super-)type of the events the listener is going to react to + * @return the rest of the configuration + */ + EventListenerAnd withListener(DataStoreEventListener listener); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/EventListenerAnd.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/EventListenerAnd.java index d1e729be..327f4ec2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/EventListenerAnd.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/EventListenerAnd.java @@ -12,13 +12,12 @@ @SuppressWarnings("WeakerAccess") public interface EventListenerAnd extends Auditing { - /** - * Registers an extra event listener - * - * @param listener the listener - * @param the type of the events the listener is subscribed to - * @return the rest of the configuration - */ - EventListenerAnd and(DataStoreEventListener listener); - + /** + * Registers an extra event listener + * + * @param listener the listener + * @param the type of the events the listener is subscribed to + * @return the rest of the configuration + */ + EventListenerAnd and(DataStoreEventListener listener); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/FallbackKeyGenerator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/FallbackKeyGenerator.java index 6f08d59c..317601f4 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/FallbackKeyGenerator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/FallbackKeyGenerator.java @@ -8,13 +8,12 @@ */ public interface FallbackKeyGenerator extends EventListener { - /** - * Sets up a default key generator that would be used as a fallback if no key generation scheme is specified for the - * repository - * - * @param keyGenerator the key generator to be used - * @return the rest of the configuration - */ - EventListener withDefaultKeyGenerator(KeyGenerator keyGenerator); - + /** + * Sets up a default key generator that would be used as a fallback if no key generation scheme is + * specified for the repository + * + * @param keyGenerator the key generator to be used + * @return the rest of the configuration + */ + EventListener withDefaultKeyGenerator(KeyGenerator keyGenerator); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MappingContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MappingContext.java index f2c9daf2..ec9f94f5 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MappingContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MappingContext.java @@ -11,21 +11,20 @@ @SuppressWarnings("WeakerAccess") public interface MappingContext extends OperationHandlers { - /** - * Tells the builder to use the provided context - * - * @param context the context - * @return the rest of the configuration - */ - EventListener withMappings(TypeMappingContext context); - - /** - * Tells the builder to register a mapping - * - * @param superType the super type for the repository interface - * @param implementation the concrete class implementing the mapped methods - * @return the rest of the configuration - */ - MappingContextAnd honoringImplementation(Class superType, Class implementation); + /** + * Tells the builder to use the provided context + * + * @param context the context + * @return the rest of the configuration + */ + EventListener withMappings(TypeMappingContext context); + /** + * Tells the builder to register a mapping + * + * @param superType the super type for the repository interface + * @param implementation the concrete class implementing the mapped methods + * @return the rest of the configuration + */ + MappingContextAnd honoringImplementation(Class superType, Class implementation); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MappingContextAnd.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MappingContextAnd.java index fcee2743..124896e6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MappingContextAnd.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MappingContextAnd.java @@ -9,13 +9,12 @@ @SuppressWarnings("WeakerAccess") public interface MappingContextAnd extends OperationHandlers { - /** - * Registers an additional mapping - * - * @param superType the super type for the interface - * @param implementation the concrete class providing mapped method implementations - * @return the rest of the configuration - */ - MappingContextAnd and(Class superType, Class implementation); - + /** + * Registers an additional mapping + * + * @param superType the super type for the interface + * @param implementation the concrete class providing mapped method implementations + * @return the rest of the configuration + */ + MappingContextAnd and(Class superType, Class implementation); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MetadataResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MetadataResolver.java index 6c22894a..d7c4621c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MetadataResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/MetadataResolver.java @@ -11,12 +11,11 @@ @SuppressWarnings("WeakerAccess") public interface MetadataResolver extends QueryDescriptionConfigurer { - /** - * Tells the builder to use the given repository metadata resolver instead of the default it has - * - * @param metadataResolver the resolver to use - * @return the rest of the configuration - */ - QueryDescriptionConfigurer resolveMetadataUsing(RepositoryMetadataResolver metadataResolver); - + /** + * Tells the builder to use the given repository metadata resolver instead of the default it has + * + * @param metadataResolver the resolver to use + * @return the rest of the configuration + */ + QueryDescriptionConfigurer resolveMetadataUsing(RepositoryMetadataResolver metadataResolver); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperationHandlers.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperationHandlers.java index d2b5a7db..889dfe81 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperationHandlers.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperationHandlers.java @@ -12,20 +12,19 @@ @SuppressWarnings("WeakerAccess") public interface OperationHandlers extends FallbackKeyGenerator { - /** - * Sets the invocation handler used for handling non-data-related operations - * - * @param invocationHandler the invocation handler - * @return the rest of the configuration - */ - FallbackKeyGenerator withOperationHandlers(NonDataOperationInvocationHandler invocationHandler); - - /** - * Registers an operation handler - * - * @param handler the handler - * @return the rest of the configuration - */ - OperationHandlersAnd withOperationHandler(NonDataOperationHandler handler); + /** + * Sets the invocation handler used for handling non-data-related operations + * + * @param invocationHandler the invocation handler + * @return the rest of the configuration + */ + FallbackKeyGenerator withOperationHandlers(NonDataOperationInvocationHandler invocationHandler); + /** + * Registers an operation handler + * + * @param handler the handler + * @return the rest of the configuration + */ + OperationHandlersAnd withOperationHandler(NonDataOperationHandler handler); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperationHandlersAnd.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperationHandlersAnd.java index 0ece502a..2f366f0e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperationHandlersAnd.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperationHandlersAnd.java @@ -11,12 +11,11 @@ @SuppressWarnings("WeakerAccess") public interface OperationHandlersAnd extends EventListener { - /** - * Registers an extra operation handler - * - * @param handler the handler - * @return the rest of the configuration - */ - OperationHandlersAnd and(NonDataOperationHandler handler); - + /** + * Registers an extra operation handler + * + * @param handler the handler + * @return the rest of the configuration + */ + OperationHandlersAnd and(NonDataOperationHandler handler); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Operators.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Operators.java index 82bafd6f..04f3b22e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Operators.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Operators.java @@ -12,20 +12,19 @@ @SuppressWarnings("WeakerAccess") public interface Operators extends DataFunctions { - /** - * Tells the builder to use the provided context instead of its own context - * - * @param context the context - * @return the rest of the configuration - */ - DataFunctions withOperators(OperatorContext context); - - /** - * Registers the given operator in the context used by the builder - * - * @param operator the operator - * @return the rest of the configuration - */ - OperatorsAnd registerOperator(Operator operator); + /** + * Tells the builder to use the provided context instead of its own context + * + * @param context the context + * @return the rest of the configuration + */ + DataFunctions withOperators(OperatorContext context); + /** + * Registers the given operator in the context used by the builder + * + * @param operator the operator + * @return the rest of the configuration + */ + OperatorsAnd registerOperator(Operator operator); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperatorsAnd.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperatorsAnd.java index 60e5cc7c..711553a5 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperatorsAnd.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/OperatorsAnd.java @@ -10,12 +10,11 @@ */ public interface OperatorsAnd extends DataFunctions { - /** - * Registers this operator as well - * - * @param operator the operator - * @return the rest of the configuration - */ - OperatorsAnd and(Operator operator); - + /** + * Registers this operator as well + * + * @param operator the operator + * @return the rest of the configuration + */ + OperatorsAnd and(Operator operator); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/QueryDescription.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/QueryDescription.java index 1bbf4b2b..aed4e8cf 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/QueryDescription.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/QueryDescription.java @@ -10,12 +10,11 @@ */ public interface QueryDescription extends DataFunctions { - /** - * Tells the builder to use the given query description extractor instead of the default - * - * @param extractor the extractor - * @return the rest of the configuration - */ - DataFunctions extractQueriesUsing(MethodQueryDescriptionExtractor extractor); - + /** + * Tells the builder to use the given query description extractor instead of the default + * + * @param extractor the extractor + * @return the rest of the configuration + */ + DataFunctions extractQueriesUsing(MethodQueryDescriptionExtractor extractor); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/QueryDescriptionConfigurer.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/QueryDescriptionConfigurer.java index 32ed5662..b63c0a4e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/QueryDescriptionConfigurer.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/QueryDescriptionConfigurer.java @@ -1,13 +1,11 @@ package com.mmnaseri.utils.spring.data.dsl.factory; /** - * This interface creates a branch in the grammar that lets you either configure the operators or the query description - * extractor. + * This interface creates a branch in the grammar that lets you either configure the operators or + * the query description extractor. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/14/15) */ @SuppressWarnings("WeakerAccess") -public interface QueryDescriptionConfigurer extends QueryDescription, Operators { - -} +public interface QueryDescriptionConfigurer extends QueryDescription, Operators {} diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilder.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilder.java index 19fb84ef..48af1d96 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilder.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilder.java @@ -10,12 +10,25 @@ import com.mmnaseri.utils.spring.data.dsl.mock.Implementation; import com.mmnaseri.utils.spring.data.dsl.mock.ImplementationAnd; import com.mmnaseri.utils.spring.data.dsl.mock.RepositoryMockBuilder; -import com.mmnaseri.utils.spring.data.proxy.*; -import com.mmnaseri.utils.spring.data.proxy.impl.*; +import com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler; +import com.mmnaseri.utils.spring.data.proxy.RepositoryFactory; +import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration; +import com.mmnaseri.utils.spring.data.proxy.ResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.ResultAdapterContext; +import com.mmnaseri.utils.spring.data.proxy.TypeMappingContext; +import com.mmnaseri.utils.spring.data.proxy.impl.DefaultRepositoryFactory; +import com.mmnaseri.utils.spring.data.proxy.impl.DefaultResultAdapterContext; +import com.mmnaseri.utils.spring.data.proxy.impl.DefaultTypeMappingContext; +import com.mmnaseri.utils.spring.data.proxy.impl.ImmutableRepositoryFactoryConfiguration; +import com.mmnaseri.utils.spring.data.proxy.impl.NonDataOperationInvocationHandler; import com.mmnaseri.utils.spring.data.query.DataFunction; import com.mmnaseri.utils.spring.data.query.DataFunctionRegistry; import com.mmnaseri.utils.spring.data.query.impl.DefaultDataFunctionRegistry; -import com.mmnaseri.utils.spring.data.store.*; +import com.mmnaseri.utils.spring.data.store.DataStore; +import com.mmnaseri.utils.spring.data.store.DataStoreEvent; +import com.mmnaseri.utils.spring.data.store.DataStoreEventListener; +import com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext; +import com.mmnaseri.utils.spring.data.store.DataStoreRegistry; import com.mmnaseri.utils.spring.data.store.impl.AuditDataEventListener; import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreEventListenerContext; import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreRegistry; @@ -32,303 +45,312 @@ */ @SuppressWarnings("WeakerAccess") public class RepositoryFactoryBuilder - implements Start, DataFunctionsAnd, DataStoresAnd, EventListenerAnd, MappingContextAnd, OperatorsAnd, - ResultAdaptersAnd, OperationHandlersAnd { - - public static final String DEFAULT_USER = "User"; - private RepositoryMetadataResolver metadataResolver; - private MethodQueryDescriptionExtractor queryDescriptionExtractor; - private DataFunctionRegistry functionRegistry; - private DataStoreRegistry dataStoreRegistry; - private ResultAdapterContext resultAdapterContext; - private TypeMappingContext typeMappingContext; - private DataStoreEventListenerContext eventListenerContext; - private NonDataOperationInvocationHandler operationInvocationHandler; - private KeyGenerator defaultKeyGenerator; - - /** - * @return the default configuration - */ - public static RepositoryFactoryConfiguration defaultConfiguration() { - final RepositoryFactoryBuilder builder = (RepositoryFactoryBuilder) builder(); - return new ImmutableRepositoryFactoryConfiguration( - builder.metadataResolver, - builder.queryDescriptionExtractor, - builder.functionRegistry, - builder.dataStoreRegistry, - builder.resultAdapterContext, - builder.typeMappingContext, - builder.eventListenerContext, - builder.operationInvocationHandler, - builder.defaultKeyGenerator); - } - - /** - * Starting point for writing code in the builder's DSL - * - * @return an instance of the builder - */ - public static Start builder() { - return new RepositoryFactoryBuilder(); - } - - /** - * Start the configuration DSL by considering the provided configuration as the default fallback - * - * @param configuration the fallback configuration - * @return an instance of the builder - */ - public static Start given(RepositoryFactoryConfiguration configuration) { - final RepositoryFactoryBuilder builder = new RepositoryFactoryBuilder(); - builder.metadataResolver = getOrDefault(configuration.getRepositoryMetadataResolver(), - builder.metadataResolver); - builder.queryDescriptionExtractor = getOrDefault(configuration.getDescriptionExtractor(), - builder.queryDescriptionExtractor); - builder.functionRegistry = getOrDefault(configuration.getFunctionRegistry(), builder.functionRegistry); - builder.dataStoreRegistry = getOrDefault(configuration.getDataStoreRegistry(), builder.dataStoreRegistry); - builder.resultAdapterContext = getOrDefault(configuration.getResultAdapterContext(), - builder.resultAdapterContext); - builder.typeMappingContext = getOrDefault(configuration.getTypeMappingContext(), builder.typeMappingContext); - builder.eventListenerContext = getOrDefault(configuration.getEventListenerContext(), - builder.eventListenerContext); - builder.operationInvocationHandler = getOrDefault(configuration.getOperationInvocationHandler(), - builder.operationInvocationHandler); - builder.defaultKeyGenerator = getOrDefault(configuration.getDefaultKeyGenerator(), builder.defaultKeyGenerator); - return builder; - } - - private static E getOrDefault(E value, E defaultValue) { - return value != null ? value : defaultValue; - } - - /** - * @return the default factory - */ - public static RepositoryFactory defaultFactory() { - return new DefaultRepositoryFactory(defaultConfiguration()); - } - - private RepositoryFactoryBuilder() { - metadataResolver = new DefaultRepositoryMetadataResolver(); - queryDescriptionExtractor = new MethodQueryDescriptionExtractor(new DefaultOperatorContext()); - functionRegistry = new DefaultDataFunctionRegistry(); - dataStoreRegistry = new DefaultDataStoreRegistry(); - resultAdapterContext = new DefaultResultAdapterContext(); - typeMappingContext = new DefaultTypeMappingContext(); - eventListenerContext = new DefaultDataStoreEventListenerContext(); - operationInvocationHandler = new NonDataOperationInvocationHandler(); - //by default, we do not want any key generator, unless one is specified - defaultKeyGenerator = null; - } - - @Override - public QueryDescriptionConfigurer resolveMetadataUsing(RepositoryMetadataResolver metadataResolver) { - this.metadataResolver = metadataResolver; - return this; - } - - @Override - public DataFunctions withOperators(OperatorContext context) { - queryDescriptionExtractor = new MethodQueryDescriptionExtractor(context); - return this; - } - - @Override - public OperatorsAnd registerOperator(Operator operator) { - queryDescriptionExtractor.getOperatorContext().register(operator); - return this; - } - - @Override - public DataFunctions extractQueriesUsing(MethodQueryDescriptionExtractor extractor) { - queryDescriptionExtractor = extractor; - return this; - } - - @Override - public DataStores withDataFunctions(DataFunctionRegistry registry) { - functionRegistry = registry; - return this; - } - - @Override - public DataFunctionsAnd registerFunction(String name, DataFunction function) { - functionRegistry.register(name, function); - return this; - } - - @Override - public ResultAdapters withDataStores(DataStoreRegistry registry) { - dataStoreRegistry = registry; - return this; - } - - @Override - public DataStoresAnd registerDataStore(DataStore dataStore) { - dataStoreRegistry.register(dataStore); - return this; - } - - @Override - public MappingContext withAdapters(ResultAdapterContext context) { - resultAdapterContext = context; - return this; - } - - @Override - public ResultAdaptersAnd adaptResultsUsing(ResultAdapter adapter) { - resultAdapterContext.register(adapter); - return this; - } - - @Override - public EventListener withMappings(TypeMappingContext context) { - typeMappingContext = context; - return this; - } - - @Override - public MappingContextAnd honoringImplementation(Class superType, Class implementation) { - typeMappingContext.register(superType, implementation); - return this; - } - - - @Override - public FallbackKeyGenerator withOperationHandlers(NonDataOperationInvocationHandler invocationHandler) { - operationInvocationHandler = invocationHandler; - return this; - } - - @Override - public OperationHandlersAnd withOperationHandler(NonDataOperationHandler handler) { - operationInvocationHandler.register(handler); - return this; - } - - @Override - public End withListeners(DataStoreEventListenerContext context) { - eventListenerContext = context; - return this; - } - - @Override - public EventListenerAnd withListener(DataStoreEventListener listener) { - eventListenerContext.register(listener); - return this; - } - - @Override - public EventListener enableAuditing(AuditorAware auditorAware) { - return (EventListener) and(new AuditDataEventListener(auditorAware)); - } - - @Override - public EventListener enableAuditing() { - return enableAuditing(new DefaultAuditorAware()); - } - - @Override - public DataFunctionsAnd and(String name, DataFunction function) { - functionRegistry.register(name, function); - return this; - } - - @Override - public DataStoresAnd and(DataStore dataStore) { - dataStoreRegistry.register(dataStore); - return this; - } - - @Override - public OperationHandlersAnd and(NonDataOperationHandler handler) { - operationInvocationHandler.register(handler); - return this; - } - - @Override - public EventListener withDefaultKeyGenerator(KeyGenerator keyGenerator) { - defaultKeyGenerator = keyGenerator; - return this; - } - - @Override - public EventListenerAnd and(DataStoreEventListener listener) { - eventListenerContext.register(listener); - return this; - } - - @Override - public MappingContextAnd and(Class superType, Class implementation) { - typeMappingContext.register(superType, implementation); - return this; - } - - @Override - public OperatorsAnd and(Operator operator) { - queryDescriptionExtractor.getOperatorContext().register(operator); - return this; - } - - @Override - public ResultAdaptersAnd and(ResultAdapter adapter) { - resultAdapterContext.register(adapter); - return this; - } - - @Override - public RepositoryFactory build() { - return new DefaultRepositoryFactory(configure()); - } - - @Override - public RepositoryFactoryConfiguration configure() { - return new ImmutableRepositoryFactoryConfiguration(metadataResolver, queryDescriptionExtractor, - functionRegistry, dataStoreRegistry, resultAdapterContext, - typeMappingContext, eventListenerContext, - operationInvocationHandler, defaultKeyGenerator); - } - - @Override - public Implementation generateKeysUsing(KeyGenerator keyGenerator) { - return new RepositoryMockBuilder().useFactory(build()).generateKeysUsing(keyGenerator); - } - - @Override - public > Implementation generateKeysUsing(Class generatorType) { - return new RepositoryMockBuilder().useFactory(build()).generateKeysUsing(generatorType); - } - - @Override - public Implementation withoutGeneratingKeys() { - return new RepositoryMockBuilder().useFactory(build()).withoutGeneratingKeys(); - } - - @Override - public ImplementationAnd usingImplementation(Class implementation) { - return new RepositoryMockBuilder().useFactory(build()).usingImplementation(implementation); - } - - @Override - public E mock(Class repositoryInterface) { - return new RepositoryMockBuilder().useFactory(build()).mock(repositoryInterface); - } - - /** - * An auditor aware that returns the static value of {@link #DEFAULT_USER} - */ - @SuppressWarnings("WeakerAccess") - public static class DefaultAuditorAware implements AuditorAware { - - /** - * @return {@link #DEFAULT_USER} - */ - @Override - @Nonnull - public Optional getCurrentAuditor() { - return Optional.of(DEFAULT_USER); - } - - } - + implements Start, + DataFunctionsAnd, + DataStoresAnd, + EventListenerAnd, + MappingContextAnd, + OperatorsAnd, + ResultAdaptersAnd, + OperationHandlersAnd { + + public static final String DEFAULT_USER = "User"; + private RepositoryMetadataResolver metadataResolver; + private MethodQueryDescriptionExtractor queryDescriptionExtractor; + private DataFunctionRegistry functionRegistry; + private DataStoreRegistry dataStoreRegistry; + private ResultAdapterContext resultAdapterContext; + private TypeMappingContext typeMappingContext; + private DataStoreEventListenerContext eventListenerContext; + private NonDataOperationInvocationHandler operationInvocationHandler; + private KeyGenerator defaultKeyGenerator; + + private RepositoryFactoryBuilder() { + metadataResolver = new DefaultRepositoryMetadataResolver(); + queryDescriptionExtractor = new MethodQueryDescriptionExtractor(new DefaultOperatorContext()); + functionRegistry = new DefaultDataFunctionRegistry(); + dataStoreRegistry = new DefaultDataStoreRegistry(); + resultAdapterContext = new DefaultResultAdapterContext(); + typeMappingContext = new DefaultTypeMappingContext(); + eventListenerContext = new DefaultDataStoreEventListenerContext(); + operationInvocationHandler = new NonDataOperationInvocationHandler(); + // by default, we do not want any key generator, unless one is specified + defaultKeyGenerator = null; + } + + @Override + public QueryDescriptionConfigurer resolveMetadataUsing( + RepositoryMetadataResolver metadataResolver) { + this.metadataResolver = metadataResolver; + return this; + } + + @Override + public DataFunctions withOperators(OperatorContext context) { + queryDescriptionExtractor = new MethodQueryDescriptionExtractor(context); + return this; + } + + @Override + public OperatorsAnd registerOperator(Operator operator) { + queryDescriptionExtractor.getOperatorContext().register(operator); + return this; + } + + @Override + public DataFunctions extractQueriesUsing(MethodQueryDescriptionExtractor extractor) { + queryDescriptionExtractor = extractor; + return this; + } + + @Override + public DataStores withDataFunctions(DataFunctionRegistry registry) { + functionRegistry = registry; + return this; + } + + @Override + public DataFunctionsAnd registerFunction(String name, DataFunction function) { + functionRegistry.register(name, function); + return this; + } + + @Override + public ResultAdapters withDataStores(DataStoreRegistry registry) { + dataStoreRegistry = registry; + return this; + } + + @Override + public DataStoresAnd registerDataStore(DataStore dataStore) { + dataStoreRegistry.register(dataStore); + return this; + } + + @Override + public MappingContext withAdapters(ResultAdapterContext context) { + resultAdapterContext = context; + return this; + } + + @Override + public ResultAdaptersAnd adaptResultsUsing(ResultAdapter adapter) { + resultAdapterContext.register(adapter); + return this; + } + + @Override + public EventListener withMappings(TypeMappingContext context) { + typeMappingContext = context; + return this; + } + + @Override + public MappingContextAnd honoringImplementation(Class superType, Class implementation) { + typeMappingContext.register(superType, implementation); + return this; + } + + @Override + public FallbackKeyGenerator withOperationHandlers( + NonDataOperationInvocationHandler invocationHandler) { + operationInvocationHandler = invocationHandler; + return this; + } + + @Override + public OperationHandlersAnd withOperationHandler(NonDataOperationHandler handler) { + operationInvocationHandler.register(handler); + return this; + } + + @Override + public End withListeners(DataStoreEventListenerContext context) { + eventListenerContext = context; + return this; + } + + @Override + public EventListenerAnd withListener( + DataStoreEventListener listener) { + eventListenerContext.register(listener); + return this; + } + + @Override + public EventListener enableAuditing(AuditorAware auditorAware) { + return (EventListener) and(new AuditDataEventListener(auditorAware)); + } + + @Override + public EventListener enableAuditing() { + return enableAuditing(new DefaultAuditorAware()); + } + + @Override + public DataFunctionsAnd and(String name, DataFunction function) { + functionRegistry.register(name, function); + return this; + } + + @Override + public DataStoresAnd and(DataStore dataStore) { + dataStoreRegistry.register(dataStore); + return this; + } + + @Override + public OperationHandlersAnd and(NonDataOperationHandler handler) { + operationInvocationHandler.register(handler); + return this; + } + + @Override + public EventListener withDefaultKeyGenerator(KeyGenerator keyGenerator) { + defaultKeyGenerator = keyGenerator; + return this; + } + + @Override + public EventListenerAnd and(DataStoreEventListener listener) { + eventListenerContext.register(listener); + return this; + } + + @Override + public MappingContextAnd and(Class superType, Class implementation) { + typeMappingContext.register(superType, implementation); + return this; + } + + @Override + public OperatorsAnd and(Operator operator) { + queryDescriptionExtractor.getOperatorContext().register(operator); + return this; + } + + @Override + public ResultAdaptersAnd and(ResultAdapter adapter) { + resultAdapterContext.register(adapter); + return this; + } + + @Override + public RepositoryFactory build() { + return new DefaultRepositoryFactory(configure()); + } + + @Override + public RepositoryFactoryConfiguration configure() { + return new ImmutableRepositoryFactoryConfiguration( + metadataResolver, + queryDescriptionExtractor, + functionRegistry, + dataStoreRegistry, + resultAdapterContext, + typeMappingContext, + eventListenerContext, + operationInvocationHandler, + defaultKeyGenerator); + } + + @Override + public Implementation generateKeysUsing(KeyGenerator keyGenerator) { + return new RepositoryMockBuilder().useFactory(build()).generateKeysUsing(keyGenerator); + } + + @Override + public > Implementation generateKeysUsing(Class generatorType) { + return new RepositoryMockBuilder().useFactory(build()).generateKeysUsing(generatorType); + } + + @Override + public Implementation withoutGeneratingKeys() { + return new RepositoryMockBuilder().useFactory(build()).withoutGeneratingKeys(); + } + + @Override + public ImplementationAnd usingImplementation(Class implementation) { + return new RepositoryMockBuilder().useFactory(build()).usingImplementation(implementation); + } + + @Override + public E mock(Class repositoryInterface) { + return new RepositoryMockBuilder().useFactory(build()).mock(repositoryInterface); + } + + /** @return the default configuration */ + public static RepositoryFactoryConfiguration defaultConfiguration() { + final RepositoryFactoryBuilder builder = (RepositoryFactoryBuilder) builder(); + return new ImmutableRepositoryFactoryConfiguration( + builder.metadataResolver, + builder.queryDescriptionExtractor, + builder.functionRegistry, + builder.dataStoreRegistry, + builder.resultAdapterContext, + builder.typeMappingContext, + builder.eventListenerContext, + builder.operationInvocationHandler, + builder.defaultKeyGenerator); + } + + /** + * Starting point for writing code in the builder's DSL + * + * @return an instance of the builder + */ + public static Start builder() { + return new RepositoryFactoryBuilder(); + } + + /** + * Start the configuration DSL by considering the provided configuration as the default fallback + * + * @param configuration the fallback configuration + * @return an instance of the builder + */ + public static Start given(RepositoryFactoryConfiguration configuration) { + final RepositoryFactoryBuilder builder = new RepositoryFactoryBuilder(); + builder.metadataResolver = + getOrDefault(configuration.getRepositoryMetadataResolver(), builder.metadataResolver); + builder.queryDescriptionExtractor = + getOrDefault(configuration.getDescriptionExtractor(), builder.queryDescriptionExtractor); + builder.functionRegistry = + getOrDefault(configuration.getFunctionRegistry(), builder.functionRegistry); + builder.dataStoreRegistry = + getOrDefault(configuration.getDataStoreRegistry(), builder.dataStoreRegistry); + builder.resultAdapterContext = + getOrDefault(configuration.getResultAdapterContext(), builder.resultAdapterContext); + builder.typeMappingContext = + getOrDefault(configuration.getTypeMappingContext(), builder.typeMappingContext); + builder.eventListenerContext = + getOrDefault(configuration.getEventListenerContext(), builder.eventListenerContext); + builder.operationInvocationHandler = + getOrDefault( + configuration.getOperationInvocationHandler(), builder.operationInvocationHandler); + builder.defaultKeyGenerator = + getOrDefault(configuration.getDefaultKeyGenerator(), builder.defaultKeyGenerator); + return builder; + } + + private static E getOrDefault(E value, E defaultValue) { + return value != null ? value : defaultValue; + } + + /** @return the default factory */ + public static RepositoryFactory defaultFactory() { + return new DefaultRepositoryFactory(defaultConfiguration()); + } + + /** An auditor aware that returns the static value of {@link #DEFAULT_USER} */ + @SuppressWarnings("WeakerAccess") + public static class DefaultAuditorAware implements AuditorAware { + + /** @return {@link #DEFAULT_USER} */ + @Override + @Nonnull + public Optional getCurrentAuditor() { + return Optional.of(DEFAULT_USER); + } + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/ResultAdapters.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/ResultAdapters.java index 1241f097..6dbcbc91 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/ResultAdapters.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/ResultAdapters.java @@ -10,21 +10,20 @@ @SuppressWarnings("WeakerAccess") public interface ResultAdapters extends MappingContext { - /** - * Tells the builder to use the provided context - * - * @param context the context - * @return the rest of the configuration - */ - MappingContext withAdapters(ResultAdapterContext context); - - /** - * Tells the build to register a result adapter - * - * @param adapter the adapter - * @param the type of the result for the adapter - * @return the rest of the configuration - */ - ResultAdaptersAnd adaptResultsUsing(ResultAdapter adapter); + /** + * Tells the builder to use the provided context + * + * @param context the context + * @return the rest of the configuration + */ + MappingContext withAdapters(ResultAdapterContext context); + /** + * Tells the build to register a result adapter + * + * @param adapter the adapter + * @param the type of the result for the adapter + * @return the rest of the configuration + */ + ResultAdaptersAnd adaptResultsUsing(ResultAdapter adapter); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/ResultAdaptersAnd.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/ResultAdaptersAnd.java index 2edfcf5c..79156e3b 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/ResultAdaptersAnd.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/ResultAdaptersAnd.java @@ -10,13 +10,12 @@ */ public interface ResultAdaptersAnd extends MappingContext { - /** - * Registers an extra adapter - * - * @param adapter the adapter - * @param the type of the result for the adapter - * @return the rest of the configuration - */ - ResultAdaptersAnd and(ResultAdapter adapter); - + /** + * Registers an extra adapter + * + * @param adapter the adapter + * @param the type of the result for the adapter + * @return the rest of the configuration + */ + ResultAdaptersAnd and(ResultAdapter adapter); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Start.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Start.java index 93639daa..c3af82bd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Start.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/factory/Start.java @@ -1,13 +1,11 @@ package com.mmnaseri.utils.spring.data.dsl.factory; /** - * This interface is used as the starting point of the DSL grammar for creating a repository factory and later mocking - * objects through that repository. + * This interface is used as the starting point of the DSL grammar for creating a repository factory + * and later mocking objects through that repository. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/14/15) */ @SuppressWarnings("WeakerAccess") -public interface Start extends MetadataResolver { - -} +public interface Start extends MetadataResolver {} diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Configuration.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Configuration.java index 8fc0cf1a..e216cb00 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Configuration.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Configuration.java @@ -11,12 +11,11 @@ @SuppressWarnings("WeakerAccess") public interface Configuration { - /** - * Tells the builder to use the given configuration - * - * @param configuration the configuration - * @return the rest of the configuration - */ - KeyGeneration useConfiguration(RepositoryFactoryConfiguration configuration); - + /** + * Tells the builder to use the given configuration + * + * @param configuration the configuration + * @return the rest of the configuration + */ + KeyGeneration useConfiguration(RepositoryFactoryConfiguration configuration); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/End.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/End.java index 645b9a69..21b8b396 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/End.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/End.java @@ -9,14 +9,13 @@ @SuppressWarnings("WeakerAccess") public interface End { - /** - * Tells the builder that it is now time to mock the given repository interface using the configuration provided - * thus far. - * - * @param repositoryInterface the repository interface to mock - * @param the type of the repository - * @return the mocked instance - */ - E mock(Class repositoryInterface); - + /** + * Tells the builder that it is now time to mock the given repository interface using the + * configuration provided thus far. + * + * @param repositoryInterface the repository interface to mock + * @param the type of the repository + * @return the mocked instance + */ + E mock(Class repositoryInterface); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Factory.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Factory.java index f5240586..a47e67b2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Factory.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Factory.java @@ -11,12 +11,11 @@ @SuppressWarnings({"WeakerAccess", "unused"}) public interface Factory { - /** - * Tells the builder to use the specified factory - * - * @param factory the factory - * @return the rest of the configuration - */ - KeyGeneration useFactory(RepositoryFactory factory); - + /** + * Tells the builder to use the specified factory + * + * @param factory the factory + * @return the rest of the configuration + */ + KeyGeneration useFactory(RepositoryFactory factory); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Implementation.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Implementation.java index 45d1ea45..f16feecd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Implementation.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Implementation.java @@ -8,12 +8,11 @@ */ public interface Implementation extends End { - /** - * Tells the builder to use the given implementation - * - * @param implementation the implementation - * @return the rest of the configuration - */ - ImplementationAnd usingImplementation(Class implementation); - + /** + * Tells the builder to use the given implementation + * + * @param implementation the implementation + * @return the rest of the configuration + */ + ImplementationAnd usingImplementation(Class implementation); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/ImplementationAnd.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/ImplementationAnd.java index f43df0ff..0e61b293 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/ImplementationAnd.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/ImplementationAnd.java @@ -8,12 +8,11 @@ */ public interface ImplementationAnd extends End { - /** - * Tells the builder to use this additional implementation - * - * @param implementation the implementation - * @return the rest of the configuration - */ - ImplementationAnd and(Class implementation); - + /** + * Tells the builder to use this additional implementation + * + * @param implementation the implementation + * @return the rest of the configuration + */ + ImplementationAnd and(Class implementation); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneration.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneration.java index 1c10fbf8..979904a8 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneration.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneration.java @@ -10,30 +10,29 @@ */ public interface KeyGeneration extends Implementation { - /** - * Sets the key generator to the provided instance - * - * @param keyGenerator the key generator - * @param the type of the keys - * @return the rest of the configuration - */ - Implementation generateKeysUsing(KeyGenerator keyGenerator); + /** + * Sets the key generator to the provided instance + * + * @param keyGenerator the key generator + * @param the type of the keys + * @return the rest of the configuration + */ + Implementation generateKeysUsing(KeyGenerator keyGenerator); - /** - * Sets the key generator to an instance of the provided type. - * - * @param generatorType the type of the key generator to use - * @param the type of the keys the generator will be generating - * @param the type of the generator - * @return the rest of the configuration - */ - > Implementation generateKeysUsing(Class generatorType); - - /** - * Tells the builder that we are not going to have any auto-generated keys - * - * @return the rest of the configuration - */ - Implementation withoutGeneratingKeys(); + /** + * Sets the key generator to an instance of the provided type. + * + * @param generatorType the type of the key generator to use + * @param the type of the keys the generator will be generating + * @param the type of the generator + * @return the rest of the configuration + */ + > Implementation generateKeysUsing(Class generatorType); + /** + * Tells the builder that we are not going to have any auto-generated keys + * + * @return the rest of the configuration + */ + Implementation withoutGeneratingKeys(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneratorProvider.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneratorProvider.java index ee511f53..7ac153da 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneratorProvider.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/KeyGeneratorProvider.java @@ -1,17 +1,28 @@ package com.mmnaseri.utils.spring.data.dsl.mock; import com.mmnaseri.utils.spring.data.domain.KeyGenerator; -import com.mmnaseri.utils.spring.data.domain.impl.key.*; +import com.mmnaseri.utils.spring.data.domain.impl.key.BsonObjectIdKeyGenerator; +import com.mmnaseri.utils.spring.data.domain.impl.key.ConfigurableSequentialIntegerKeyGenerator; +import com.mmnaseri.utils.spring.data.domain.impl.key.ConfigurableSequentialLongKeyGenerator; +import com.mmnaseri.utils.spring.data.domain.impl.key.RandomIntegerKeyGenerator; +import com.mmnaseri.utils.spring.data.domain.impl.key.RandomLongKeyGenerator; +import com.mmnaseri.utils.spring.data.domain.impl.key.SequentialIntegerKeyGenerator; +import com.mmnaseri.utils.spring.data.domain.impl.key.SequentialLongKeyGenerator; +import com.mmnaseri.utils.spring.data.domain.impl.key.UUIDKeyGenerator; import org.springframework.core.GenericTypeResolver; import org.springframework.util.ClassUtils; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** - * This class will provide a key generator for the requested key type, based on the preset list of available key - * generators. + * This class will provide a key generator for the requested key type, based on the preset list of + * available key generators. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/12/15) @@ -19,24 +30,27 @@ @SuppressWarnings("WeakerAccess") class KeyGeneratorProvider { - private static final String OBJECT_ID_CLASS = "org.bson.types.ObjectId"; - private final Map, List>> generators; + private static final String OBJECT_ID_CLASS = "org.bson.types.ObjectId"; + private final Map, List>> generators; - KeyGeneratorProvider() { - final List> discoveredKeyGenerators = getKeyGeneratorTypes(); - generators = new ConcurrentHashMap<>(); - for (Class generatorType : discoveredKeyGenerators) { - final Class keyType = GenericTypeResolver.resolveTypeArgument(generatorType, KeyGenerator.class); - assert keyType != null; - if (!generators.containsKey(keyType)) { - generators.put(keyType, new CopyOnWriteArrayList<>()); - } - generators.get(keyType).add(generatorType); - } + KeyGeneratorProvider() { + final List> discoveredKeyGenerators = getKeyGeneratorTypes(); + generators = new ConcurrentHashMap<>(); + for (Class generatorType : discoveredKeyGenerators) { + final Class keyType = + GenericTypeResolver.resolveTypeArgument(generatorType, KeyGenerator.class); + assert keyType != null; + if (!generators.containsKey(keyType)) { + generators.put(keyType, new CopyOnWriteArrayList<>()); + } + generators.get(keyType).add(generatorType); } + } - private List> getKeyGeneratorTypes() { - final List> classes = new ArrayList<>(Arrays.asList( + private List> getKeyGeneratorTypes() { + final List> classes = + new ArrayList<>( + Arrays.asList( RandomIntegerKeyGenerator.class, RandomLongKeyGenerator.class, SequentialIntegerKeyGenerator.class, @@ -44,44 +58,44 @@ private List> getKeyGeneratorTypes() { ConfigurableSequentialIntegerKeyGenerator.class, ConfigurableSequentialLongKeyGenerator.class, UUIDKeyGenerator.class)); - if (ClassUtils.isPresent(OBJECT_ID_CLASS, ClassUtils.getDefaultClassLoader())) { - classes.add(BsonObjectIdKeyGenerator.class); - } - return classes; + if (ClassUtils.isPresent(OBJECT_ID_CLASS, ClassUtils.getDefaultClassLoader())) { + classes.add(BsonObjectIdKeyGenerator.class); } + return classes; + } - private List>> getKeyGenerators(Class keyType) { - final LinkedList>> keyGenerators = new LinkedList<>(); - if (generators.containsKey(keyType)) { - addKeyGenerators(keyGenerators, keyType); - } - for (Class generatorKeyType : generators.keySet()) { - if (keyType.isAssignableFrom(generatorKeyType)) { - addKeyGenerators(keyGenerators, generatorKeyType); - } - } - return keyGenerators; + private List>> getKeyGenerators(Class keyType) { + final LinkedList>> keyGenerators = new LinkedList<>(); + if (generators.containsKey(keyType)) { + addKeyGenerators(keyGenerators, keyType); } - - private void addKeyGenerators(final LinkedList>> keyGenerators, - final Class generatorKeyType) { - final List> classes = generators.get(generatorKeyType); - for (Class type : classes) { - keyGenerators.add((Class>) type); - } + for (Class generatorKeyType : generators.keySet()) { + if (keyType.isAssignableFrom(generatorKeyType)) { + addKeyGenerators(keyGenerators, generatorKeyType); + } } + return keyGenerators; + } - /** - * Provides a key generator for the specified key type. This is to automate the process of getting a key generator, - * when no alternative is provided by the user. - * - * @param keyType the type of keys for which a generator is required - * @param the type of keys the generator will provide - * @return the generator or {@literal null} if none could be found to satisfy the key type - */ - public Class> getKeyGenerator(Class keyType) { - final List>> generators = getKeyGenerators(keyType); - return generators.isEmpty() ? null : generators.get(0); + private void addKeyGenerators( + final LinkedList>> keyGenerators, + final Class generatorKeyType) { + final List> classes = generators.get(generatorKeyType); + for (Class type : classes) { + keyGenerators.add((Class>) type); } + } + /** + * Provides a key generator for the specified key type. This is to automate the process of getting + * a key generator, when no alternative is provided by the user. + * + * @param keyType the type of keys for which a generator is required + * @param the type of keys the generator will provide + * @return the generator or {@literal null} if none could be found to satisfy the key type + */ + public Class> getKeyGenerator(Class keyType) { + final List>> generators = getKeyGenerators(keyType); + return generators.isEmpty() ? null : generators.get(0); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilder.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilder.java index 0e9f3b7c..15a885c3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilder.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilder.java @@ -20,97 +20,98 @@ */ public class RepositoryMockBuilder implements Start, ImplementationAnd, KeyGeneration { - private final RepositoryFactory factory; - private final List> implementations; - private final KeyGenerator keyGenerator; - - public RepositoryMockBuilder() { - this(null, new LinkedList<>(), null); - } - - private RepositoryMockBuilder(RepositoryFactory factory, List> implementations, - KeyGenerator keyGenerator) { - this.factory = factory; - this.implementations = implementations; - this.keyGenerator = keyGenerator; - } - - @Override - public KeyGeneration useConfiguration(RepositoryFactoryConfiguration configuration) { - return new RepositoryMockBuilder(new DefaultRepositoryFactory(configuration), implementations, keyGenerator); - } - - @Override - public KeyGeneration useFactory(RepositoryFactory factory) { - return new RepositoryMockBuilder(factory, implementations, keyGenerator); - } - - @Override - public ImplementationAnd usingImplementation(Class implementation) { - final LinkedList> implementations = new LinkedList<>(this.implementations); - implementations.add(implementation); - return new RepositoryMockBuilder(factory, implementations, keyGenerator); - } - - @Override - public ImplementationAnd and(Class implementation) { - return usingImplementation(implementation); - } - - @Override - public Implementation generateKeysUsing(KeyGenerator keyGenerator) { - return new RepositoryMockBuilder(factory, implementations, keyGenerator); - } - - @Override - public > Implementation generateKeysUsing(Class generatorType) { - //noinspection unchecked - final G instance = (G) createKeyGenerator(generatorType); - return generateKeysUsing(instance); + private final RepositoryFactory factory; + private final List> implementations; + private final KeyGenerator keyGenerator; + + public RepositoryMockBuilder() { + this(null, new LinkedList<>(), null); + } + + private RepositoryMockBuilder( + RepositoryFactory factory, List> implementations, KeyGenerator keyGenerator) { + this.factory = factory; + this.implementations = implementations; + this.keyGenerator = keyGenerator; + } + + @Override + public KeyGeneration useConfiguration(RepositoryFactoryConfiguration configuration) { + return new RepositoryMockBuilder( + new DefaultRepositoryFactory(configuration), implementations, keyGenerator); + } + + @Override + public KeyGeneration useFactory(RepositoryFactory factory) { + return new RepositoryMockBuilder(factory, implementations, keyGenerator); + } + + @Override + public ImplementationAnd usingImplementation(Class implementation) { + final LinkedList> implementations = new LinkedList<>(this.implementations); + implementations.add(implementation); + return new RepositoryMockBuilder(factory, implementations, keyGenerator); + } + + @Override + public ImplementationAnd and(Class implementation) { + return usingImplementation(implementation); + } + + @Override + public Implementation generateKeysUsing(KeyGenerator keyGenerator) { + return new RepositoryMockBuilder(factory, implementations, keyGenerator); + } + + @Override + public > Implementation generateKeysUsing(Class generatorType) { + //noinspection unchecked + final G instance = (G) createKeyGenerator(generatorType); + return generateKeysUsing(instance); + } + + @Override + public Implementation withoutGeneratingKeys() { + return new RepositoryMockBuilder(factory, implementations, new NoOpKeyGenerator<>()); + } + + private KeyGenerator createKeyGenerator(Class generatorType) { + final KeyGenerator instance; + try { + instance = generatorType.getDeclaredConstructor().newInstance(); + } catch (Exception e) { + throw new MockBuilderException( + "Failed to instantiate key generator of type " + generatorType, e); } - - @Override - public Implementation withoutGeneratingKeys() { - return new RepositoryMockBuilder(factory, implementations, new NoOpKeyGenerator<>()); + return instance; + } + + @Override + public E mock(Class repositoryInterface) { + final RepositoryFactory repositoryFactory; + if (factory == null) { + repositoryFactory = RepositoryFactoryBuilder.defaultFactory(); + } else { + repositoryFactory = this.factory; } - - private KeyGenerator createKeyGenerator(Class generatorType) { - final KeyGenerator instance; - try { - instance = generatorType.getDeclaredConstructor().newInstance(); - } catch (Exception e) { - throw new MockBuilderException("Failed to instantiate key generator of type " + generatorType, e); - } - return instance; + if (keyGenerator == null) { + final RepositoryFactoryConfiguration configuration = repositoryFactory.getConfiguration(); + final KeyGenerator evaluatedKeyGenerator; + if (configuration.getDefaultKeyGenerator() != null) { + evaluatedKeyGenerator = configuration.getDefaultKeyGenerator(); + } else { + final KeyGeneratorProvider generatorProvider = new KeyGeneratorProvider(); + final RepositoryMetadata metadata = + configuration.getRepositoryMetadataResolver().resolve(repositoryInterface); + final Class identifierType = metadata.getIdentifierType(); + final Class> keyGeneratorType = + generatorProvider.getKeyGenerator(identifierType); + evaluatedKeyGenerator = createKeyGenerator(keyGeneratorType); + } + return generateKeysUsing(evaluatedKeyGenerator).mock(repositoryInterface); + } else { + return repositoryFactory.getInstance( + keyGenerator, repositoryInterface, implementations.toArray(new Class[0])); } - - @Override - public E mock(Class repositoryInterface) { - final RepositoryFactory repositoryFactory; - if (factory == null) { - repositoryFactory = RepositoryFactoryBuilder.defaultFactory(); - } else { - repositoryFactory = this.factory; - } - if (keyGenerator == null) { - final RepositoryFactoryConfiguration configuration = repositoryFactory.getConfiguration(); - final KeyGenerator evaluatedKeyGenerator; - if (configuration.getDefaultKeyGenerator() != null) { - evaluatedKeyGenerator = configuration.getDefaultKeyGenerator(); - } else { - final KeyGeneratorProvider generatorProvider = new KeyGeneratorProvider(); - final RepositoryMetadata metadata = configuration.getRepositoryMetadataResolver().resolve( - repositoryInterface); - final Class identifierType = metadata.getIdentifierType(); - final Class> keyGeneratorType = generatorProvider.getKeyGenerator( - identifierType); - evaluatedKeyGenerator = createKeyGenerator(keyGeneratorType); - } - return generateKeysUsing(evaluatedKeyGenerator).mock(repositoryInterface); - } else { - return repositoryFactory.getInstance(keyGenerator, repositoryInterface, - implementations.toArray(new Class[0])); - } - } - + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Start.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Start.java index 94c0cf8d..1c5818cd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Start.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/dsl/mock/Start.java @@ -7,6 +7,4 @@ * @since 1.0 (10/14/15) */ @SuppressWarnings("WeakerAccess") -public interface Start extends Factory, Configuration { - -} +public interface Start extends Factory, Configuration {} diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/CorruptDataException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/CorruptDataException.java index 7ebe4276..84985056 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/CorruptDataException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/CorruptDataException.java @@ -6,8 +6,7 @@ */ public class CorruptDataException extends DataStoreException { - public CorruptDataException(Class entityType, Object data, String corruption) { - super(entityType, entityType + ": Data <" + data + "> is unacceptable. " + corruption); - } - + public CorruptDataException(Class entityType, Object data, String corruption) { + super(entityType, entityType + ": Data <" + data + "> is unacceptable. " + corruption); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataFunctionException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataFunctionException.java index 0a007abe..c53d8da3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataFunctionException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataFunctionException.java @@ -6,11 +6,11 @@ */ public class DataFunctionException extends DataOperationException { - public DataFunctionException(String message) { - super(message); - } + public DataFunctionException(String message) { + super(message); + } - public DataFunctionException(String message, Throwable cause) { - super(message, cause); - } + public DataFunctionException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationDefinitionException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationDefinitionException.java index a22872d8..c7da66d9 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationDefinitionException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationDefinitionException.java @@ -8,8 +8,7 @@ */ public class DataOperationDefinitionException extends DataOperationException { - public DataOperationDefinitionException(Method method, Throwable cause) { - super("Encountered an error while resolving operation metadata: " + method, cause); - } - + public DataOperationDefinitionException(Method method, Throwable cause) { + super("Encountered an error while resolving operation metadata: " + method, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationException.java index 318dbbef..060503e3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationException.java @@ -6,12 +6,11 @@ */ public abstract class DataOperationException extends RepositoryMockException { - public DataOperationException(String message) { - super(message); - } - - public DataOperationException(String message, Throwable cause) { - super(message, cause); - } + public DataOperationException(String message) { + super(message); + } + public DataOperationException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationExecutionException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationExecutionException.java index e77613de..a513f80d 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationExecutionException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataOperationExecutionException.java @@ -6,8 +6,7 @@ */ public class DataOperationExecutionException extends DataOperationException { - public DataOperationExecutionException(String message, Throwable cause) { - super(message, cause); - } - + public DataOperationExecutionException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreException.java index 33c66f6d..01d8f394 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreException.java @@ -6,8 +6,7 @@ */ public class DataStoreException extends RepositoryMockException { - public DataStoreException(Class entityType, String message) { - super(entityType + ": " + message); - } - + public DataStoreException(Class entityType, String message) { + super(entityType + ": " + message); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreNotFoundException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreNotFoundException.java index afff1fa9..d091d611 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreNotFoundException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DataStoreNotFoundException.java @@ -6,8 +6,7 @@ */ public class DataStoreNotFoundException extends DataStoreException { - public DataStoreNotFoundException(Class entityType) { - super(entityType, "No data store could be found for this entity type: " + entityType); - } - + public DataStoreNotFoundException(Class entityType) { + super(entityType, "No data store could be found for this entity type: " + entityType); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateFunctionException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateFunctionException.java index 541acbd0..b21a3931 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateFunctionException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateFunctionException.java @@ -6,8 +6,7 @@ */ public class DuplicateFunctionException extends FunctionRegistryException { - public DuplicateFunctionException(String name) { - super("Another function with this name has already been registered: " + name); - } - + public DuplicateFunctionException(String name) { + super("Another function with this name has already been registered: " + name); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateOperatorException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateOperatorException.java index 926c0611..4fe87cca 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateOperatorException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/DuplicateOperatorException.java @@ -8,8 +8,11 @@ */ public class DuplicateOperatorException extends OperatorContextException { - public DuplicateOperatorException(Operator existing, String token) { - super("Another operator (" + existing.getName() + ") already defines answers to this token: " + token); - } - + public DuplicateOperatorException(Operator existing, String token) { + super( + "Another operator (" + + existing.getName() + + ") already defines answers to this token: " + + token); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityDefinitionException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityDefinitionException.java index dd719be9..722622a9 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityDefinitionException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityDefinitionException.java @@ -6,8 +6,7 @@ */ public abstract class EntityDefinitionException extends RepositoryMockException { - public EntityDefinitionException(String message) { - super(message); - } - + public EntityDefinitionException(String message) { + super(message); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityMissingKeyException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityMissingKeyException.java index 2a804b6a..e5787262 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityMissingKeyException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityMissingKeyException.java @@ -6,8 +6,11 @@ */ public class EntityMissingKeyException extends EntityStateException { - public EntityMissingKeyException(Class entityType, String keyProperty) { - super("An object of instance " + entityType + " must declare a valid key under property " + keyProperty); - } - + public EntityMissingKeyException(Class entityType, String keyProperty) { + super( + "An object of instance " + + entityType + + " must declare a valid key under property " + + keyProperty); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityStateException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityStateException.java index 7e993c2f..cc2a0fa1 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityStateException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/EntityStateException.java @@ -6,8 +6,7 @@ */ public abstract class EntityStateException extends RepositoryMockException { - public EntityStateException(String message) { - super(message); - } - + public EntityStateException(String message) { + super(message); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionNotFoundException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionNotFoundException.java index d2533293..db708eed 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionNotFoundException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionNotFoundException.java @@ -6,8 +6,7 @@ */ public class FunctionNotFoundException extends FunctionRegistryException { - public FunctionNotFoundException(String functionName) { - super("No function with this name has been registered: " + functionName); - } - + public FunctionNotFoundException(String functionName) { + super("No function with this name has been registered: " + functionName); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionRegistryException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionRegistryException.java index 3f930053..b441a9d2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionRegistryException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/FunctionRegistryException.java @@ -6,8 +6,7 @@ */ public abstract class FunctionRegistryException extends RepositoryMockException { - public FunctionRegistryException(String message) { - super(message); - } - + public FunctionRegistryException(String message) { + super(message); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/InvalidArgumentException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/InvalidArgumentException.java index 1c24a374..17fd524c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/InvalidArgumentException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/InvalidArgumentException.java @@ -6,12 +6,11 @@ */ public class InvalidArgumentException extends DataOperationException { - public InvalidArgumentException(String message) { - super(message); - } - - public InvalidArgumentException(String message, Throwable cause) { - super(message, cause); - } + public InvalidArgumentException(String message) { + super(message); + } + public InvalidArgumentException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MockBuilderException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MockBuilderException.java index f5d42392..7fcd5b0f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MockBuilderException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MockBuilderException.java @@ -6,8 +6,7 @@ */ public class MockBuilderException extends RepositoryMockException { - public MockBuilderException(String message, Throwable cause) { - super(message, cause); - } - + public MockBuilderException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MultipleIdPropertiesException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MultipleIdPropertiesException.java index efdff7ff..b21cd06f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MultipleIdPropertiesException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/MultipleIdPropertiesException.java @@ -6,8 +6,10 @@ */ public class MultipleIdPropertiesException extends EntityDefinitionException { - public MultipleIdPropertiesException(Class entityType) { - super("There are multiple properties in " + entityType + " that are annotated as the ID property"); - } - + public MultipleIdPropertiesException(Class entityType) { + super( + "There are multiple properties in " + + entityType + + " that are annotated as the ID property"); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/NoIdPropertyException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/NoIdPropertyException.java index 6529e464..11be02e0 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/NoIdPropertyException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/NoIdPropertyException.java @@ -6,8 +6,7 @@ */ public class NoIdPropertyException extends EntityDefinitionException { - public NoIdPropertyException(Class entityType) { - super("No id property could be resolved for type " + entityType); - } - + public NoIdPropertyException(Class entityType) { + super("No id property could be resolved for type " + entityType); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/OperatorContextException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/OperatorContextException.java index 68d00f10..d3b48cee 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/OperatorContextException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/OperatorContextException.java @@ -6,8 +6,7 @@ */ public class OperatorContextException extends RepositoryMockException { - public OperatorContextException(String message) { - super(message); - } - + public OperatorContextException(String message) { + super(message); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ParserException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ParserException.java index c87fd476..9a800dd0 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ParserException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ParserException.java @@ -6,8 +6,7 @@ */ public class ParserException extends RuntimeException { - public ParserException(String message) { - super(message); - } - + public ParserException(String message) { + super(message); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PrimitiveIdTypeException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PrimitiveIdTypeException.java index ac486d69..ee010dbd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PrimitiveIdTypeException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PrimitiveIdTypeException.java @@ -6,9 +6,12 @@ */ public class PrimitiveIdTypeException extends EntityDefinitionException { - public PrimitiveIdTypeException(Class entityType, String idProperty) { - super("The ID property (" + idProperty + ") found on entity <" + entityType - + "> is of a primitive type. Primitive types are not supported by this framework."); - } - + public PrimitiveIdTypeException(Class entityType, String idProperty) { + super( + "The ID property (" + + idProperty + + ") found on entity <" + + entityType + + "> is of a primitive type. Primitive types are not supported by this framework."); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PropertyTypeMismatchException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PropertyTypeMismatchException.java index ad57fa1f..34267e10 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PropertyTypeMismatchException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/PropertyTypeMismatchException.java @@ -6,10 +6,17 @@ */ public class PropertyTypeMismatchException extends EntityDefinitionException { - public PropertyTypeMismatchException(Class declaringClass, String propertyName, Class expectedType, - Class actualType) { - super("Expected property <" + propertyName + "> of class <" + declaringClass + "> to be of type <" - + expectedType + "> but it was of type <" + actualType + ">"); - } - + public PropertyTypeMismatchException( + Class declaringClass, String propertyName, Class expectedType, Class actualType) { + super( + "Expected property <" + + propertyName + + "> of class <" + + declaringClass + + "> to be of type <" + + expectedType + + "> but it was of type <" + + actualType + + ">"); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/QueryParserException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/QueryParserException.java index 941dd253..5fe83f0a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/QueryParserException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/QueryParserException.java @@ -6,12 +6,11 @@ */ public class QueryParserException extends RepositoryDefinitionException { - public QueryParserException(Class repositoryInterface, String message) { - super(repositoryInterface, message); - } - - public QueryParserException(Class repositoryInterface, String message, Throwable cause) { - super(repositoryInterface, message, cause); - } + public QueryParserException(Class repositoryInterface, String message) { + super(repositoryInterface, message); + } + public QueryParserException(Class repositoryInterface, String message, Throwable cause) { + super(repositoryInterface, message, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java index 8e9ac57a..3a25977f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java @@ -6,12 +6,12 @@ */ public class RepositoryDefinitionException extends RepositoryMockException { - public RepositoryDefinitionException(Class repositoryInterface, String message) { - super(repositoryInterface + ": " + message); - } - - public RepositoryDefinitionException(Class repositoryInterface, String message, Throwable cause) { - super(repositoryInterface + ": " + message, cause); - } + public RepositoryDefinitionException(Class repositoryInterface, String message) { + super(repositoryInterface + ": " + message); + } + public RepositoryDefinitionException( + Class repositoryInterface, String message, Throwable cause) { + super(repositoryInterface + ": " + message, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryMockException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryMockException.java index d780cb96..aea6fad2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryMockException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryMockException.java @@ -6,12 +6,11 @@ */ public abstract class RepositoryMockException extends RuntimeException { - public RepositoryMockException(String message) { - super(message); - } - - public RepositoryMockException(String message, Throwable cause) { - super(message, cause); - } + public RepositoryMockException(String message) { + super(message); + } + public RepositoryMockException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultAdapterFailureException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultAdapterFailureException.java index 12535aa3..fa6c9a06 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultAdapterFailureException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultAdapterFailureException.java @@ -6,16 +6,24 @@ */ public class ResultAdapterFailureException extends DataOperationException { - public ResultAdapterFailureException(Object originalValue, Class expectedType) { - super("Could not adapt value: <" + originalValue + "> to type <" + expectedType + ">"); - } + public ResultAdapterFailureException(Object originalValue, Class expectedType) { + super("Could not adapt value: <" + originalValue + "> to type <" + expectedType + ">"); + } - public ResultAdapterFailureException(Object originalValue, Class expectedType, String failure) { - super("Could not adapt value: <" + originalValue + "> to type <" + expectedType + ">; " + failure); - } - - public ResultAdapterFailureException(Object originalValue, Class expectedType, Throwable failure) { - super("Could not adapt value: <" + originalValue + "> to type <" + expectedType + ">; ", failure); - } + public ResultAdapterFailureException( + Object originalValue, Class expectedType, String failure) { + super( + "Could not adapt value: <" + + originalValue + + "> to type <" + + expectedType + + ">; " + + failure); + } + public ResultAdapterFailureException( + Object originalValue, Class expectedType, Throwable failure) { + super( + "Could not adapt value: <" + originalValue + "> to type <" + expectedType + ">; ", failure); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultConversionFailureException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultConversionFailureException.java index 225c657e..ad66dda3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultConversionFailureException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/ResultConversionFailureException.java @@ -6,8 +6,7 @@ */ public class ResultConversionFailureException extends DataOperationException { - public ResultConversionFailureException(Throwable cause) { - super("Failed to retrieve promised result", cause); - } - + public ResultConversionFailureException(Throwable cause) { + super("Failed to retrieve promised result", cause); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/UnknownDataOperationException.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/UnknownDataOperationException.java index e39ddd49..9cea1b7f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/UnknownDataOperationException.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/UnknownDataOperationException.java @@ -8,8 +8,7 @@ */ public class UnknownDataOperationException extends DataOperationException { - public UnknownDataOperationException(Method method) { - super("Failed to resolve operation for method: " + method); - } - + public UnknownDataOperationException(Method method) { + super("Failed to resolve operation for method: " + method); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/DataOperationResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/DataOperationResolver.java index e656ede1..4347c7f0 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/DataOperationResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/DataOperationResolver.java @@ -5,21 +5,19 @@ import java.lang.reflect.Method; /** - *

This interface encapsulates the process of resolving the handler for a single unit of work when interacting with - * an - * underlying {@link com.mmnaseri.utils.spring.data.store.DataStore data store}.

+ * This interface encapsulates the process of resolving the handler for a single unit of work when + * interacting with an underlying {@link com.mmnaseri.utils.spring.data.store.DataStore data store}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public interface DataOperationResolver { - /** - * Resolves the data store operation from the given method - * - * @param method the method for which a data operation is required. - * @return the resolved operation. - */ - DataStoreOperation resolve(Method method); - + /** + * Resolves the data store operation from the given method + * + * @param method the method for which a data operation is required. + * @return the resolved operation. + */ + DataStoreOperation resolve(Method method); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/DependencyAware.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/DependencyAware.java index b220683d..b0f2e688 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/DependencyAware.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/DependencyAware.java @@ -1,13 +1,11 @@ package com.mmnaseri.utils.spring.data.proxy; /** - * This interface indicates that an interface should be used to inject dependencies into a concrete mapping - * implementation class. + * This interface indicates that an interface should be used to inject dependencies into a concrete + * mapping implementation class. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (4/14/16, 12:49 AM) */ @SuppressWarnings("WeakerAccess") -public interface DependencyAware { - -} +public interface DependencyAware {} diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/InvocationMapping.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/InvocationMapping.java index 8c9ccc09..26e37565 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/InvocationMapping.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/InvocationMapping.java @@ -5,22 +5,17 @@ import java.lang.reflect.Method; /** - *

This interface is used to represent data about a single invocation mapping, consisting of the method and - * the data store operation to which it is bound.

+ * This interface is used to represent data about a single invocation mapping, consisting of the + * method and the data store operation to which it is bound. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public interface InvocationMapping { - /** - * @return the method - */ - Method getMethod(); - - /** - * @return the data store operation - */ - DataStoreOperation getOperation(); + /** @return the method */ + Method getMethod(); + /** @return the data store operation */ + DataStoreOperation getOperation(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/NonDataOperationHandler.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/NonDataOperationHandler.java index e24ca271..7d25a1ef 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/NonDataOperationHandler.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/NonDataOperationHandler.java @@ -11,24 +11,25 @@ @SuppressWarnings("unused") public interface NonDataOperationHandler { - /** - * Used to find out if the given invocation on the indicated proxy object can be handled by this handler. - * - * @param proxy the proxy - * @param method the method - * @param args the arguments passed to the method - * @return {@literal true} if this handler can handle the given invocation. - */ - boolean handles(Object proxy, Method method, Object... args); - - /** - * Used to handle the invocation. It is assumed that prior to calling this method, the caller has already verified - * (using {@link #handles(Object, Method, Object...)}) that the handler can indeed handle this method invocation. - * - * @param proxy the proxy object - * @param args the arguments - * @return the result - */ - Object invoke(Object proxy, Object... args); + /** + * Used to find out if the given invocation on the indicated proxy object can be handled by this + * handler. + * + * @param proxy the proxy + * @param method the method + * @param args the arguments passed to the method + * @return {@literal true} if this handler can handle the given invocation. + */ + boolean handles(Object proxy, Method method, Object... args); + /** + * Used to handle the invocation. It is assumed that prior to calling this method, the caller has + * already verified (using {@link #handles(Object, Method, Object...)}) that the handler can + * indeed handle this method invocation. + * + * @param proxy the proxy object + * @param args the arguments + * @return the result + */ + Object invoke(Object proxy, Object... args); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryConfiguration.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryConfiguration.java index 5692aa85..9f596167 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryConfiguration.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryConfiguration.java @@ -6,27 +6,23 @@ import java.util.List; /** - * This interface represents all the pieces of information that were used to instantiate a repository instance. + * This interface represents all the pieces of information that were used to instantiate a + * repository instance. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/12/15) */ public interface RepositoryConfiguration { - /** - * @return the repository metadata - */ - RepositoryMetadata getRepositoryMetadata(); + /** @return the repository metadata */ + RepositoryMetadata getRepositoryMetadata(); - /** - * @return the key generator - */ - KeyGenerator getKeyGenerator(); - - /** - * @return implementations bound to the repository instance (including the ones derived from the {@link - * TypeMappingContext} used when instantiating the repository. - */ - List> getBoundImplementations(); + /** @return the key generator */ + KeyGenerator getKeyGenerator(); + /** + * @return implementations bound to the repository instance (including the ones derived from the + * {@link TypeMappingContext} used when instantiating the repository. + */ + List> getBoundImplementations(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryConfigurationAware.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryConfigurationAware.java index 4620f8b3..a329701d 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryConfigurationAware.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryConfigurationAware.java @@ -8,11 +8,10 @@ */ public interface RepositoryConfigurationAware extends DependencyAware { - /** - * Called when the bound implementation class needs to know about the repository configuration. - * - * @param repositoryConfiguration the repository configuration - */ - void setRepositoryConfiguration(RepositoryConfiguration repositoryConfiguration); - + /** + * Called when the bound implementation class needs to know about the repository configuration. + * + * @param repositoryConfiguration the repository configuration + */ + void setRepositoryConfiguration(RepositoryConfiguration repositoryConfiguration); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactory.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactory.java index d1238c30..c0c893f4 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactory.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactory.java @@ -3,36 +3,33 @@ import com.mmnaseri.utils.spring.data.domain.KeyGenerator; /** - *

This interface encapsulates the process of instantiating a repository. A repository factory is needed to - * properly set up a repository instance.

+ * This interface encapsulates the process of instantiating a repository. A repository factory is + * needed to properly set up a repository instance. * - *

A default implementation is provided via {@link com.mmnaseri.utils.spring.data.proxy.impl.DefaultRepositoryFactory - * default - * repositor factory}.

+ *

A default implementation is provided via {@link + * com.mmnaseri.utils.spring.data.proxy.impl.DefaultRepositoryFactory default repositor factory}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public interface RepositoryFactory { - /** - * Creates an instance of the repository as per the provided configuration. - * - * @param keyGenerator the key generator to use when inserting items (if auto generation is required). You - * can specify a {@literal null} key generator to signify that {@link - * RepositoryFactoryConfiguration#getDefaultKeyGenerator() the fallback key generator} - * should be used when generating keys. - * @param repositoryInterface the repository interface which we want to mock - * @param implementations all the concrete classes that can be used to figure out method mappings - * @param the type of the interface - * @return a prepared instance of the repository - * @throws com.mmnaseri.utils.spring.data.error.RepositoryMockException should anything go wrong - */ - E getInstance(KeyGenerator keyGenerator, Class repositoryInterface, Class... implementations); - - /** - * @return the configuration bound to this repository factory - */ - RepositoryFactoryConfiguration getConfiguration(); + /** + * Creates an instance of the repository as per the provided configuration. + * + * @param keyGenerator the key generator to use when inserting items (if auto generation is + * required). You can specify a {@literal null} key generator to signify that {@link + * RepositoryFactoryConfiguration#getDefaultKeyGenerator() the fallback key generator} should + * be used when generating keys. + * @param repositoryInterface the repository interface which we want to mock + * @param implementations all the concrete classes that can be used to figure out method mappings + * @param the type of the interface + * @return a prepared instance of the repository + * @throws com.mmnaseri.utils.spring.data.error.RepositoryMockException should anything go wrong + */ + E getInstance( + KeyGenerator keyGenerator, Class repositoryInterface, Class... implementations); + /** @return the configuration bound to this repository factory */ + RepositoryFactoryConfiguration getConfiguration(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryAware.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryAware.java index 02610d36..900a1088 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryAware.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryAware.java @@ -8,11 +8,10 @@ */ public interface RepositoryFactoryAware extends DependencyAware { - /** - * Used to inject the repository factory into the implementing class - * - * @param factory the factory - */ - void setRepositoryFactory(RepositoryFactory factory); - + /** + * Used to inject the repository factory into the implementing class + * + * @param factory the factory + */ + void setRepositoryFactory(RepositoryFactory factory); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryConfiguration.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryConfiguration.java index cde6b0e4..a531d9f7 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryConfiguration.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryConfiguration.java @@ -9,56 +9,41 @@ import com.mmnaseri.utils.spring.data.store.DataStoreRegistry; /** - * This class will be used to hold all the pieces of information required to instantiate a repository. + * This class will be used to hold all the pieces of information required to instantiate a + * repository. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/8/15) */ public interface RepositoryFactoryConfiguration { - /** - * @return the repository metadata resolver - */ - RepositoryMetadataResolver getRepositoryMetadataResolver(); + /** @return the repository metadata resolver */ + RepositoryMetadataResolver getRepositoryMetadataResolver(); - /** - * @return the description extractor used to extract query metadata from a query method - */ - MethodQueryDescriptionExtractor getDescriptionExtractor(); + /** @return the description extractor used to extract query metadata from a query method */ + MethodQueryDescriptionExtractor getDescriptionExtractor(); - /** - * @return the function registry containing all the functions used when executing the queries - */ - DataFunctionRegistry getFunctionRegistry(); + /** @return the function registry containing all the functions used when executing the queries */ + DataFunctionRegistry getFunctionRegistry(); - /** - * @return the data store registry - */ - DataStoreRegistry getDataStoreRegistry(); + /** @return the data store registry */ + DataStoreRegistry getDataStoreRegistry(); - /** - * @return the result adapter context - */ - ResultAdapterContext getResultAdapterContext(); + /** @return the result adapter context */ + ResultAdapterContext getResultAdapterContext(); - /** - * @return the type mapping context - */ - TypeMappingContext getTypeMappingContext(); + /** @return the type mapping context */ + TypeMappingContext getTypeMappingContext(); - /** - * @return the data store event listener context - */ - DataStoreEventListenerContext getEventListenerContext(); + /** @return the data store event listener context */ + DataStoreEventListenerContext getEventListenerContext(); - /** - * @return the non-data operation invocation handler - */ - NonDataOperationInvocationHandler getOperationInvocationHandler(); - - /** - * @return the default key generator that should be used as a fallback when no key generator is specified - */ - KeyGenerator getDefaultKeyGenerator(); + /** @return the non-data operation invocation handler */ + NonDataOperationInvocationHandler getOperationInvocationHandler(); + /** + * @return the default key generator that should be used as a fallback when no key generator is + * specified + */ + KeyGenerator getDefaultKeyGenerator(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryConfigurationAware.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryConfigurationAware.java index 7aa6a8c2..40f3418c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryConfigurationAware.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/RepositoryFactoryConfigurationAware.java @@ -1,18 +1,18 @@ package com.mmnaseri.utils.spring.data.proxy; /** - * This interface is used when an implementing class needs to know about the repository factory configuration. + * This interface is used when an implementing class needs to know about the repository factory + * configuration. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/9/15) */ public interface RepositoryFactoryConfigurationAware extends DependencyAware { - /** - * This method is called to inject the repository factory configuration - * - * @param configuration the configuration - */ - void setRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration); - + /** + * This method is called to inject the repository factory configuration + * + * @param configuration the configuration + */ + void setRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultAdapter.java index 4006078b..a35d0fb6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultAdapter.java @@ -3,36 +3,34 @@ import com.mmnaseri.utils.spring.data.domain.Invocation; /** - *

This interface is used to encapsulate the process of adapting results from a data store operation to that - * of the invoked repository method.

+ * This interface is used to encapsulate the process of adapting results from a data store operation + * to that of the invoked repository method. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public interface ResultAdapter extends Comparable { - /** - * Called to determine whether or not this adapter can adapt the original value passed down from a data store - * operation to the type required by the repository method being invoked - * - * @param invocation the invocation - * @param originalValue the original value - * @return {@literal true} if the adapter can convert the value - */ - boolean accepts(Invocation invocation, Object originalValue); + /** + * Called to determine whether or not this adapter can adapt the original value passed down from a + * data store operation to the type required by the repository method being invoked + * + * @param invocation the invocation + * @param originalValue the original value + * @return {@literal true} if the adapter can convert the value + */ + boolean accepts(Invocation invocation, Object originalValue); - /** - * Called when we need to adapt the result from an invocation to the result required by the repository method - * - * @param invocation the repository method invocation - * @param originalValue the original value returned from a data store operation - * @return the adapted value - */ - E adapt(Invocation invocation, Object originalValue); - - /** - * @return the priority for this adapter - */ - int getPriority(); + /** + * Called when we need to adapt the result from an invocation to the result required by the + * repository method + * + * @param invocation the repository method invocation + * @param originalValue the original value returned from a data store operation + * @return the adapted value + */ + E adapt(Invocation invocation, Object originalValue); + /** @return the priority for this adapter */ + int getPriority(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultAdapterContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultAdapterContext.java index a6030917..8ebc7c9e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultAdapterContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultAdapterContext.java @@ -5,33 +5,30 @@ import java.util.Collection; /** - *

This interface is used to register result adapters and later call on them to adapt the results to - * the appropriate type.

+ * This interface is used to register result adapters and later call on them to adapt the results to + * the appropriate type. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public interface ResultAdapterContext { - /** - * Registers a new result adapter with this context - * - * @param adapter the adapter - */ - void register(ResultAdapter adapter); + /** + * Registers a new result adapter with this context + * + * @param adapter the adapter + */ + void register(ResultAdapter adapter); - /** - * Will call the registered result adapters to adapt the results to the required type. - * - * @param invocation the invocation for which we are adapting the results - * @param originalResult the original result from the data store operation - * @return the adapted result - */ - Object adapt(Invocation invocation, Object originalResult); - - /** - * @return all the adapters registered with this context - */ - Collection> getAdapters(); + /** + * Will call the registered result adapters to adapt the results to the required type. + * + * @param invocation the invocation for which we are adapting the results + * @param originalResult the original result from the data store operation + * @return the adapted result + */ + Object adapt(Invocation invocation, Object originalResult); + /** @return all the adapters registered with this context */ + Collection> getAdapters(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultConverter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultConverter.java index 33f04211..48963eb3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultConverter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/ResultConverter.java @@ -3,25 +3,24 @@ import com.mmnaseri.utils.spring.data.domain.Invocation; /** - *

This interface encapsulates the process of converting a result from one type to the other.

+ * This interface encapsulates the process of converting a result from one type to the other. * - *

This is different from adapting results since conversion doesn't involve mandatory operations and - * can go through without any change to the original value. Also, converters are chained, so that the result of one is - * passed to the next and so one, whereas with adapters, you have a single adapter suitable for the current situation - * that operates on the result.

+ *

This is different from adapting results since conversion doesn't involve mandatory operations + * and can go through without any change to the original value. Also, converters are chained, so + * that the result of one is passed to the next and so one, whereas with adapters, you have a single + * adapter suitable for the current situation that operates on the result. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public interface ResultConverter { - /** - * Called when we need to convert the result - * - * @param invocation the invocation for which the conversion is happening - * @param original the original value - * @return the converted value (or the original value if no conversion happened) - */ - Object convert(Invocation invocation, Object original); - + /** + * Called when we need to convert the result + * + * @param invocation the invocation for which the conversion is happening + * @param original the original value + * @return the converted value (or the original value if no conversion happened) + */ + Object convert(Invocation invocation, Object original); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/TypeMapping.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/TypeMapping.java index 9c733047..6ecc39ef 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/TypeMapping.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/TypeMapping.java @@ -8,14 +8,9 @@ */ public interface TypeMapping { - /** - * @return the type of the mapped class - */ - Class getType(); - - /** - * @return an instance of the mapped class - */ - E getInstance(); + /** @return the type of the mapped class */ + Class getType(); + /** @return an instance of the mapped class */ + E getInstance(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/TypeMappingContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/TypeMappingContext.java index 4df713d5..8bae0578 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/TypeMappingContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/TypeMappingContext.java @@ -10,31 +10,31 @@ */ public interface TypeMappingContext { - /** - * Registers a mapping that should be honored for all repositories that are a subtype of the provided repository - * type. This means that if you register an implementation for {@link Object} all repositories will inherit this - * mapping. - * - * @param repositoryType the repository (super) type - * @param implementation the implementation type - */ - void register(Class repositoryType, Class implementation); + /** + * Registers a mapping that should be honored for all repositories that are a subtype of the + * provided repository type. This means that if you register an implementation for {@link Object} + * all repositories will inherit this mapping. + * + * @param repositoryType the repository (super) type + * @param implementation the implementation type + */ + void register(Class repositoryType, Class implementation); - /** - * Given a repository type returns all concrete classes that could be used for that repository's mappings - * - * @param repositoryType the repository type - * @return the list of all possible mappings - */ - List> getImplementations(Class repositoryType); - - /** - * Given a repository type, will look up all possible mappings and creates {@link TypeMapping mapping} objects from - * those - * - * @param repositoryType the repository type - * @return a list of applicable mappings in the order in which they were registered - */ - List> getMappings(Class repositoryType); + /** + * Given a repository type returns all concrete classes that could be used for that repository's + * mappings + * + * @param repositoryType the repository type + * @return the list of all possible mappings + */ + List> getImplementations(Class repositoryType); + /** + * Given a repository type, will look up all possible mappings and creates {@link TypeMapping + * mapping} objects from those + * + * @param repositoryType the repository type + * @return a list of applicable mappings in the order in which they were registered + */ + List> getMappings(Class repositoryType); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandler.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandler.java index 83481d08..a5c29a55 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandler.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandler.java @@ -21,12 +21,12 @@ import java.util.concurrent.CopyOnWriteArraySet; /** - *

This class is in charge of handling a data operation that was triggered by invoking a repository method.

+ * This class is in charge of handling a data operation that was triggered by invoking a repository + * method. * - *

The invocation is first considered by trying to find a data operation handler. If such a handler cannot be - * found, we will try to handle it by finding the appropriate - * {@link com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler - * non-data operation handler}.

+ *

The invocation is first considered by trying to find a data operation handler. If such a + * handler cannot be found, we will try to handle it by finding the appropriate {@link + * com.mmnaseri.utils.spring.data.proxy.NonDataOperationHandler non-data operation handler}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) @@ -34,60 +34,64 @@ @SuppressWarnings("WeakerAccess") public class DataOperationInvocationHandler implements InvocationHandler { - private static final Log log = LogFactory.getLog(DataOperationInvocationHandler.class); - private final DataStore dataStore; - private final ResultAdapterContext adapterContext; - private final ResultConverter converter; - private final RepositoryConfiguration repositoryConfiguration; - private final List> mappings; - private final Map> cache = new ConcurrentHashMap<>(); - private final Set misses = new CopyOnWriteArraySet<>(); - private final NonDataOperationInvocationHandler operationInvocationHandler; + private static final Log log = LogFactory.getLog(DataOperationInvocationHandler.class); + private final DataStore dataStore; + private final ResultAdapterContext adapterContext; + private final ResultConverter converter; + private final RepositoryConfiguration repositoryConfiguration; + private final List> mappings; + private final Map> cache = new ConcurrentHashMap<>(); + private final Set misses = new CopyOnWriteArraySet<>(); + private final NonDataOperationInvocationHandler operationInvocationHandler; - public DataOperationInvocationHandler(RepositoryConfiguration repositoryConfiguration, - List> mappings, - DataStore dataStore, ResultAdapterContext adapterContext, - NonDataOperationInvocationHandler operationInvocationHandler) { - this.repositoryConfiguration = repositoryConfiguration; - this.mappings = mappings; - this.dataStore = dataStore; - this.adapterContext = adapterContext; - this.operationInvocationHandler = operationInvocationHandler; - this.converter = new DefaultResultConverter(); - } + public DataOperationInvocationHandler( + RepositoryConfiguration repositoryConfiguration, + List> mappings, + DataStore dataStore, + ResultAdapterContext adapterContext, + NonDataOperationInvocationHandler operationInvocationHandler) { + this.repositoryConfiguration = repositoryConfiguration; + this.mappings = mappings; + this.dataStore = dataStore; + this.adapterContext = adapterContext; + this.operationInvocationHandler = operationInvocationHandler; + this.converter = new DefaultResultConverter(); + } - @Override - public Object invoke(Object proxy, Method method, Object[] args) { - log.info("A method call to " + method - + " has been intercepted. We will now try to find an appropriate invocation."); - final Invocation methodInvocation = new ImmutableInvocation(method, args); - InvocationMapping targetMapping = null; - if (!misses.contains(method)) { - if (cache.containsKey(method)) { - targetMapping = cache.get(method); - } else { - for (InvocationMapping mapping : mappings) { - if (mapping.getMethod().equals(method)) { - targetMapping = mapping; - cache.put(method, targetMapping); - break; - } - } - } - } - if (targetMapping == null) { - log.info( - "The invocation cannot be resolved using a data operation. We will try to handle this as a " - + "non-data operation"); - misses.add(method); - return operationInvocationHandler.invoke(proxy, method, args); + @Override + public Object invoke(Object proxy, Method method, Object[] args) { + log.info( + "A method call to " + + method + + " has been intercepted. We will now try to find an appropriate invocation."); + final Invocation methodInvocation = new ImmutableInvocation(method, args); + InvocationMapping targetMapping = null; + if (!misses.contains(method)) { + if (cache.containsKey(method)) { + targetMapping = cache.get(method); + } else { + for (InvocationMapping mapping : mappings) { + if (mapping.getMethod().equals(method)) { + targetMapping = mapping; + cache.put(method, targetMapping); + break; + } } - final DataStoreOperation operation = targetMapping.getOperation(); - log.info("Executing the operation for method " + method); - final Object operationResult = operation.execute(dataStore, repositoryConfiguration, methodInvocation); - log.info("Trying to see if any conversion is necessary on the object"); - final Object convertedResult = converter.convert(methodInvocation, operationResult); - return adapterContext.adapt(methodInvocation, convertedResult); + } } - + if (targetMapping == null) { + log.info( + "The invocation cannot be resolved using a data operation. We will try to handle this as a " + + "non-data operation"); + misses.add(method); + return operationInvocationHandler.invoke(proxy, method, args); + } + final DataStoreOperation operation = targetMapping.getOperation(); + log.info("Executing the operation for method " + method); + final Object operationResult = + operation.execute(dataStore, repositoryConfiguration, methodInvocation); + log.info("Trying to see if any conversion is necessary on the object"); + final Object convertedResult = converter.convert(methodInvocation, operationResult); + return adapterContext.adapt(methodInvocation, convertedResult); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactory.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactory.java index d72e9a94..49769184 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactory.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactory.java @@ -1,9 +1,25 @@ package com.mmnaseri.utils.spring.data.proxy.impl; -import com.mmnaseri.utils.spring.data.domain.*; +import com.mmnaseri.utils.spring.data.domain.DataStoreAware; +import com.mmnaseri.utils.spring.data.domain.KeyGenerator; +import com.mmnaseri.utils.spring.data.domain.KeyGeneratorAware; +import com.mmnaseri.utils.spring.data.domain.RepositoryAware; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataAware; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataResolver; import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor; import com.mmnaseri.utils.spring.data.domain.impl.key.NoOpKeyGenerator; -import com.mmnaseri.utils.spring.data.proxy.*; +import com.mmnaseri.utils.spring.data.proxy.DataOperationResolver; +import com.mmnaseri.utils.spring.data.proxy.InvocationMapping; +import com.mmnaseri.utils.spring.data.proxy.RepositoryConfiguration; +import com.mmnaseri.utils.spring.data.proxy.RepositoryConfigurationAware; +import com.mmnaseri.utils.spring.data.proxy.RepositoryFactory; +import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryAware; +import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration; +import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfigurationAware; +import com.mmnaseri.utils.spring.data.proxy.ResultAdapterContext; +import com.mmnaseri.utils.spring.data.proxy.TypeMapping; +import com.mmnaseri.utils.spring.data.proxy.TypeMappingContext; import com.mmnaseri.utils.spring.data.proxy.impl.resolvers.DefaultDataOperationResolver; import com.mmnaseri.utils.spring.data.query.DataFunctionRegistry; import com.mmnaseri.utils.spring.data.store.DataStore; @@ -25,228 +41,246 @@ import java.util.concurrent.ConcurrentHashMap; /** - *

This class is the entry point to this framework as a whole. Using this class, you can mock a repository - * interface by passing the proper set of configurations and parameters.

+ * This class is the entry point to this framework as a whole. Using this class, you can mock a + * repository interface by passing the proper set of configurations and parameters. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class DefaultRepositoryFactory implements RepositoryFactory { - private static final Log log = LogFactory.getLog(DefaultRepositoryFactory.class); - private final RepositoryMetadataResolver repositoryMetadataResolver; - private final Map, RepositoryMetadata> metadataMap = new ConcurrentHashMap<>(); - private final MethodQueryDescriptionExtractor descriptionExtractor; - private final DataFunctionRegistry functionRegistry; - private final DataStoreRegistry dataStoreRegistry; - private final ResultAdapterContext adapterContext; - private final TypeMappingContext typeMappingContext; - private final RepositoryFactoryConfiguration configuration; - private final NonDataOperationInvocationHandler operationInvocationHandler; + private static final Log log = LogFactory.getLog(DefaultRepositoryFactory.class); + private final RepositoryMetadataResolver repositoryMetadataResolver; + private final Map, RepositoryMetadata> metadataMap = new ConcurrentHashMap<>(); + private final MethodQueryDescriptionExtractor descriptionExtractor; + private final DataFunctionRegistry functionRegistry; + private final DataStoreRegistry dataStoreRegistry; + private final ResultAdapterContext adapterContext; + private final TypeMappingContext typeMappingContext; + private final RepositoryFactoryConfiguration configuration; + private final NonDataOperationInvocationHandler operationInvocationHandler; - public DefaultRepositoryFactory(RepositoryFactoryConfiguration configuration) { - this.configuration = configuration; - this.repositoryMetadataResolver = configuration.getRepositoryMetadataResolver(); - this.descriptionExtractor = configuration.getDescriptionExtractor(); - this.functionRegistry = configuration.getFunctionRegistry(); - this.dataStoreRegistry = configuration.getDataStoreRegistry(); - this.adapterContext = configuration.getResultAdapterContext(); - this.typeMappingContext = configuration.getTypeMappingContext(); - this.operationInvocationHandler = configuration.getOperationInvocationHandler(); - } + public DefaultRepositoryFactory(RepositoryFactoryConfiguration configuration) { + this.configuration = configuration; + this.repositoryMetadataResolver = configuration.getRepositoryMetadataResolver(); + this.descriptionExtractor = configuration.getDescriptionExtractor(); + this.functionRegistry = configuration.getFunctionRegistry(); + this.dataStoreRegistry = configuration.getDataStoreRegistry(); + this.adapterContext = configuration.getResultAdapterContext(); + this.typeMappingContext = configuration.getTypeMappingContext(); + this.operationInvocationHandler = configuration.getOperationInvocationHandler(); + } - @Override - public E getInstance(KeyGenerator keyGenerator, Class repositoryInterface, Class... implementations) { - final KeyGenerator actualKeyGenerator; - if (keyGenerator == null) { - if (configuration.getDefaultKeyGenerator() != null) { - //if no key generator is passed and there is a default key generator specified, we fall back to that - actualKeyGenerator = configuration.getDefaultKeyGenerator(); - } else { - //otherwise, let's assume that not key generation is required - actualKeyGenerator = new NoOpKeyGenerator<>(); - } - } else { - actualKeyGenerator = keyGenerator; - } - log.info("We are going to create a proxy instance of type " + repositoryInterface + " using key generator " - + actualKeyGenerator + " and binding the implementations to " + Arrays - .toString(implementations)); - //figure out the repository metadata - log.info("Resolving repository metadata for " + repositoryInterface); - final RepositoryMetadata metadata = getRepositoryMetadata(repositoryInterface); - //get the underlying data store - log.info("Resolving the data store for " + repositoryInterface); - final DataStore dataStore = getDataStore(metadata); - //figure out type mappings - log.info("Trying to find all the proper type mappings for entity repository " + repositoryInterface); - final List> typeMappings = getTypeMappings(metadata, dataStore, actualKeyGenerator, - implementations); - //set up the data operation resolver - final DataOperationResolver operationResolver = new DefaultDataOperationResolver(typeMappings, - descriptionExtractor, metadata, - functionRegistry, - configuration); - //get all of this repository's methods - final Method[] methods = repositoryInterface.getMethods(); - //get mappings for the repository methods - log.info("Trying to find all the invocation mappings for methods declared on " + repositoryInterface); - final List> invocationMappings = getInvocationMappings(operationResolver, methods); - //extract the bound implementation types - final List> boundImplementations = new LinkedList<>(); - for (TypeMapping mapping : typeMappings) { - boundImplementations.add(mapping.getType()); - } - //set up the repository configuration - final RepositoryConfiguration repositoryConfiguration = new ImmutableRepositoryConfiguration(metadata, - actualKeyGenerator, - boundImplementations); - //create the interceptor + @Override + public E getInstance( + KeyGenerator keyGenerator, Class repositoryInterface, Class... implementations) { + final KeyGenerator actualKeyGenerator; + if (keyGenerator == null) { + if (configuration.getDefaultKeyGenerator() != null) { + // if no key generator is passed and there is a default key generator specified, we fall + // back to that + actualKeyGenerator = configuration.getDefaultKeyGenerator(); + } else { + // otherwise, let's assume that not key generation is required + actualKeyGenerator = new NoOpKeyGenerator<>(); + } + } else { + actualKeyGenerator = keyGenerator; + } + log.info( + "We are going to create a proxy instance of type " + + repositoryInterface + + " using key generator " + + actualKeyGenerator + + " and binding the implementations to " + + Arrays.toString(implementations)); + // figure out the repository metadata + log.info("Resolving repository metadata for " + repositoryInterface); + final RepositoryMetadata metadata = getRepositoryMetadata(repositoryInterface); + // get the underlying data store + log.info("Resolving the data store for " + repositoryInterface); + final DataStore dataStore = getDataStore(metadata); + // figure out type mappings + log.info( + "Trying to find all the proper type mappings for entity repository " + repositoryInterface); + final List> typeMappings = + getTypeMappings(metadata, dataStore, actualKeyGenerator, implementations); + // set up the data operation resolver + final DataOperationResolver operationResolver = + new DefaultDataOperationResolver( + typeMappings, descriptionExtractor, metadata, functionRegistry, configuration); + // get all of this repository's methods + final Method[] methods = repositoryInterface.getMethods(); + // get mappings for the repository methods + log.info( + "Trying to find all the invocation mappings for methods declared on " + + repositoryInterface); + final List> invocationMappings = + getInvocationMappings(operationResolver, methods); + // extract the bound implementation types + final List> boundImplementations = new LinkedList<>(); + for (TypeMapping mapping : typeMappings) { + boundImplementations.add(mapping.getType()); + } + // set up the repository configuration + final RepositoryConfiguration repositoryConfiguration = + new ImmutableRepositoryConfiguration(metadata, actualKeyGenerator, boundImplementations); + // create the interceptor + //noinspection unchecked + final InvocationHandler interceptor = + new DataOperationInvocationHandler( + repositoryConfiguration, + invocationMappings, + dataStore, + adapterContext, + operationInvocationHandler); + // create a proxy for the repository + log.info("Instantiating the proxy using the provided configuration"); + final Object instance = + Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {repositoryInterface}, interceptor); + // for each type mapping, inject proper dependencies + for (TypeMapping typeMapping : typeMappings) { + log.info( + "Injecting all the required dependencies into the repository mapping implementations"); + if (typeMapping.getInstance() instanceof RepositoryAware) { //noinspection unchecked - final InvocationHandler interceptor = new DataOperationInvocationHandler(repositoryConfiguration, - invocationMappings, dataStore, - adapterContext, - operationInvocationHandler); - //create a proxy for the repository - log.info("Instantiating the proxy using the provided configuration"); - final Object instance = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{repositoryInterface}, - interceptor); - //for each type mapping, inject proper dependencies - for (TypeMapping typeMapping : typeMappings) { - log.info("Injecting all the required dependencies into the repository mapping implementations"); - if (typeMapping.getInstance() instanceof RepositoryAware) { - //noinspection unchecked - ((RepositoryAware) typeMapping.getInstance()).setRepository(instance); - } - if (typeMapping.getInstance() instanceof RepositoryConfigurationAware) { - ((RepositoryConfigurationAware) typeMapping.getInstance()).setRepositoryConfiguration( - repositoryConfiguration); - } - if (typeMapping.getInstance() instanceof RepositoryFactoryAware) { - ((RepositoryFactoryAware) typeMapping.getInstance()).setRepositoryFactory(this); - } - } - //return the repository instance - return repositoryInterface.cast(instance); + ((RepositoryAware) typeMapping.getInstance()).setRepository(instance); + } + if (typeMapping.getInstance() instanceof RepositoryConfigurationAware) { + ((RepositoryConfigurationAware) typeMapping.getInstance()) + .setRepositoryConfiguration(repositoryConfiguration); + } + if (typeMapping.getInstance() instanceof RepositoryFactoryAware) { + ((RepositoryFactoryAware) typeMapping.getInstance()).setRepositoryFactory(this); + } } + // return the repository instance + return repositoryInterface.cast(instance); + } - @Override - public RepositoryFactoryConfiguration getConfiguration() { - return configuration; - } + @Override + public RepositoryFactoryConfiguration getConfiguration() { + return configuration; + } - /** - *

Given a repository metadata, it will find out all the proper type mappings bound as implementations to the - * repository. These will come from the - * {@link TypeMappingContext}, overridden by the implementations provided by the user for this specific case.

- * - *

If the mapped concrete class needs to know anything from the current mocking context, it can implement one of - * the - * various {@link org.springframework.beans.factory.Aware aware} interfaces to be given the proper piece of - * contextual information.

- * - * @param metadata the repository metadata - * @param dataStore the data store - * @param keyGenerator the key generator - * @param implementations the implementations specified by the user - * @return the resolved list of type mappings - */ - private List> getTypeMappings(RepositoryMetadata metadata, DataStore dataStore, - KeyGenerator keyGenerator, Class[] implementations) { - final TypeMappingContext localContext = new DefaultTypeMappingContext(typeMappingContext); - for (Class implementation : implementations) { - localContext.register(metadata.getRepositoryInterface(), implementation); - } - final List> typeMappings = new LinkedList<>(localContext.getMappings(metadata.getRepositoryInterface())); - for (TypeMapping mapping : typeMappings) { - if (mapping.getInstance() instanceof DataStoreAware) { - DataStoreAware instance = (DataStoreAware) mapping.getInstance(); - instance.setDataStore(dataStore); - } - if (mapping.getInstance() instanceof RepositoryMetadataAware) { - RepositoryMetadataAware instance = (RepositoryMetadataAware) mapping.getInstance(); - instance.setRepositoryMetadata(metadata); - } - if (mapping.getInstance() instanceof KeyGeneratorAware) { - KeyGeneratorAware instance = (KeyGeneratorAware) mapping.getInstance(); - //noinspection unchecked - instance.setKeyGenerator(keyGenerator); - } - if (mapping.getInstance() instanceof RepositoryFactoryConfigurationAware) { - RepositoryFactoryConfigurationAware instance = - (RepositoryFactoryConfigurationAware) mapping.getInstance(); - instance.setRepositoryFactoryConfiguration(configuration); - } - } - return typeMappings; + /** + * Given a repository metadata, it will find out all the proper type mappings bound as + * implementations to the repository. These will come from the {@link TypeMappingContext}, + * overridden by the implementations provided by the user for this specific case. + * + *

If the mapped concrete class needs to know anything from the current mocking context, it can + * implement one of the various {@link org.springframework.beans.factory.Aware aware} interfaces + * to be given the proper piece of contextual information. + * + * @param metadata the repository metadata + * @param dataStore the data store + * @param keyGenerator the key generator + * @param implementations the implementations specified by the user + * @return the resolved list of type mappings + */ + private List> getTypeMappings( + RepositoryMetadata metadata, + DataStore dataStore, + KeyGenerator keyGenerator, + Class[] implementations) { + final TypeMappingContext localContext = new DefaultTypeMappingContext(typeMappingContext); + for (Class implementation : implementations) { + localContext.register(metadata.getRepositoryInterface(), implementation); } - - /** - * Given a repository interface, it will resolve the metadata for that interface. - * - * @param repositoryInterface the interface - * @param the type of the interface - * @return the repository metadata associated with the interface - */ - private RepositoryMetadata getRepositoryMetadata(Class repositoryInterface) { - final RepositoryMetadata metadata; - if (metadataMap.containsKey(repositoryInterface)) { - metadata = metadataMap.get(repositoryInterface); - } else { - metadata = repositoryMetadataResolver.resolve(repositoryInterface); - metadataMap.put(repositoryInterface, metadata); - } - return metadata; + final List> typeMappings = + new LinkedList<>(localContext.getMappings(metadata.getRepositoryInterface())); + for (TypeMapping mapping : typeMappings) { + if (mapping.getInstance() instanceof DataStoreAware) { + DataStoreAware instance = (DataStoreAware) mapping.getInstance(); + instance.setDataStore(dataStore); + } + if (mapping.getInstance() instanceof RepositoryMetadataAware) { + RepositoryMetadataAware instance = (RepositoryMetadataAware) mapping.getInstance(); + instance.setRepositoryMetadata(metadata); + } + if (mapping.getInstance() instanceof KeyGeneratorAware) { + KeyGeneratorAware instance = (KeyGeneratorAware) mapping.getInstance(); + //noinspection unchecked + instance.setKeyGenerator(keyGenerator); + } + if (mapping.getInstance() instanceof RepositoryFactoryConfigurationAware) { + RepositoryFactoryConfigurationAware instance = + (RepositoryFactoryConfigurationAware) mapping.getInstance(); + instance.setRepositoryFactoryConfiguration(configuration); + } } + return typeMappings; + } - /** - *

Given a repository metadata, it will return the data store instance associated with the entity type for that - * repository.

- * - *

If the data store is not an instance of {@link EventPublishingDataStore} it will wrap it in one, thus enabling - * event processing - * for this repository.

- * - *

It will also register the data store instance to let the user access the data store, as well as cache it for - * future use.

- * - * @param metadata the metadata - * @return the data store - */ - private DataStore getDataStore(RepositoryMetadata metadata) { - DataStore dataStore; - if (dataStoreRegistry.has(metadata.getEntityType())) { - dataStore = dataStoreRegistry.getDataStore(metadata.getEntityType()); - } else { - //noinspection unchecked - dataStore = new MemoryDataStore<>((Class) metadata.getEntityType()); - } - if (!(dataStore instanceof EventPublishingDataStore)) { - dataStore = new EventPublishingDataStore<>(dataStore, metadata, new DefaultDataStoreEventListenerContext( - configuration.getEventListenerContext())); - } - dataStoreRegistry.register(dataStore); - return dataStore; + /** + * Given a repository interface, it will resolve the metadata for that interface. + * + * @param repositoryInterface the interface + * @param the type of the interface + * @return the repository metadata associated with the interface + */ + private RepositoryMetadata getRepositoryMetadata(Class repositoryInterface) { + final RepositoryMetadata metadata; + if (metadataMap.containsKey(repositoryInterface)) { + metadata = metadataMap.get(repositoryInterface); + } else { + metadata = repositoryMetadataResolver.resolve(repositoryInterface); + metadataMap.put(repositoryInterface, metadata); } + return metadata; + } - /** - * Given a set of methods, it will rely on a {@link DataOperationResolver} to find the mappings for each of the - * methods. - * - * @param operationResolver the resolver to use - * @param methods the array of methods - * @return resolved invocations - */ - private List> getInvocationMappings(DataOperationResolver operationResolver, - Method[] methods) { - final List> invocationMappings = new LinkedList<>(); - for (Method method : methods) { - final DataStoreOperation operation = operationResolver.resolve(method); - //noinspection unchecked - invocationMappings.add( - new ImmutableInvocationMapping<>(method, (DataStoreOperation) operation)); - } - return invocationMappings; + /** + * Given a repository metadata, it will return the data store instance associated with the entity + * type for that repository. + * + *

If the data store is not an instance of {@link EventPublishingDataStore} it will wrap it in + * one, thus enabling event processing for this repository. + * + *

It will also register the data store instance to let the user access the data store, as well + * as cache it for future use. + * + * @param metadata the metadata + * @return the data store + */ + private DataStore getDataStore(RepositoryMetadata metadata) { + DataStore dataStore; + if (dataStoreRegistry.has(metadata.getEntityType())) { + dataStore = dataStoreRegistry.getDataStore(metadata.getEntityType()); + } else { + //noinspection unchecked + dataStore = new MemoryDataStore<>((Class) metadata.getEntityType()); } + if (!(dataStore instanceof EventPublishingDataStore)) { + dataStore = + new EventPublishingDataStore<>( + dataStore, + metadata, + new DefaultDataStoreEventListenerContext(configuration.getEventListenerContext())); + } + dataStoreRegistry.register(dataStore); + return dataStore; + } + /** + * Given a set of methods, it will rely on a {@link DataOperationResolver} to find the mappings + * for each of the methods. + * + * @param operationResolver the resolver to use + * @param methods the array of methods + * @return resolved invocations + */ + private List> getInvocationMappings( + DataOperationResolver operationResolver, Method[] methods) { + final List> invocationMappings = new LinkedList<>(); + for (Method method : methods) { + final DataStoreOperation operation = operationResolver.resolve(method); + //noinspection unchecked + invocationMappings.add( + new ImmutableInvocationMapping<>( + method, (DataStoreOperation) operation)); + } + return invocationMappings; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryConfiguration.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryConfiguration.java index 9f5a59d2..04d7645b 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryConfiguration.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryConfiguration.java @@ -18,126 +18,131 @@ */ public class DefaultRepositoryFactoryConfiguration implements RepositoryFactoryConfiguration { - private RepositoryMetadataResolver repositoryMetadataResolver; - private MethodQueryDescriptionExtractor descriptionExtractor; - private DataFunctionRegistry functionRegistry; - private DataStoreRegistry dataStoreRegistry; - private ResultAdapterContext resultAdapterContext; - private TypeMappingContext typeMappingContext; - private DataStoreEventListenerContext eventListenerContext; - private NonDataOperationInvocationHandler operationInvocationHandler; - private KeyGenerator defaultKeyGenerator; - - public DefaultRepositoryFactoryConfiguration() { - } - - public DefaultRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) { - this(configuration.getRepositoryMetadataResolver(), configuration.getDescriptionExtractor(), - configuration.getFunctionRegistry(), configuration.getDataStoreRegistry(), - configuration.getResultAdapterContext(), configuration.getTypeMappingContext(), - configuration.getEventListenerContext(), - configuration.getOperationInvocationHandler(), configuration.getDefaultKeyGenerator()); - } - - public DefaultRepositoryFactoryConfiguration(RepositoryMetadataResolver repositoryMetadataResolver, - MethodQueryDescriptionExtractor descriptionExtractor, - DataFunctionRegistry functionRegistry, - DataStoreRegistry dataStoreRegistry, - ResultAdapterContext resultAdapterContext, - TypeMappingContext typeMappingContext, - DataStoreEventListenerContext eventListenerContext, - NonDataOperationInvocationHandler operationInvocationHandler, - KeyGenerator defaultKeyGenerator) { - this.repositoryMetadataResolver = repositoryMetadataResolver; - this.descriptionExtractor = descriptionExtractor; - this.functionRegistry = functionRegistry; - this.dataStoreRegistry = dataStoreRegistry; - this.resultAdapterContext = resultAdapterContext; - this.typeMappingContext = typeMappingContext; - this.eventListenerContext = eventListenerContext; - this.operationInvocationHandler = operationInvocationHandler; - this.defaultKeyGenerator = defaultKeyGenerator; - } - - @Override - public RepositoryMetadataResolver getRepositoryMetadataResolver() { - return repositoryMetadataResolver; - } - - public void setRepositoryMetadataResolver(RepositoryMetadataResolver repositoryMetadataResolver) { - this.repositoryMetadataResolver = repositoryMetadataResolver; - } - - @Override - public MethodQueryDescriptionExtractor getDescriptionExtractor() { - return descriptionExtractor; - } - - public void setDescriptionExtractor(MethodQueryDescriptionExtractor descriptionExtractor) { - this.descriptionExtractor = descriptionExtractor; - } - - @Override - public DataFunctionRegistry getFunctionRegistry() { - return functionRegistry; - } - - public void setFunctionRegistry(DataFunctionRegistry functionRegistry) { - this.functionRegistry = functionRegistry; - } - - @Override - public DataStoreRegistry getDataStoreRegistry() { - return dataStoreRegistry; - } - - public void setDataStoreRegistry(DataStoreRegistry dataStoreRegistry) { - this.dataStoreRegistry = dataStoreRegistry; - } - - @Override - public ResultAdapterContext getResultAdapterContext() { - return resultAdapterContext; - } - - public void setResultAdapterContext(ResultAdapterContext resultAdapterContext) { - this.resultAdapterContext = resultAdapterContext; - } - - @Override - public TypeMappingContext getTypeMappingContext() { - return typeMappingContext; - } - - public void setTypeMappingContext(TypeMappingContext typeMappingContext) { - this.typeMappingContext = typeMappingContext; - } - - @Override - public DataStoreEventListenerContext getEventListenerContext() { - return eventListenerContext; - } - - public void setEventListenerContext(DataStoreEventListenerContext eventListenerContext) { - this.eventListenerContext = eventListenerContext; - } - - @Override - public NonDataOperationInvocationHandler getOperationInvocationHandler() { - return operationInvocationHandler; - } - - public void setOperationInvocationHandler(NonDataOperationInvocationHandler operationInvocationHandler) { - this.operationInvocationHandler = operationInvocationHandler; - } - - @Override - public KeyGenerator getDefaultKeyGenerator() { - return defaultKeyGenerator; - } - - public void setDefaultKeyGenerator(KeyGenerator defaultKeyGenerator) { - this.defaultKeyGenerator = defaultKeyGenerator; - } - + private RepositoryMetadataResolver repositoryMetadataResolver; + private MethodQueryDescriptionExtractor descriptionExtractor; + private DataFunctionRegistry functionRegistry; + private DataStoreRegistry dataStoreRegistry; + private ResultAdapterContext resultAdapterContext; + private TypeMappingContext typeMappingContext; + private DataStoreEventListenerContext eventListenerContext; + private NonDataOperationInvocationHandler operationInvocationHandler; + private KeyGenerator defaultKeyGenerator; + + public DefaultRepositoryFactoryConfiguration() {} + + public DefaultRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) { + this( + configuration.getRepositoryMetadataResolver(), + configuration.getDescriptionExtractor(), + configuration.getFunctionRegistry(), + configuration.getDataStoreRegistry(), + configuration.getResultAdapterContext(), + configuration.getTypeMappingContext(), + configuration.getEventListenerContext(), + configuration.getOperationInvocationHandler(), + configuration.getDefaultKeyGenerator()); + } + + public DefaultRepositoryFactoryConfiguration( + RepositoryMetadataResolver repositoryMetadataResolver, + MethodQueryDescriptionExtractor descriptionExtractor, + DataFunctionRegistry functionRegistry, + DataStoreRegistry dataStoreRegistry, + ResultAdapterContext resultAdapterContext, + TypeMappingContext typeMappingContext, + DataStoreEventListenerContext eventListenerContext, + NonDataOperationInvocationHandler operationInvocationHandler, + KeyGenerator defaultKeyGenerator) { + this.repositoryMetadataResolver = repositoryMetadataResolver; + this.descriptionExtractor = descriptionExtractor; + this.functionRegistry = functionRegistry; + this.dataStoreRegistry = dataStoreRegistry; + this.resultAdapterContext = resultAdapterContext; + this.typeMappingContext = typeMappingContext; + this.eventListenerContext = eventListenerContext; + this.operationInvocationHandler = operationInvocationHandler; + this.defaultKeyGenerator = defaultKeyGenerator; + } + + @Override + public RepositoryMetadataResolver getRepositoryMetadataResolver() { + return repositoryMetadataResolver; + } + + public void setRepositoryMetadataResolver(RepositoryMetadataResolver repositoryMetadataResolver) { + this.repositoryMetadataResolver = repositoryMetadataResolver; + } + + @Override + public MethodQueryDescriptionExtractor getDescriptionExtractor() { + return descriptionExtractor; + } + + public void setDescriptionExtractor(MethodQueryDescriptionExtractor descriptionExtractor) { + this.descriptionExtractor = descriptionExtractor; + } + + @Override + public DataFunctionRegistry getFunctionRegistry() { + return functionRegistry; + } + + public void setFunctionRegistry(DataFunctionRegistry functionRegistry) { + this.functionRegistry = functionRegistry; + } + + @Override + public DataStoreRegistry getDataStoreRegistry() { + return dataStoreRegistry; + } + + public void setDataStoreRegistry(DataStoreRegistry dataStoreRegistry) { + this.dataStoreRegistry = dataStoreRegistry; + } + + @Override + public ResultAdapterContext getResultAdapterContext() { + return resultAdapterContext; + } + + public void setResultAdapterContext(ResultAdapterContext resultAdapterContext) { + this.resultAdapterContext = resultAdapterContext; + } + + @Override + public TypeMappingContext getTypeMappingContext() { + return typeMappingContext; + } + + public void setTypeMappingContext(TypeMappingContext typeMappingContext) { + this.typeMappingContext = typeMappingContext; + } + + @Override + public DataStoreEventListenerContext getEventListenerContext() { + return eventListenerContext; + } + + public void setEventListenerContext(DataStoreEventListenerContext eventListenerContext) { + this.eventListenerContext = eventListenerContext; + } + + @Override + public NonDataOperationInvocationHandler getOperationInvocationHandler() { + return operationInvocationHandler; + } + + public void setOperationInvocationHandler( + NonDataOperationInvocationHandler operationInvocationHandler) { + this.operationInvocationHandler = operationInvocationHandler; + } + + @Override + public KeyGenerator getDefaultKeyGenerator() { + return defaultKeyGenerator; + } + + public void setDefaultKeyGenerator(KeyGenerator defaultKeyGenerator) { + this.defaultKeyGenerator = defaultKeyGenerator; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContext.java index 651cc94b..4df340a8 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContext.java @@ -4,7 +4,25 @@ import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException; import com.mmnaseri.utils.spring.data.proxy.ResultAdapter; import com.mmnaseri.utils.spring.data.proxy.ResultAdapterContext; -import com.mmnaseri.utils.spring.data.proxy.impl.adapters.*; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.CollectionIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.FutureIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.GeoPageIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.IteratorIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.ListenableFutureIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullSimpleResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToCollectionResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToFutureResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToIteratorResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToListenableFutureResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NullToSliceResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.NumberIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.OptionalResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.PageIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.SameTypeResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.SimpleIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.SliceIterableResultAdapter; +import com.mmnaseri.utils.spring.data.proxy.impl.adapters.VoidResultAdapter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -22,69 +40,68 @@ @SuppressWarnings("WeakerAccess") public class DefaultResultAdapterContext implements ResultAdapterContext { - private static final Log log = LogFactory.getLog(DefaultResultAdapterContext.class); - private final List> adapters; + private static final Log log = LogFactory.getLog(DefaultResultAdapterContext.class); + private final List> adapters; - /** - * Instantiates the context and registers all the default adapters. - */ - public DefaultResultAdapterContext() { - this(true); - } - - /** - * Instantiates the context - * - * @param registerDefaults whether default adapters should be registered by default. - */ - public DefaultResultAdapterContext(boolean registerDefaults) { - adapters = new ArrayList<>(); - if (registerDefaults) { - adapters.add(new VoidResultAdapter()); - adapters.add(new SameTypeResultAdapter()); - adapters.add(new NullSimpleResultAdapter()); - adapters.add(new NullToIteratorResultAdapter()); - adapters.add(new NullToCollectionResultAdapter()); - adapters.add(new NullToIterableResultAdapter()); - adapters.add(new NullToSliceResultAdapter()); - adapters.add(new NullToFutureResultAdapter()); - adapters.add(new NullToListenableFutureResultAdapter()); - adapters.add(new NumberIterableResultAdapter()); - adapters.add(new SimpleIterableResultAdapter()); - adapters.add(new IteratorIterableResultAdapter()); - adapters.add(new CollectionIterableResultAdapter()); - adapters.add(new SliceIterableResultAdapter()); - adapters.add(new PageIterableResultAdapter()); - adapters.add(new GeoPageIterableResultAdapter()); - adapters.add(new FutureIterableResultAdapter()); - adapters.add(new ListenableFutureIterableResultAdapter()); - Collections.sort(adapters); - } - } + /** Instantiates the context and registers all the default adapters. */ + public DefaultResultAdapterContext() { + this(true); + } - @Override - public synchronized void register(ResultAdapter adapter) { - log.info("Registering adapter " + adapter + " with the registry"); - adapters.add(adapter); - Collections.sort(adapters); + /** + * Instantiates the context + * + * @param registerDefaults whether default adapters should be registered by default. + */ + public DefaultResultAdapterContext(boolean registerDefaults) { + adapters = new ArrayList<>(); + if (registerDefaults) { + adapters.add(new VoidResultAdapter()); + adapters.add(new SameTypeResultAdapter()); + adapters.add(new NullSimpleResultAdapter()); + adapters.add(new NullToIteratorResultAdapter()); + adapters.add(new NullToCollectionResultAdapter()); + adapters.add(new NullToIterableResultAdapter()); + adapters.add(new NullToSliceResultAdapter()); + adapters.add(new NullToFutureResultAdapter()); + adapters.add(new NullToListenableFutureResultAdapter()); + adapters.add(new NumberIterableResultAdapter()); + adapters.add(new SimpleIterableResultAdapter()); + adapters.add(new OptionalResultAdapter()); + adapters.add(new IteratorIterableResultAdapter()); + adapters.add(new CollectionIterableResultAdapter()); + adapters.add(new SliceIterableResultAdapter()); + adapters.add(new PageIterableResultAdapter()); + adapters.add(new GeoPageIterableResultAdapter()); + adapters.add(new FutureIterableResultAdapter()); + adapters.add(new ListenableFutureIterableResultAdapter()); + Collections.sort(adapters); } + } - @Override - public Object adapt(Invocation invocation, Object originalResult) { - log.info("Adapting the result of invocation to type " + invocation.getMethod().getReturnType()); - for (ResultAdapter adapter : adapters) { - if (adapter.accepts(invocation, originalResult)) { - return adapter.adapt(invocation, originalResult); - } - } - log.error("Could not find any result adapter that was capable of adapting the result of the invocation to type " - + invocation.getMethod().getReturnType()); - throw new ResultAdapterFailureException(originalResult, invocation.getMethod().getReturnType()); - } + @Override + public synchronized void register(ResultAdapter adapter) { + log.info("Registering adapter " + adapter + " with the registry"); + adapters.add(adapter); + Collections.sort(adapters); + } - @Override - public Collection> getAdapters() { - return Collections.unmodifiableCollection(adapters); + @Override + public Object adapt(Invocation invocation, Object originalResult) { + log.info("Adapting the result of invocation to type " + invocation.getMethod().getReturnType()); + for (ResultAdapter adapter : adapters) { + if (adapter.accepts(invocation, originalResult)) { + return adapter.adapt(invocation, originalResult); + } } + log.error( + "Could not find any result adapter that was capable of adapting the result of the invocation to type " + + invocation.getMethod().getReturnType()); + throw new ResultAdapterFailureException(originalResult, invocation.getMethod().getReturnType()); + } + @Override + public Collection> getAdapters() { + return Collections.unmodifiableCollection(adapters); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContext.java index af8a7d51..e9a2eb57 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContext.java @@ -3,7 +3,11 @@ import com.mmnaseri.utils.spring.data.error.RepositoryDefinitionException; import com.mmnaseri.utils.spring.data.proxy.TypeMapping; import com.mmnaseri.utils.spring.data.proxy.TypeMappingContext; -import com.mmnaseri.utils.spring.data.repository.*; +import com.mmnaseri.utils.spring.data.repository.DefaultCrudRepository; +import com.mmnaseri.utils.spring.data.repository.DefaultGemfireRepository; +import com.mmnaseri.utils.spring.data.repository.DefaultJpaRepository; +import com.mmnaseri.utils.spring.data.repository.DefaultPagingAndSortingRepository; +import com.mmnaseri.utils.spring.data.repository.DefaultQueryByExampleExecutor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.annotation.AnnotationAwareOrderComparator; @@ -16,8 +20,8 @@ import java.util.concurrent.ConcurrentMap; /** - *

This is the default type mapping context that is also capable of registering the default mappings - * for the interfaces provided through Spring Data.

+ * This is the default type mapping context that is also capable of registering the default mappings + * for the interfaces provided through Spring Data. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/8/15) @@ -25,107 +29,114 @@ @SuppressWarnings("WeakerAccess") public class DefaultTypeMappingContext implements TypeMappingContext { - private static final Log log = LogFactory.getLog(DefaultTypeMappingContext.class); - private static final String GEMFIRE_SUPPORT_CLASS = "org.springframework.data.gemfire.repository.GemfireRepository"; - private static final String JPA_SUPPORT_CLASS = "org.springframework.data.jpa.repository.JpaRepository"; - private static final String QUERY_BY_EXAMPLE_SUPPORT_CLASS = - "org.springframework.data.repository.query.QueryByExampleExecutor"; - private final TypeMappingContext parent; - private final ConcurrentMap, List>> mappings = new ConcurrentHashMap<>(); + private static final Log log = LogFactory.getLog(DefaultTypeMappingContext.class); + private static final String GEMFIRE_SUPPORT_CLASS = + "org.springframework.data.gemfire.repository.GemfireRepository"; + private static final String JPA_SUPPORT_CLASS = + "org.springframework.data.jpa.repository.JpaRepository"; + private static final String QUERY_BY_EXAMPLE_SUPPORT_CLASS = + "org.springframework.data.repository.query.QueryByExampleExecutor"; + private final TypeMappingContext parent; + private final ConcurrentMap, List>> mappings = new ConcurrentHashMap<>(); - /** - * Instantiates the context and registers all the default converters - */ - public DefaultTypeMappingContext() { - this(true); - } + /** Instantiates the context and registers all the default converters */ + public DefaultTypeMappingContext() { + this(true); + } - /** - * Instantiates the context - * - * @param registerDefaults whether or not the default mappings should be registered. - */ - public DefaultTypeMappingContext(boolean registerDefaults) { - this(null); - if (registerDefaults) { - log.info("Trying to register all the default type mappings"); - if (isClassPresent(GEMFIRE_SUPPORT_CLASS)) { - log.debug("We seem to have Gemfire in the classpath, so, we should register the supporting registry"); - register(Object.class, DefaultGemfireRepository.class); - } - if (isClassPresent(JPA_SUPPORT_CLASS)) { - log.debug("JPA support is enabled in this project, so we need to support the methods"); - register(Object.class, DefaultJpaRepository.class); - } - if (isClassPresent(QUERY_BY_EXAMPLE_SUPPORT_CLASS)) { - log.debug("Query by example is enabled. We will the proper method implementations."); - register(Object.class, DefaultQueryByExampleExecutor.class); - } - register(Object.class, DefaultPagingAndSortingRepository.class); - register(Object.class, DefaultCrudRepository.class); - } + /** + * Instantiates the context + * + * @param registerDefaults whether or not the default mappings should be registered. + */ + public DefaultTypeMappingContext(boolean registerDefaults) { + this(null); + if (registerDefaults) { + log.info("Trying to register all the default type mappings"); + if (isClassPresent(GEMFIRE_SUPPORT_CLASS)) { + log.debug( + "We seem to have Gemfire in the classpath, so, we should register the supporting registry"); + register(Object.class, DefaultGemfireRepository.class); + } + if (isClassPresent(JPA_SUPPORT_CLASS)) { + log.debug("JPA support is enabled in this project, so we need to support the methods"); + register(Object.class, DefaultJpaRepository.class); + } + if (isClassPresent(QUERY_BY_EXAMPLE_SUPPORT_CLASS)) { + log.debug("Query by example is enabled. We will the proper method implementations."); + register(Object.class, DefaultQueryByExampleExecutor.class); + } + register(Object.class, DefaultPagingAndSortingRepository.class); + register(Object.class, DefaultCrudRepository.class); } + } - private boolean isClassPresent(String className) { - return ClassUtils.isPresent(className, ClassUtils.getDefaultClassLoader()); - } + public DefaultTypeMappingContext(TypeMappingContext parent) { + this.parent = parent; + } - public DefaultTypeMappingContext(TypeMappingContext parent) { - this.parent = parent; - } + private boolean isClassPresent(String className) { + return ClassUtils.isPresent(className, ClassUtils.getDefaultClassLoader()); + } - @Override - public void register(Class repositoryType, Class implementation) { - if (Modifier.isAbstract(implementation.getModifiers()) || Modifier.isInterface(implementation.getModifiers())) { - log.error("Cannot bind a non-concrete class as an implementation for a non-concrete class"); - throw new RepositoryDefinitionException(repositoryType, - "Cannot bind a non-concrete class as an implementation for a " - + "non-concrete class"); - } - log.info("Registering implementation " + implementation + " to super type " + repositoryType + - "; this means any repository of this type will inherit functionality defined in the " + - "bound implementation class."); - mappings.putIfAbsent(repositoryType, new LinkedList<>()); - mappings.get(repositoryType).add(implementation); + @Override + public void register(Class repositoryType, Class implementation) { + if (Modifier.isAbstract(implementation.getModifiers()) + || Modifier.isInterface(implementation.getModifiers())) { + log.error("Cannot bind a non-concrete class as an implementation for a non-concrete class"); + throw new RepositoryDefinitionException( + repositoryType, + "Cannot bind a non-concrete class as an implementation for a " + "non-concrete class"); } + log.info( + "Registering implementation " + + implementation + + " to super type " + + repositoryType + + "; this means any repository of this type will inherit functionality defined in the " + + "bound implementation class."); + mappings.putIfAbsent(repositoryType, new LinkedList<>()); + mappings.get(repositoryType).add(implementation); + } - @Override - public List> getImplementations(Class repositoryType) { - final List> classes = new LinkedList<>(); - for (Class repositorySuperType : mappings.keySet()) { - if (repositorySuperType.isAssignableFrom(repositoryType)) { - classes.addAll(mappings.get(repositorySuperType)); - } - } - classes.sort(AnnotationAwareOrderComparator.INSTANCE); - if (parent != null) { - classes.addAll(parent.getImplementations(repositoryType)); - } - return classes; + @Override + public List> getImplementations(Class repositoryType) { + final List> classes = new LinkedList<>(); + for (Class repositorySuperType : mappings.keySet()) { + if (repositorySuperType.isAssignableFrom(repositoryType)) { + classes.addAll(mappings.get(repositorySuperType)); + } } - - @Override - public List> getMappings(Class repositoryType) { - final List> typeMappings = new LinkedList<>(); - final List> implementations = getImplementations(repositoryType); - log.info("The repository " + repositoryType + " is bound to implementations " + implementations); - for (Class implementation : implementations) { - final Object instance; - try { - instance = implementation.getDeclaredConstructor().newInstance(); - } catch (IllegalAccessException e) { - log.error("The constructor for the implementation class is not accessible: " + implementation); - throw new RepositoryDefinitionException(repositoryType, - "Failed to access the constructor for " + implementation, e); - } catch (Exception e) { - log.error("The constructor for " + implementation + " threw an exception"); - throw new RepositoryDefinitionException(repositoryType, - "Constructor threw an exception " + implementation, e); - } - //noinspection unchecked - typeMappings.add(new ImmutableTypeMapping<>((Class) implementation, instance)); - } - return typeMappings; + classes.sort(AnnotationAwareOrderComparator.INSTANCE); + if (parent != null) { + classes.addAll(parent.getImplementations(repositoryType)); } + return classes; + } + @Override + public List> getMappings(Class repositoryType) { + final List> typeMappings = new LinkedList<>(); + final List> implementations = getImplementations(repositoryType); + log.info( + "The repository " + repositoryType + " is bound to implementations " + implementations); + for (Class implementation : implementations) { + final Object instance; + try { + instance = implementation.getDeclaredConstructor().newInstance(); + } catch (IllegalAccessException e) { + log.error( + "The constructor for the implementation class is not accessible: " + implementation); + throw new RepositoryDefinitionException( + repositoryType, "Failed to access the constructor for " + implementation, e); + } catch (Exception e) { + log.error("The constructor for " + implementation + " threw an exception"); + throw new RepositoryDefinitionException( + repositoryType, "Constructor threw an exception " + implementation, e); + } + //noinspection unchecked + typeMappings.add(new ImmutableTypeMapping<>((Class) implementation, instance)); + } + return typeMappings; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMapping.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMapping.java index a06cbf0b..ea4ddc15 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMapping.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMapping.java @@ -6,7 +6,7 @@ import java.lang.reflect.Method; /** - *

This class is an immutable invocation mapping.

+ * This class is an immutable invocation mapping. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) @@ -14,27 +14,26 @@ @SuppressWarnings("WeakerAccess") public class ImmutableInvocationMapping implements InvocationMapping { - private final Method method; - private final DataStoreOperation operation; + private final Method method; + private final DataStoreOperation operation; - public ImmutableInvocationMapping(Method method, DataStoreOperation operation) { - this.method = method; - this.operation = operation; - } + public ImmutableInvocationMapping(Method method, DataStoreOperation operation) { + this.method = method; + this.operation = operation; + } - @Override - public Method getMethod() { - return method; - } + @Override + public Method getMethod() { + return method; + } - @Override - public DataStoreOperation getOperation() { - return operation; - } - - @Override - public String toString() { - return method + " -> " + operation; - } + @Override + public DataStoreOperation getOperation() { + return operation; + } + @Override + public String toString() { + return method + " -> " + operation; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryConfiguration.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryConfiguration.java index 780a1a73..91e510cf 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryConfiguration.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryConfiguration.java @@ -7,37 +7,38 @@ import java.util.List; /** - *

This class is an immutable repository configuration.

+ * This class is an immutable repository configuration. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/12/15) */ public class ImmutableRepositoryConfiguration implements RepositoryConfiguration { - private final RepositoryMetadata repositoryMetadata; - private final KeyGenerator keyGenerator; - private final List> boundImplementations; - - public ImmutableRepositoryConfiguration(RepositoryMetadata repositoryMetadata, KeyGenerator keyGenerator, - List> boundImplementations) { - this.repositoryMetadata = repositoryMetadata; - this.keyGenerator = keyGenerator; - this.boundImplementations = boundImplementations; - } - - @Override - public RepositoryMetadata getRepositoryMetadata() { - return repositoryMetadata; - } - - @Override - public KeyGenerator getKeyGenerator() { - return keyGenerator; - } - - @Override - public List> getBoundImplementations() { - return boundImplementations; - } - + private final RepositoryMetadata repositoryMetadata; + private final KeyGenerator keyGenerator; + private final List> boundImplementations; + + public ImmutableRepositoryConfiguration( + RepositoryMetadata repositoryMetadata, + KeyGenerator keyGenerator, + List> boundImplementations) { + this.repositoryMetadata = repositoryMetadata; + this.keyGenerator = keyGenerator; + this.boundImplementations = boundImplementations; + } + + @Override + public RepositoryMetadata getRepositoryMetadata() { + return repositoryMetadata; + } + + @Override + public KeyGenerator getKeyGenerator() { + return keyGenerator; + } + + @Override + public List> getBoundImplementations() { + return boundImplementations; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfiguration.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfiguration.java index 619c4661..8dde8e3a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfiguration.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfiguration.java @@ -11,8 +11,8 @@ import com.mmnaseri.utils.spring.data.store.DataStoreRegistry; /** - *

This class is an immutable repository factory configuration insofar as the configuration itself is - * considered. The properties themselves won't be protected and are open to external change.

+ * This class is an immutable repository factory configuration insofar as the configuration itself + * is considered. The properties themselves won't be protected and are open to external change. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (4/12/16, 1:49 PM) @@ -20,88 +20,92 @@ @SuppressWarnings("WeakerAccess") public class ImmutableRepositoryFactoryConfiguration implements RepositoryFactoryConfiguration { - private final RepositoryMetadataResolver metadataResolver; - private final MethodQueryDescriptionExtractor queryDescriptionExtractor; - private final DataFunctionRegistry functionRegistry; - private final DataStoreRegistry dataStoreRegistry; - private final ResultAdapterContext resultAdapterContext; - private final TypeMappingContext typeMappingContext; - private final DataStoreEventListenerContext eventListenerContext; - private final NonDataOperationInvocationHandler operationInvocationHandler; - private final KeyGenerator keyGenerator; + private final RepositoryMetadataResolver metadataResolver; + private final MethodQueryDescriptionExtractor queryDescriptionExtractor; + private final DataFunctionRegistry functionRegistry; + private final DataStoreRegistry dataStoreRegistry; + private final ResultAdapterContext resultAdapterContext; + private final TypeMappingContext typeMappingContext; + private final DataStoreEventListenerContext eventListenerContext; + private final NonDataOperationInvocationHandler operationInvocationHandler; + private final KeyGenerator keyGenerator; - public ImmutableRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) { - this(configuration.getRepositoryMetadataResolver(), configuration.getDescriptionExtractor(), - configuration.getFunctionRegistry(), - configuration.getDataStoreRegistry(), configuration.getResultAdapterContext(), - configuration.getTypeMappingContext(), - configuration.getEventListenerContext(), configuration.getOperationInvocationHandler(), - configuration.getDefaultKeyGenerator()); - } + public ImmutableRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) { + this( + configuration.getRepositoryMetadataResolver(), + configuration.getDescriptionExtractor(), + configuration.getFunctionRegistry(), + configuration.getDataStoreRegistry(), + configuration.getResultAdapterContext(), + configuration.getTypeMappingContext(), + configuration.getEventListenerContext(), + configuration.getOperationInvocationHandler(), + configuration.getDefaultKeyGenerator()); + } - public ImmutableRepositoryFactoryConfiguration(RepositoryMetadataResolver metadataResolver, - MethodQueryDescriptionExtractor queryDescriptionExtractor, - DataFunctionRegistry functionRegistry, - DataStoreRegistry dataStoreRegistry, - ResultAdapterContext resultAdapterContext, - TypeMappingContext typeMappingContext, - DataStoreEventListenerContext eventListenerContext, - NonDataOperationInvocationHandler operationInvocationHandler, - KeyGenerator keyGenerator) { - this.metadataResolver = metadataResolver; - this.queryDescriptionExtractor = queryDescriptionExtractor; - this.functionRegistry = functionRegistry; - this.dataStoreRegistry = dataStoreRegistry; - this.resultAdapterContext = resultAdapterContext; - this.typeMappingContext = typeMappingContext; - this.eventListenerContext = eventListenerContext; - this.operationInvocationHandler = operationInvocationHandler; - this.keyGenerator = keyGenerator; - } + public ImmutableRepositoryFactoryConfiguration( + RepositoryMetadataResolver metadataResolver, + MethodQueryDescriptionExtractor queryDescriptionExtractor, + DataFunctionRegistry functionRegistry, + DataStoreRegistry dataStoreRegistry, + ResultAdapterContext resultAdapterContext, + TypeMappingContext typeMappingContext, + DataStoreEventListenerContext eventListenerContext, + NonDataOperationInvocationHandler operationInvocationHandler, + KeyGenerator keyGenerator) { + this.metadataResolver = metadataResolver; + this.queryDescriptionExtractor = queryDescriptionExtractor; + this.functionRegistry = functionRegistry; + this.dataStoreRegistry = dataStoreRegistry; + this.resultAdapterContext = resultAdapterContext; + this.typeMappingContext = typeMappingContext; + this.eventListenerContext = eventListenerContext; + this.operationInvocationHandler = operationInvocationHandler; + this.keyGenerator = keyGenerator; + } - @Override - public RepositoryMetadataResolver getRepositoryMetadataResolver() { - return metadataResolver; - } + @Override + public RepositoryMetadataResolver getRepositoryMetadataResolver() { + return metadataResolver; + } - @Override - public MethodQueryDescriptionExtractor getDescriptionExtractor() { - return queryDescriptionExtractor; - } + @Override + public MethodQueryDescriptionExtractor getDescriptionExtractor() { + return queryDescriptionExtractor; + } - @Override - public DataFunctionRegistry getFunctionRegistry() { - return functionRegistry; - } + @Override + public DataFunctionRegistry getFunctionRegistry() { + return functionRegistry; + } - @Override - public DataStoreRegistry getDataStoreRegistry() { - return dataStoreRegistry; - } + @Override + public DataStoreRegistry getDataStoreRegistry() { + return dataStoreRegistry; + } - @Override - public ResultAdapterContext getResultAdapterContext() { - return resultAdapterContext; - } + @Override + public ResultAdapterContext getResultAdapterContext() { + return resultAdapterContext; + } - @Override - public TypeMappingContext getTypeMappingContext() { - return typeMappingContext; - } + @Override + public TypeMappingContext getTypeMappingContext() { + return typeMappingContext; + } - @Override - public DataStoreEventListenerContext getEventListenerContext() { - return eventListenerContext; - } + @Override + public DataStoreEventListenerContext getEventListenerContext() { + return eventListenerContext; + } - @Override - public NonDataOperationInvocationHandler getOperationInvocationHandler() { - return operationInvocationHandler; - } - - @Override - public KeyGenerator getDefaultKeyGenerator() { - return keyGenerator; - } + @Override + public NonDataOperationInvocationHandler getOperationInvocationHandler() { + return operationInvocationHandler; + } + @Override + public KeyGenerator getDefaultKeyGenerator() { + return keyGenerator; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableTypeMapping.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableTypeMapping.java index 495aebc1..ce78fb98 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableTypeMapping.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableTypeMapping.java @@ -10,22 +10,21 @@ */ public class ImmutableTypeMapping implements TypeMapping { - private final Class type; - private final E instance; + private final Class type; + private final E instance; - public ImmutableTypeMapping(Class type, E instance) { - this.type = type; - this.instance = instance; - } + public ImmutableTypeMapping(Class type, E instance) { + this.type = type; + this.instance = instance; + } - @Override - public Class getType() { - return type; - } - - @Override - public E getInstance() { - return instance; - } + @Override + public Class getType() { + return type; + } + @Override + public E getInstance() { + return instance; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandler.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandler.java index e3d3814b..868bc4c7 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandler.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandler.java @@ -22,43 +22,42 @@ */ public class NonDataOperationInvocationHandler implements InvocationHandler { - private static final Log log = LogFactory.getLog(NonDataOperationInvocationHandler.class); - private final List handlers; - - public NonDataOperationInvocationHandler() { - this(true); + private static final Log log = LogFactory.getLog(NonDataOperationInvocationHandler.class); + private final List handlers; + + public NonDataOperationInvocationHandler() { + this(true); + } + + public NonDataOperationInvocationHandler(boolean registerDefaults) { + handlers = new LinkedList<>(); + if (registerDefaults) { + log.info("Registering all the default operation handlers"); + handlers.add(new EqualsNonDataOperationHandler()); + handlers.add(new HashCodeNonDataOperationHandler()); + handlers.add(new ToStringNonDataOperationHandler()); } - - public NonDataOperationInvocationHandler(boolean registerDefaults) { - handlers = new LinkedList<>(); - if (registerDefaults) { - log.info("Registering all the default operation handlers"); - handlers.add(new EqualsNonDataOperationHandler()); - handlers.add(new HashCodeNonDataOperationHandler()); - handlers.add(new ToStringNonDataOperationHandler()); - } + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) { + log.info("Intercepting non-data method " + method); + for (NonDataOperationHandler handler : handlers) { + if (handler.handles(proxy, method, args)) { + log.info("Found handler " + handler + " for method " + method); + return handler.invoke(proxy, args); + } } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) { - log.info("Intercepting non-data method " + method); - for (NonDataOperationHandler handler : handlers) { - if (handler.handles(proxy, method, args)) { - log.info("Found handler " + handler + " for method " + method); - return handler.invoke(proxy, args); - } - } - log.error("No data or non-data operation handler could be found for method " + method); - throw new UnknownDataOperationException(method); - } - - public void register(NonDataOperationHandler handler) { - log.info("Registering operation handler " + handler); - handlers.add(handler); - } - - public List getHandlers() { - return Collections.unmodifiableList(handlers); - } - + log.error("No data or non-data operation handler could be found for method " + method); + throw new UnknownDataOperationException(method); + } + + public void register(NonDataOperationHandler handler) { + log.info("Registering operation handler " + handler); + handlers.add(handler); + } + + public List getHandlers() { + return Collections.unmodifiableList(handlers); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractIterableResultAdapter.java index 325291ce..8bdfdebd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractIterableResultAdapter.java @@ -10,23 +10,22 @@ */ public abstract class AbstractIterableResultAdapter extends AbstractResultAdapter { - public AbstractIterableResultAdapter(int priority) { - super(priority); - } + public AbstractIterableResultAdapter(int priority) { + super(priority); + } - @Override - public E adapt(Invocation invocation, Object originalValue) { - final Iterable iterable = (Iterable) originalValue; - return doAdapt(invocation, iterable); - } - - /** - * This is called when we want to adapt an iterable object to another type. - * - * @param invocation the invocation which called for this adaptation - * @param iterable the iterable to be adapted to the appropriate result type - * @return the adapted result - */ - protected abstract E doAdapt(Invocation invocation, Iterable iterable); + @Override + public E adapt(Invocation invocation, Object originalValue) { + final Iterable iterable = (Iterable) originalValue; + return doAdapt(invocation, iterable); + } + /** + * This is called when we want to adapt an iterable object to another type. + * + * @param invocation the invocation which called for this adaptation + * @param iterable the iterable to be adapted to the appropriate result type + * @return the adapted result + */ + protected abstract E doAdapt(Invocation invocation, Iterable iterable); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractResultAdapter.java index 3ab1c31c..07fce3db 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/AbstractResultAdapter.java @@ -3,28 +3,27 @@ import com.mmnaseri.utils.spring.data.proxy.ResultAdapter; /** - *

This is the base class for all result adapters that adds comparison capabilities to teh adapters. - * This basically means that now adapters can be compared using their assigned priorities.

+ * This is the base class for all result adapters that adds comparison capabilities to teh adapters. + * This basically means that now adapters can be compared using their assigned priorities. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public abstract class AbstractResultAdapter implements ResultAdapter { - private final int priority; + private final int priority; - public AbstractResultAdapter(int priority) { - this.priority = priority; - } + public AbstractResultAdapter(int priority) { + this.priority = priority; + } - @Override - public int compareTo(ResultAdapter that) { - return Integer.compare(getPriority(), that.getPriority()); - } - - @Override - public int getPriority() { - return priority; - } + @Override + public int compareTo(ResultAdapter that) { + return Integer.compare(getPriority(), that.getPriority()); + } + @Override + public int getPriority() { + return priority; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapter.java index bcdb2260..230f5bbf 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapter.java @@ -7,39 +7,39 @@ import java.util.Collection; /** - *

This adapter will adapt results from an iterable to the appropriate collection type. It will accept - * adaptations if the original value is an iterable object and the target result is some sort {@link - * java.util.Collection collection}.

+ * This adapter will adapt results from an iterable to the appropriate collection type. It will + * accept adaptations if the original value is an iterable object and the target result is some sort + * {@link java.util.Collection collection}. * - *

This adapter will execute at priority {@literal -300}.

+ *

This adapter will execute at priority {@literal -300}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public class CollectionIterableResultAdapter extends AbstractIterableResultAdapter { - public CollectionIterableResultAdapter() { - super(-300); - } + public CollectionIterableResultAdapter() { + super(-300); + } - @Override - protected Collection doAdapt(Invocation invocation, Iterable iterable) { - final Collection collection; - try { - collection = CollectionInstanceUtils.getCollection(invocation.getMethod().getReturnType()); - } catch (IllegalArgumentException e) { - throw new ResultAdapterFailureException(iterable, invocation.getMethod().getReturnType(), e); - } - for (Object item : iterable) { - //noinspection unchecked - collection.add(item); - } - return collection; + @Override + protected Collection doAdapt(Invocation invocation, Iterable iterable) { + final Collection collection; + try { + collection = CollectionInstanceUtils.getCollection(invocation.getMethod().getReturnType()); + } catch (IllegalArgumentException e) { + throw new ResultAdapterFailureException(iterable, invocation.getMethod().getReturnType(), e); } - - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue instanceof Iterable && Collection.class.isAssignableFrom( - invocation.getMethod().getReturnType()); + for (Object item : iterable) { + //noinspection unchecked + collection.add(item); } + return collection; + } + + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue instanceof Iterable + && Collection.class.isAssignableFrom(invocation.getMethod().getReturnType()); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIterator.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIterator.java index c6ab21c2..72299ddd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIterator.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIterator.java @@ -10,24 +10,21 @@ */ public class EmptyIterator implements Iterator { - /** - * This is the shared instance of the empty iterator - */ - public static final EmptyIterator INSTANCE = new EmptyIterator(); + /** This is the shared instance of the empty iterator */ + public static final EmptyIterator INSTANCE = new EmptyIterator(); - @Override - public boolean hasNext() { - return false; - } + @Override + public boolean hasNext() { + return false; + } - @Override - public Object next() { - throw new IndexOutOfBoundsException(); - } - - @Override - public void remove() { - throw new IndexOutOfBoundsException(); - } + @Override + public Object next() { + throw new IndexOutOfBoundsException(); + } + @Override + public void remove() { + throw new IndexOutOfBoundsException(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapter.java index 0a3cdc9e..608bca1e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapter.java @@ -6,35 +6,35 @@ import java.util.concurrent.FutureTask; /** - *

This class will adapt results from an iterable object to a future. The future task returned will have already - * executed with the results available.

+ * This class will adapt results from an iterable object to a future. The future task returned will + * have already executed with the results available. * - *

It will accept adaptations wherein the original value is some sort of iterable and the required return type - * is an instance of {@link Future}. Remember that it does not check for individual object type - * compatibility.

+ *

It will accept adaptations wherein the original value is some sort of iterable and the + * required return type is an instance of {@link Future}. Remember that it does not check + * for individual object type compatibility. * - *

This adapter will execute at priority {@literal -100}.

+ *

This adapter will execute at priority {@literal -100}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public class FutureIterableResultAdapter extends AbstractIterableResultAdapter { - public FutureIterableResultAdapter() { - super(-100); - } + public FutureIterableResultAdapter() { + super(-100); + } - @Override - protected Future doAdapt(Invocation invocation, final Iterable iterable) { - //noinspection unchecked - final FutureTask task = new FutureTask(() -> iterable); - task.run(); - return task; - } - - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue instanceof Iterable && invocation.getMethod().getReturnType().equals(Future.class); - } + @Override + protected Future doAdapt(Invocation invocation, final Iterable iterable) { + //noinspection unchecked + final FutureTask task = new FutureTask(() -> iterable); + task.run(); + return task; + } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue instanceof Iterable + && invocation.getMethod().getReturnType().equals(Future.class); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapter.java index 249c658c..c5f60952 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapter.java @@ -8,38 +8,37 @@ import java.util.List; /** - *

This class will adapt results from an iterable object to a geo page.

+ * This class will adapt results from an iterable object to a geo page. * - *

It will accept adaptations wherein the original value is some sort of iterable and the required return type - * is an instance of {@link GeoPage}. Remember that it does not check for individual object type - * compatibility.

+ *

It will accept adaptations wherein the original value is some sort of iterable and the + * required return type is an instance of {@link GeoPage}. Remember that it does not check + * for individual object type compatibility. * - *

This adapter will execute at priority {@literal -150}.

+ *

This adapter will execute at priority {@literal -150}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public class GeoPageIterableResultAdapter extends AbstractIterableResultAdapter { - public GeoPageIterableResultAdapter() { - super(-150); - } - - @Override - protected GeoPage doAdapt(Invocation invocation, Iterable iterable) { - final List content = new ArrayList(); - for (Object item : iterable) { - //noinspection unchecked - content.add(item); - } - //noinspection unchecked - return new GeoPage(new GeoResults(content)); - } + public GeoPageIterableResultAdapter() { + super(-150); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue instanceof Iterable && invocation.getMethod().getReturnType() - .equals(GeoPage.class); + @Override + protected GeoPage doAdapt(Invocation invocation, Iterable iterable) { + final List content = new ArrayList(); + for (Object item : iterable) { + //noinspection unchecked + content.add(item); } + //noinspection unchecked + return new GeoPage(new GeoResults(content)); + } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue instanceof Iterable + && invocation.getMethod().getReturnType().equals(GeoPage.class); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapter.java index f1245347..2a61d3a9 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapter.java @@ -5,32 +5,31 @@ import java.util.Iterator; /** - *

This class will adapt results from an iterable object to an iterator.

+ * This class will adapt results from an iterable object to an iterator. * - *

It will accept adaptations wherein the original value is some sort of iterable and the required return type - * is an instance of {@link Iterator}. Remember that it does not check for individual object type - * compatibility.

+ *

It will accept adaptations wherein the original value is some sort of iterable and the + * required return type is an instance of {@link Iterator}. Remember that it does not check + * for individual object type compatibility. * - *

This adapter will execute at priority {@literal -350}.

+ *

This adapter will execute at priority {@literal -350}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public class IteratorIterableResultAdapter extends AbstractIterableResultAdapter { - public IteratorIterableResultAdapter() { - super(-350); - } + public IteratorIterableResultAdapter() { + super(-350); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue instanceof Iterable && Iterator.class.equals( - invocation.getMethod().getReturnType()); - } - - @Override - protected Iterator doAdapt(Invocation invocation, Iterable iterable) { - return iterable.iterator(); - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue instanceof Iterable + && Iterator.class.equals(invocation.getMethod().getReturnType()); + } + @Override + protected Iterator doAdapt(Invocation invocation, Iterable iterable) { + return iterable.iterator(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapter.java index 649b250f..73b224de 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapter.java @@ -7,36 +7,35 @@ import java.util.concurrent.Callable; /** - *

This class will adapt results from an iterable object to a listenable future. The future task returned - * will have already - * executed with the results available.

+ * This class will adapt results from an iterable object to a listenable future. The future + * task returned will have already executed with the results available. * - *

It will accept adaptations wherein the original value is some sort of iterable and the required return type - * is an instance of {@link ListenableFuture}. Remember that it does not check for individual object type - * compatibility.

+ *

It will accept adaptations wherein the original value is some sort of iterable and the + * required return type is an instance of {@link ListenableFuture}. Remember that it does + * not check for individual object type compatibility. * - *

This adapter will execute at priority {@literal -50}.

+ *

This adapter will execute at priority {@literal -50}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ -public class ListenableFutureIterableResultAdapter extends AbstractIterableResultAdapter { +public class ListenableFutureIterableResultAdapter + extends AbstractIterableResultAdapter { - public ListenableFutureIterableResultAdapter() { - super(-50); - } + public ListenableFutureIterableResultAdapter() { + super(-50); + } - @Override - protected ListenableFuture doAdapt(Invocation invocation, final Iterable iterable) { - final ListenableFutureTask task = new ListenableFutureTask<>((Callable) () -> iterable); - task.run(); - return task; - } - - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue instanceof Iterable && invocation.getMethod().getReturnType() - .equals(ListenableFuture.class); - } + @Override + protected ListenableFuture doAdapt(Invocation invocation, final Iterable iterable) { + final ListenableFutureTask task = new ListenableFutureTask<>((Callable) () -> iterable); + task.run(); + return task; + } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue instanceof Iterable + && invocation.getMethod().getReturnType().equals(ListenableFuture.class); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapter.java index 9a95862c..b23d92ef 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapter.java @@ -7,37 +7,36 @@ import java.util.concurrent.Future; /** - *

This adapter will try to adapt a {@literal null} value to a simple value. Simple here is defined as anything - * that is not an iterable, an iterator, or a future promise.

+ * This adapter will try to adapt a {@literal null} value to a simple value. Simple here is defined + * as anything that is not an iterable, an iterator, or a future promise. * - *

It adapts results if the return type is simple and the original value is {@literal null}.

+ *

It adapts results if the return type is simple and the original value is {@literal null}. * - *

This adapter runs at the priority of {@literal -400}.

+ *

This adapter runs at the priority of {@literal -400}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public class NullSimpleResultAdapter extends AbstractResultAdapter { - public NullSimpleResultAdapter() { - super(-400); - } + public NullSimpleResultAdapter() { + super(-400); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - final Class returnType = invocation.getMethod().getReturnType(); - return !Iterable.class.isAssignableFrom(returnType) && - !Iterator.class.isAssignableFrom(returnType) && - !Future.class.isAssignableFrom(returnType) && - originalValue == null; - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + final Class returnType = invocation.getMethod().getReturnType(); + return !Iterable.class.isAssignableFrom(returnType) + && !Iterator.class.isAssignableFrom(returnType) + && !Future.class.isAssignableFrom(returnType) + && originalValue == null; + } - @Override - public Object adapt(Invocation invocation, Object originalValue) { - if (invocation.getMethod().getReturnType().isPrimitive()) { - throw new ResultAdapterFailureException(null, invocation.getMethod().getReturnType()); - } - return null; + @Override + public Object adapt(Invocation invocation, Object originalValue) { + if (invocation.getMethod().getReturnType().isPrimitive()) { + throw new ResultAdapterFailureException(null, invocation.getMethod().getReturnType()); } - + return null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapter.java index be5a954b..2512a30b 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapter.java @@ -6,29 +6,30 @@ import java.util.Collection; /** - *

This adapter will try to adapt a {@literal null} value to a collection.

+ * This adapter will try to adapt a {@literal null} value to a collection. * - *

It adapts results if the return type is of type {@link Collection} and the original value is {@literal null}.

+ *

It adapts results if the return type is of type {@link Collection} and the original value is + * {@literal null}. * - *

This adapter runs at the priority of {@literal -300}.

+ *

This adapter runs at the priority of {@literal -300}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public class NullToCollectionResultAdapter extends AbstractResultAdapter { - public NullToCollectionResultAdapter() { - super(-300); - } + public NullToCollectionResultAdapter() { + super(-300); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue == null && Collection.class.isAssignableFrom(invocation.getMethod().getReturnType()); - } - - @Override - public Collection adapt(Invocation invocation, Object originalValue) { - return CollectionInstanceUtils.getCollection(invocation.getMethod().getReturnType()); - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue == null + && Collection.class.isAssignableFrom(invocation.getMethod().getReturnType()); + } + @Override + public Collection adapt(Invocation invocation, Object originalValue) { + return CollectionInstanceUtils.getCollection(invocation.getMethod().getReturnType()); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapter.java index 1442e9dd..250ff7ad 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapter.java @@ -6,32 +6,32 @@ import java.util.concurrent.FutureTask; /** - *

This adapter will try to adapt a {@literal null} value to a future.

+ * This adapter will try to adapt a {@literal null} value to a future. * - *

It adapts results if the return type is of type {@link Future} and the original value is {@literal null}.

+ *

It adapts results if the return type is of type {@link Future} and the original value is + * {@literal null}. * - *

This adapter runs at the priority of {@literal -150}.

+ *

This adapter runs at the priority of {@literal -150}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public class NullToFutureResultAdapter extends AbstractResultAdapter { - public NullToFutureResultAdapter() { - super(-150); - } + public NullToFutureResultAdapter() { + super(-150); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue == null && invocation.getMethod().getReturnType().equals(Future.class); - } - - @Override - public Future adapt(Invocation invocation, Object originalValue) { - //noinspection unchecked - final FutureTask task = new FutureTask(() -> null); - task.run(); - return task; - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue == null && invocation.getMethod().getReturnType().equals(Future.class); + } + @Override + public Future adapt(Invocation invocation, Object originalValue) { + //noinspection unchecked + final FutureTask task = new FutureTask(() -> null); + task.run(); + return task; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapter.java index 7d1e3b87..9d877251 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapter.java @@ -5,29 +5,29 @@ import java.util.Collections; /** - *

This adapter will try to adapt a {@literal null} value to an iterable.

+ * This adapter will try to adapt a {@literal null} value to an iterable. * - *

It adapts results if the return type is of type {@link Iterable} and the original value is {@literal null}.

+ *

It adapts results if the return type is of type {@link Iterable} and the original value is + * {@literal null}. * - *

This adapter runs at the priority of {@literal -250}.

+ *

This adapter runs at the priority of {@literal -250}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public class NullToIterableResultAdapter extends AbstractResultAdapter { - public NullToIterableResultAdapter() { - super(-250); - } + public NullToIterableResultAdapter() { + super(-250); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return invocation.getMethod().getReturnType().equals(Iterable.class) && originalValue == null; - } - - @Override - public Iterable adapt(Invocation invocation, Object originalValue) { - return Collections.emptyList(); - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return invocation.getMethod().getReturnType().equals(Iterable.class) && originalValue == null; + } + @Override + public Iterable adapt(Invocation invocation, Object originalValue) { + return Collections.emptyList(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapter.java index 9f407bcb..99d30fb6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapter.java @@ -5,29 +5,29 @@ import java.util.Iterator; /** - *

This adapter will try to adapt a {@literal null} value to an iterator.

+ * This adapter will try to adapt a {@literal null} value to an iterator. * - *

It adapts results if the return type is of type {@link Iterator} and the original value is {@literal null}.

+ *

It adapts results if the return type is of type {@link Iterator} and the original value is + * {@literal null}. * - *

This adapter runs at the priority of {@literal -350}.

+ *

This adapter runs at the priority of {@literal -350}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public class NullToIteratorResultAdapter extends AbstractResultAdapter { - public NullToIteratorResultAdapter() { - super(-350); - } + public NullToIteratorResultAdapter() { + super(-350); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue == null && Iterator.class.equals(invocation.getMethod().getReturnType()); - } - - @Override - public Iterator adapt(Invocation invocation, Object originalValue) { - return EmptyIterator.INSTANCE; - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue == null && Iterator.class.equals(invocation.getMethod().getReturnType()); + } + @Override + public Iterator adapt(Invocation invocation, Object originalValue) { + return EmptyIterator.INSTANCE; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapter.java index 298e648b..f0c4e184 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapter.java @@ -5,33 +5,33 @@ import org.springframework.util.concurrent.ListenableFutureTask; /** - *

This adapter will try to adapt a {@literal null} value to a listenable future.

+ * This adapter will try to adapt a {@literal null} value to a listenable future. * - *

It adapts results if the return type is of type {@link ListenableFuture} and the original value is {@literal - * null}.

+ *

It adapts results if the return type is of type {@link ListenableFuture} and the original + * value is {@literal null}. * - *

This adapter runs at the priority of {@literal -100}.

+ *

This adapter runs at the priority of {@literal -100}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public class NullToListenableFutureResultAdapter extends AbstractResultAdapter { - public NullToListenableFutureResultAdapter() { - super(-100); - } + public NullToListenableFutureResultAdapter() { + super(-100); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue == null && invocation.getMethod().getReturnType().equals(ListenableFuture.class); - } - - @Override - public ListenableFuture adapt(Invocation invocation, Object originalValue) { - //noinspection unchecked - final ListenableFutureTask task = new ListenableFutureTask(() -> null); - task.run(); - return task; - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue == null + && invocation.getMethod().getReturnType().equals(ListenableFuture.class); + } + @Override + public ListenableFuture adapt(Invocation invocation, Object originalValue) { + //noinspection unchecked + final ListenableFutureTask task = new ListenableFutureTask(() -> null); + task.run(); + return task; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapter.java index b9972355..7d7a23bd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapter.java @@ -8,30 +8,31 @@ import java.util.Collections; /** - *

This adapter will try to adapt a {@literal null} value to a slice.

+ * This adapter will try to adapt a {@literal null} value to a slice. * - *

It adapts results if the return type is of type {@link Slice} and the original value is {@literal null}.

+ *

It adapts results if the return type is of type {@link Slice} and the original value is + * {@literal null}. * - *

This adapter runs at the priority of {@literal -200}.

+ *

This adapter runs at the priority of {@literal -200}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public class NullToSliceResultAdapter extends AbstractResultAdapter { - public NullToSliceResultAdapter() { - super(-200); - } + public NullToSliceResultAdapter() { + super(-200); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue == null && Slice.class.isAssignableFrom(invocation.getMethod().getReturnType()); - } - - @Override - public Slice adapt(Invocation invocation, Object originalValue) { - //noinspection unchecked - return new GeoPage(new GeoResults(Collections.emptyList())); - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue == null + && Slice.class.isAssignableFrom(invocation.getMethod().getReturnType()); + } + @Override + public Slice adapt(Invocation invocation, Object originalValue) { + //noinspection unchecked + return new GeoPage(new GeoResults(Collections.emptyList())); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapter.java index 4b1cb47b..4087b7b9 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapter.java @@ -7,74 +7,74 @@ import java.util.Iterator; /** - *

This class will adapt results from an iterable object to a number. The future task returned will have already - * executed with the results available.

+ * This class will adapt results from an iterable object to a number. The future task returned will + * have already executed with the results available. * - *

It will accept adaptations wherein the original value is some sort of iterable and the required return type - * is an instance of {@link Number}. Additionally, it will check to see if the iterable yields only one item and also - * that the item is a number.

+ *

It will accept adaptations wherein the original value is some sort of iterable and the + * required return type is an instance of {@link Number}. Additionally, it will check to see if the + * iterable yields only one item and also that the item is a number. * - *

Here is a list of supported number types:

+ *

Here is a list of supported number types: * *

    - *
  • {@link Long}
  • - *
  • {@link Short}
  • - *
  • {@link Integer}
  • - *
  • {@link Byte}
  • - *
  • {@link Double}
  • - *
  • {@link Float}
  • + *
  • {@link Long} + *
  • {@link Short} + *
  • {@link Integer} + *
  • {@link Byte} + *
  • {@link Double} + *
  • {@link Float} *
* - *

This adapter will execute at priority {@literal -425}.

+ *

This adapter will execute at priority {@literal -425}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/12/15) */ public class NumberIterableResultAdapter extends AbstractIterableResultAdapter { - public NumberIterableResultAdapter() { - super(-425); - } + public NumberIterableResultAdapter() { + super(-425); + } - @Override - protected Object doAdapt(Invocation invocation, Iterable iterable) { - final Iterator iterator = iterable.iterator(); - final Object value = iterator.next(); - final Number number = (Number) value; - final Class returnType = PropertyUtils.getTypeOf(invocation.getMethod().getReturnType()); - if (Long.class.equals(returnType)) { - return number.longValue(); - } else if (Short.class.equals(returnType)) { - return number.shortValue(); - } else if (Integer.class.equals(returnType)) { - return number.intValue(); - } else if (Byte.class.equals(returnType)) { - return number.byteValue(); - } else if (Double.class.equals(returnType)) { - return number.doubleValue(); - } else if (Float.class.equals(returnType)) { - return number.floatValue(); - } - throw new ResultAdapterFailureException(value, returnType); + @Override + protected Object doAdapt(Invocation invocation, Iterable iterable) { + final Iterator iterator = iterable.iterator(); + final Object value = iterator.next(); + final Number number = (Number) value; + final Class returnType = PropertyUtils.getTypeOf(invocation.getMethod().getReturnType()); + if (Long.class.equals(returnType)) { + return number.longValue(); + } else if (Short.class.equals(returnType)) { + return number.shortValue(); + } else if (Integer.class.equals(returnType)) { + return number.intValue(); + } else if (Byte.class.equals(returnType)) { + return number.byteValue(); + } else if (Double.class.equals(returnType)) { + return number.doubleValue(); + } else if (Float.class.equals(returnType)) { + return number.floatValue(); } + throw new ResultAdapterFailureException(value, returnType); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - if (originalValue == null) { - return false; - } - if (!Number.class.isAssignableFrom(PropertyUtils.getTypeOf(invocation.getMethod().getReturnType()))) { - return false; - } - if (originalValue instanceof Iterable) { - Iterable iterable = (Iterable) originalValue; - final Iterator iterator = iterable.iterator(); - if (iterator.hasNext()) { - final Object value = iterator.next(); - return value instanceof Number && !iterator.hasNext(); - } - } - return false; + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + if (originalValue == null) { + return false; } - + if (!Number.class.isAssignableFrom( + PropertyUtils.getTypeOf(invocation.getMethod().getReturnType()))) { + return false; + } + if (originalValue instanceof Iterable) { + Iterable iterable = (Iterable) originalValue; + final Iterator iterator = iterable.iterator(); + if (iterator.hasNext()) { + final Object value = iterator.next(); + return value instanceof Number && !iterator.hasNext(); + } + } + return false; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/OptionalResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/OptionalResultAdapter.java new file mode 100644 index 00000000..fe2c1636 --- /dev/null +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/OptionalResultAdapter.java @@ -0,0 +1,52 @@ +package com.mmnaseri.utils.spring.data.proxy.impl.adapters; + +import com.mmnaseri.utils.spring.data.domain.Invocation; +import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException; + +import java.util.Iterator; +import java.util.Optional; + +/** + * This adapter accepts all invocations wherein the original value is an {@link Iterable} object and + * the requested method type is an {@link Optional} value. + * + *

While adapting, the adapter will also check that the iterable yields only one item and that it + * is of the same type or of a child type of the type requested by the invoked method. + * + *

This adapter runs at the priority {@literal -400}. + * + * @author Milad Naseri (m.m.naseri@gmail.com) + * @since 2.1.1 (10/29/2020) + */ +public class OptionalResultAdapter extends AbstractIterableResultAdapter { + + public OptionalResultAdapter() { + super(-400); + } + + @Override + public boolean accepts(final Invocation invocation, final Object originalValue) { + if (!(originalValue instanceof Iterable)) { + return false; + } + final Class returnType = invocation.getMethod().getReturnType(); + return returnType.isAssignableFrom(Optional.class); + } + + @Override + protected Object doAdapt(final Invocation invocation, final Iterable iterable) { + final Iterator iterator = iterable.iterator(); + if (iterator.hasNext()) { + final Object value = iterator.next(); + if (iterator.hasNext()) { + throw new ResultAdapterFailureException( + iterable, + invocation.getMethod().getReturnType(), + "Expected only one item but found many"); + } + return Optional.of(value); + } else { + return Optional.empty(); + } + } +} diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapter.java index 3e2f5e88..17442409 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapter.java @@ -8,38 +8,37 @@ import java.util.List; /** - *

This class will adapt results from an iterable object to a page.

+ * This class will adapt results from an iterable object to a page. * - *

It will accept adaptations wherein the original value is some sort of iterable and the required return type - * is an instance of {@link Page}. Remember that it does not check for individual object type - * compatibility.

+ *

It will accept adaptations wherein the original value is some sort of iterable and the + * required return type is an instance of {@link Page}. Remember that it does not check for + * individual object type compatibility. * - *

This adapter will execute at priority {@literal -200}.

+ *

This adapter will execute at priority {@literal -200}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public class PageIterableResultAdapter extends AbstractIterableResultAdapter { - public PageIterableResultAdapter() { - super(-200); - } - - @Override - protected Page doAdapt(Invocation invocation, Iterable iterable) { - final List content = new ArrayList(); - for (Object item : iterable) { - //noinspection unchecked - content.add(item); - } - //noinspection unchecked - return new PageImpl(content); - } + public PageIterableResultAdapter() { + super(-200); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue instanceof Iterable && invocation.getMethod().getReturnType() - .equals(Page.class); + @Override + protected Page doAdapt(Invocation invocation, Iterable iterable) { + final List content = new ArrayList(); + for (Object item : iterable) { + //noinspection unchecked + content.add(item); } + //noinspection unchecked + return new PageImpl(content); + } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue instanceof Iterable + && invocation.getMethod().getReturnType().equals(Page.class); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SameTypeResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SameTypeResultAdapter.java index 734c9f96..c7171fac 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SameTypeResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SameTypeResultAdapter.java @@ -3,28 +3,28 @@ import com.mmnaseri.utils.spring.data.domain.Invocation; /** - *

This adapter will accept and adapt results when the request result type is of the same type or a super - * type of the available value.

+ * This adapter will accept and adapt results when the request result type is of the same type or a + * super type of the available value. * - *

This adapter runs at priority {@literal -500}.

+ *

This adapter runs at priority {@literal -500}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public class SameTypeResultAdapter extends AbstractResultAdapter { - public SameTypeResultAdapter() { - super(-500); - } + public SameTypeResultAdapter() { + super(-500); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue != null && invocation.getMethod().getReturnType().isInstance(originalValue); - } - - @Override - public Object adapt(Invocation invocation, Object originalValue) { - return originalValue; - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue != null + && invocation.getMethod().getReturnType().isInstance(originalValue); + } + @Override + public Object adapt(Invocation invocation, Object originalValue) { + return originalValue; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapter.java index ef6bf598..21a83202 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapter.java @@ -5,55 +5,60 @@ import com.mmnaseri.utils.spring.data.tools.PropertyUtils; import java.util.Iterator; +import java.util.Optional; import java.util.concurrent.Future; /** - *

This adapter accepts all invocations wherein the original value is an {@link Iterable} object and - * the requested method type is a simple value. Simple types are types that are not a subtype of {@link Iterable}, - * {@link Iterator}, or {@link Future}.

+ * This adapter accepts all invocations wherein the original value is an {@link Iterable} object and + * the requested method type is a simple value. Simple types are types that are not a subtype of + * {@link Iterable}, {@link Iterator}, {@link Future}, or {@link Optional}. * - *

While adapting, the adapter will also check that the iterable yields only one item and that it is - * of the same type or of a child type of the type requested by the invoked method.

+ *

While adapting, the adapter will also check that the iterable yields only one item and that it + * is of the same type or of a child type of the type requested by the invoked method. * - *

This adapter runs at the priority {@literal -400}.

+ *

This adapter runs at the priority {@literal -400}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public class SimpleIterableResultAdapter extends AbstractIterableResultAdapter { - public SimpleIterableResultAdapter() { - super(-400); - } + public SimpleIterableResultAdapter() { + super(-400); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - if (!(originalValue instanceof Iterable)) { - return false; - } - final Class returnType = invocation.getMethod().getReturnType(); - return !Iterable.class.isAssignableFrom(returnType) && - !Iterator.class.isAssignableFrom(returnType) && - !Future.class.isAssignableFrom(returnType); + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + if (!(originalValue instanceof Iterable)) { + return false; } + final Class returnType = invocation.getMethod().getReturnType(); + return !Iterable.class.isAssignableFrom(returnType) + && !Iterator.class.isAssignableFrom(returnType) + && !Future.class.isAssignableFrom(returnType) + && !Optional.class.isAssignableFrom(returnType); + } - @Override - protected Object doAdapt(Invocation invocation, Iterable iterable) { - final Iterator iterator = iterable.iterator(); - if (iterator.hasNext()) { - final Object value = iterator.next(); - if (iterator.hasNext()) { - throw new ResultAdapterFailureException(iterable, invocation.getMethod().getReturnType(), - "Expected only one item but found many"); - } - if (!PropertyUtils.getTypeOf(invocation.getMethod().getReturnType()).isInstance(value)) { - throw new ResultAdapterFailureException(value, invocation.getMethod().getReturnType(), - "Expected value to be of the indicated type"); - } - return value; - } else { - return null; - } + @Override + protected Object doAdapt(Invocation invocation, Iterable iterable) { + final Iterator iterator = iterable.iterator(); + if (iterator.hasNext()) { + final Object value = iterator.next(); + if (iterator.hasNext()) { + throw new ResultAdapterFailureException( + iterable, + invocation.getMethod().getReturnType(), + "Expected only one item but found many"); + } + if (!PropertyUtils.getTypeOf(invocation.getMethod().getReturnType()).isInstance(value)) { + throw new ResultAdapterFailureException( + value, + invocation.getMethod().getReturnType(), + "Expected value to be of the indicated type"); + } + return value; + } else { + return null; } - + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapter.java index 978b2098..c7d9c452 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapter.java @@ -8,38 +8,37 @@ import java.util.List; /** - *

This class will adapt results from an iterable object to a slice.

+ * This class will adapt results from an iterable object to a slice. * - *

It will accept adaptations wherein the original value is some sort of iterable and the required return type - * is an instance of {@link Slice}. Remember that it does not check for individual object type - * compatibility.

+ *

It will accept adaptations wherein the original value is some sort of iterable and the + * required return type is an instance of {@link Slice}. Remember that it does not check + * for individual object type compatibility. * - *

This adapter will execute at priority {@literal -250}.

+ *

This adapter will execute at priority {@literal -250}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) */ public class SliceIterableResultAdapter extends AbstractIterableResultAdapter { - public SliceIterableResultAdapter() { - super(-250); - } - - @Override - protected Slice doAdapt(Invocation invocation, Iterable iterable) { - final List content = new ArrayList(); - for (Object item : iterable) { - //noinspection unchecked - content.add(item); - } - //noinspection unchecked - return new SliceImpl(content); - } + public SliceIterableResultAdapter() { + super(-250); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return originalValue instanceof Iterable && invocation.getMethod().getReturnType() - .equals(Slice.class); + @Override + protected Slice doAdapt(Invocation invocation, Iterable iterable) { + final List content = new ArrayList(); + for (Object item : iterable) { + //noinspection unchecked + content.add(item); } + //noinspection unchecked + return new SliceImpl(content); + } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return originalValue instanceof Iterable + && invocation.getMethod().getReturnType().equals(Slice.class); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapter.java index 5283a29b..78240143 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapter.java @@ -3,28 +3,27 @@ import com.mmnaseri.utils.spring.data.domain.Invocation; /** - *

This adapter is used to adapt any value to the method type of {@literal void} by returning - * {@literal null}.

+ * This adapter is used to adapt any value to the method type of {@literal void} by returning + * {@literal null}. * - *

This adapter is executed at {@link Integer#MIN_VALUE the lowest possible priority}.

+ *

This adapter is executed at {@link Integer#MIN_VALUE the lowest possible priority}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/24/15) */ public class VoidResultAdapter extends AbstractResultAdapter { - public VoidResultAdapter() { - super(Integer.MIN_VALUE); - } + public VoidResultAdapter() { + super(Integer.MIN_VALUE); + } - @Override - public boolean accepts(Invocation invocation, Object originalValue) { - return void.class.equals(invocation.getMethod().getReturnType()); - } - - @Override - public Object adapt(Invocation invocation, Object originalValue) { - return null; - } + @Override + public boolean accepts(Invocation invocation, Object originalValue) { + return void.class.equals(invocation.getMethod().getReturnType()); + } + @Override + public Object adapt(Invocation invocation, Object originalValue) { + return null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverter.java index 256ae5eb..ce304529 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverter.java @@ -4,7 +4,8 @@ import com.mmnaseri.utils.spring.data.proxy.ResultConverter; /** - * This class will let us convert non-{@literal null} values if the invocation is not of type {@literal void}. + * This class will let us convert non-{@literal null} values if the invocation is not of type + * {@literal void}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @see #doConvert(Invocation, Object) @@ -12,24 +13,23 @@ */ public abstract class AbstractResultConverter implements ResultConverter { - @Override - public Object convert(Invocation invocation, Object original) { - if (original == null || invocation.getMethod().getReturnType().equals(void.class)) { - return null; - } - if (invocation.getMethod().getReturnType().isInstance(original)) { - return original; - } - return doConvert(invocation, original); + @Override + public Object convert(Invocation invocation, Object original) { + if (original == null || invocation.getMethod().getReturnType().equals(void.class)) { + return null; } + if (invocation.getMethod().getReturnType().isInstance(original)) { + return original; + } + return doConvert(invocation, original); + } - /** - * Called to invoke a conversion of the given value to the desired result value. - * - * @param invocation the invocation - * @param original the original value - * @return the converted value - */ - protected abstract Object doConvert(Invocation invocation, Object original); - + /** + * Called to invoke a conversion of the given value to the desired result value. + * + * @param invocation the invocation + * @param original the original value + * @return the converted value + */ + protected abstract Object doConvert(Invocation invocation, Object original); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/DefaultResultConverter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/DefaultResultConverter.java index 297af61f..665701c2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/DefaultResultConverter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/DefaultResultConverter.java @@ -7,13 +7,13 @@ import java.util.List; /** - *

This class is the default result converter that also acts as a registry for other converters. It will - * execute the default converters in the following order

+ * This class is the default result converter that also acts as a registry for other converters. It + * will execute the default converters in the following order * *
    - *
  1. {@link FutureToIterableConverter}
  2. - *
  3. {@link IteratorToIterableConverter}
  4. - *
  5. {@link SingleValueToIterableConverter}
  6. + *
  7. {@link FutureToIterableConverter} + *
  8. {@link IteratorToIterableConverter} + *
  9. {@link SingleValueToIterableConverter} *
* * @author Milad Naseri (m.m.naseri@gmail.com) @@ -22,36 +22,33 @@ @SuppressWarnings("WeakerAccess") public class DefaultResultConverter implements ResultConverter { - private final List converters; - - /** - * Instantiates the converter and registers the default converters - */ - public DefaultResultConverter() { - this(true); - } - - /** - * Instantiates the converter - * - * @param registerDefaults whether or not default converters should be registered - */ - public DefaultResultConverter(boolean registerDefaults) { - converters = new LinkedList<>(); - if (registerDefaults) { - converters.add(new FutureToIterableConverter()); - converters.add(new IteratorToIterableConverter()); - converters.add(new SingleValueToIterableConverter()); - } + private final List converters; + + /** Instantiates the converter and registers the default converters */ + public DefaultResultConverter() { + this(true); + } + + /** + * Instantiates the converter + * + * @param registerDefaults whether or not default converters should be registered + */ + public DefaultResultConverter(boolean registerDefaults) { + converters = new LinkedList<>(); + if (registerDefaults) { + converters.add(new FutureToIterableConverter()); + converters.add(new IteratorToIterableConverter()); + converters.add(new SingleValueToIterableConverter()); } + } - @Override - public Object convert(Invocation invocation, Object original) { - Object value = original; - for (ResultConverter converter : converters) { - value = converter.convert(invocation, value); - } - return value; + @Override + public Object convert(Invocation invocation, Object original) { + Object value = original; + for (ResultConverter converter : converters) { + value = converter.convert(invocation, value); } - + return value; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverter.java index 1fde13c5..b31ac3a2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverter.java @@ -7,9 +7,10 @@ import java.util.concurrent.Future; /** - * This converter will convert a value that is of type {@link Future} to an iterable. Furthermore, it will convert that - * value one more level to get to the final value, if required. Also, the conversion will be a blocking statement that - * waits for the future value to be resolved via {@link Future#get()}. + * This converter will convert a value that is of type {@link Future} to an iterable. Furthermore, + * it will convert that value one more level to get to the final value, if required. Also, the + * conversion will be a blocking statement that waits for the future value to be resolved via {@link + * Future#get()}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) @@ -17,19 +18,18 @@ @SuppressWarnings("WeakerAccess") public class FutureToIterableConverter extends AbstractResultConverter { - @Override - protected Object doConvert(Invocation invocation, Object original) { - if (original instanceof Future) { - Future future = (Future) original; - final ResultConverter converter = new DefaultResultConverter(); - try { - final Object result = future.get(); - return converter.convert(invocation, result); - } catch (Exception e) { - throw new ResultConversionFailureException(e); - } - } - return original; + @Override + protected Object doConvert(Invocation invocation, Object original) { + if (original instanceof Future) { + Future future = (Future) original; + final ResultConverter converter = new DefaultResultConverter(); + try { + final Object result = future.get(); + return converter.convert(invocation, result); + } catch (Exception e) { + throw new ResultConversionFailureException(e); + } } - + return original; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverter.java index 4d426538..415fff15 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverter.java @@ -15,17 +15,16 @@ @SuppressWarnings("WeakerAccess") public class IteratorToIterableConverter extends AbstractResultConverter { - @Override - protected Object doConvert(Invocation invocation, Object original) { - if (original instanceof Iterator) { - Iterator iterator = (Iterator) original; - final List list = new LinkedList<>(); - while (iterator.hasNext()) { - list.add(iterator.next()); - } - return list; - } - return original; + @Override + protected Object doConvert(Invocation invocation, Object original) { + if (original instanceof Iterator) { + Iterator iterator = (Iterator) original; + final List list = new LinkedList<>(); + while (iterator.hasNext()) { + list.add(iterator.next()); + } + return list; } - + return original; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverter.java index 3862f750..d81c1c1c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverter.java @@ -6,8 +6,8 @@ import java.util.Iterator; /** - * This value will create a {@link Collections#singletonList singleton list} out of the passed value, so long as it is - * not an iterable or iterator object. + * This value will create a {@link Collections#singletonList singleton list} out of the passed + * value, so long as it is not an iterable or iterator object. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/28/15) @@ -15,12 +15,11 @@ @SuppressWarnings("WeakerAccess") public class SingleValueToIterableConverter extends AbstractResultConverter { - @Override - protected Object doConvert(Invocation invocation, Object original) { - if (original instanceof Iterable || original instanceof Iterator) { - return original; - } - return Collections.singletonList(original); + @Override + protected Object doConvert(Invocation invocation, Object original) { + if (original instanceof Iterable || original instanceof Iterator) { + return original; } - + return Collections.singletonList(original); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/EqualsNonDataOperationHandler.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/EqualsNonDataOperationHandler.java index e690ba5e..4eacdfe5 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/EqualsNonDataOperationHandler.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/EqualsNonDataOperationHandler.java @@ -12,17 +12,16 @@ */ public class EqualsNonDataOperationHandler implements NonDataOperationHandler { - private static final String EQUALS = "equals"; + private static final String EQUALS = "equals"; - @Override - public boolean handles(Object proxy, Method method, Object... args) { - return Object.class.equals(method.getDeclaringClass()) && EQUALS.equals(method.getName()); - } - - @Override - public Object invoke(Object proxy, Object... args) { - final Object that = args[0]; - return proxy.equals(that); - } + @Override + public boolean handles(Object proxy, Method method, Object... args) { + return Object.class.equals(method.getDeclaringClass()) && EQUALS.equals(method.getName()); + } + @Override + public Object invoke(Object proxy, Object... args) { + final Object that = args[0]; + return proxy.equals(that); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/HashCodeNonDataOperationHandler.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/HashCodeNonDataOperationHandler.java index d49b4fe0..6980862c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/HashCodeNonDataOperationHandler.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/HashCodeNonDataOperationHandler.java @@ -12,16 +12,15 @@ */ public class HashCodeNonDataOperationHandler implements NonDataOperationHandler { - private static final String HASH_CODE = "hashCode"; + private static final String HASH_CODE = "hashCode"; - @Override - public boolean handles(Object proxy, Method method, Object... args) { - return Object.class.equals(method.getDeclaringClass()) && HASH_CODE.equals(method.getName()); - } - - @Override - public Object invoke(Object proxy, Object... args) { - return System.identityHashCode(proxy); - } + @Override + public boolean handles(Object proxy, Method method, Object... args) { + return Object.class.equals(method.getDeclaringClass()) && HASH_CODE.equals(method.getName()); + } + @Override + public Object invoke(Object proxy, Object... args) { + return System.identityHashCode(proxy); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/ToStringNonDataOperationHandler.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/ToStringNonDataOperationHandler.java index 4ee2c434..93d03c67 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/ToStringNonDataOperationHandler.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/regular/ToStringNonDataOperationHandler.java @@ -12,16 +12,15 @@ */ public class ToStringNonDataOperationHandler implements NonDataOperationHandler { - private static final String TO_STRING = "toString"; + private static final String TO_STRING = "toString"; - @Override - public boolean handles(Object proxy, Method method, Object... args) { - return Object.class.equals(method.getDeclaringClass()) && TO_STRING.equals(method.getName()); - } - - @Override - public Object invoke(Object proxy, Object... args) { - return proxy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(proxy)); - } + @Override + public boolean handles(Object proxy, Method method, Object... args) { + return Object.class.equals(method.getDeclaringClass()) && TO_STRING.equals(method.getName()); + } + @Override + public Object invoke(Object proxy, Object... args) { + return proxy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(proxy)); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolver.java index f3d575db..a4a4bc5a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolver.java @@ -24,36 +24,38 @@ */ public class DefaultDataOperationResolver implements DataOperationResolver { - private static final Log log = LogFactory.getLog(DefaultDataOperationResolver.class); - private final List resolvers; + private static final Log log = LogFactory.getLog(DefaultDataOperationResolver.class); + private final List resolvers; - public DefaultDataOperationResolver(List> implementations, - MethodQueryDescriptionExtractor descriptionExtractor, - RepositoryMetadata repositoryMetadata, DataFunctionRegistry functionRegistry, - RepositoryFactoryConfiguration configuration) { - resolvers = new ArrayList<>(); - resolvers.add(new SignatureDataOperationResolver(implementations)); - resolvers.add(new QueryMethodDataOperationResolver(descriptionExtractor, repositoryMetadata, functionRegistry, - configuration)); - } + public DefaultDataOperationResolver( + List> implementations, + MethodQueryDescriptionExtractor descriptionExtractor, + RepositoryMetadata repositoryMetadata, + DataFunctionRegistry functionRegistry, + RepositoryFactoryConfiguration configuration) { + resolvers = new ArrayList<>(); + resolvers.add(new SignatureDataOperationResolver(implementations)); + resolvers.add( + new QueryMethodDataOperationResolver( + descriptionExtractor, repositoryMetadata, functionRegistry, configuration)); + } - @Override - public DataStoreOperation resolve(Method method) { - log.info("Resolving the data operation for method " + method); - for (DataOperationResolver resolver : resolvers) { - log.debug("Attempting to resolve the method call using resolver " + resolver); - final DataStoreOperation resolution; - try { - resolution = resolver.resolve(method); - } catch (Exception e) { - throw new DataOperationDefinitionException(method, e); - } - if (resolution != null) { - return resolution; - } - } - log.error("No suitable data operation could be found for method " + method); - throw new UnknownDataOperationException(method); + @Override + public DataStoreOperation resolve(Method method) { + log.info("Resolving the data operation for method " + method); + for (DataOperationResolver resolver : resolvers) { + log.debug("Attempting to resolve the method call using resolver " + resolver); + final DataStoreOperation resolution; + try { + resolution = resolver.resolve(method); + } catch (Exception e) { + throw new DataOperationDefinitionException(method, e); + } + if (resolution != null) { + return resolution; + } } - + log.error("No suitable data operation could be found for method " + method); + throw new UnknownDataOperationException(method); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolver.java index 4d46153f..72a9adf1 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolver.java @@ -17,10 +17,12 @@ import java.lang.reflect.Method; /** - *

This class will resolve methods to their query method equivalent by parsing their names and parameters.

+ * This class will resolve methods to their query method equivalent by parsing their names and + * parameters. * - *

Even though, technically speaking, a class annotated with {@link QueryAnnotation} is a - * query method, this class will ignore such methods since it doesn't know how to respond to native queries.

+ *

Even though, technically speaking, a class annotated with {@link QueryAnnotation} is + * a query method, this class will ignore such methods since it doesn't know how to respond to + * native queries. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) @@ -28,32 +30,34 @@ @SuppressWarnings("WeakerAccess") public class QueryMethodDataOperationResolver implements DataOperationResolver { - private static final Log log = LogFactory.getLog(QueryMethodDataOperationResolver.class); - private final MethodQueryDescriptionExtractor descriptionExtractor; - private final RepositoryMetadata repositoryMetadata; - private final DataFunctionRegistry functionRegistry; - private final RepositoryFactoryConfiguration configuration; + private static final Log log = LogFactory.getLog(QueryMethodDataOperationResolver.class); + private final MethodQueryDescriptionExtractor descriptionExtractor; + private final RepositoryMetadata repositoryMetadata; + private final DataFunctionRegistry functionRegistry; + private final RepositoryFactoryConfiguration configuration; - public QueryMethodDataOperationResolver(MethodQueryDescriptionExtractor descriptionExtractor, - RepositoryMetadata repositoryMetadata, - DataFunctionRegistry functionRegistry, - RepositoryFactoryConfiguration configuration) { - this.descriptionExtractor = descriptionExtractor; - this.repositoryMetadata = repositoryMetadata; - this.functionRegistry = functionRegistry; - this.configuration = configuration; - } + public QueryMethodDataOperationResolver( + MethodQueryDescriptionExtractor descriptionExtractor, + RepositoryMetadata repositoryMetadata, + DataFunctionRegistry functionRegistry, + RepositoryFactoryConfiguration configuration) { + this.descriptionExtractor = descriptionExtractor; + this.repositoryMetadata = repositoryMetadata; + this.functionRegistry = functionRegistry; + this.configuration = configuration; + } - @Override - public DataStoreOperation resolve(Method method) { - if (AnnotationUtils.findAnnotation(method, QueryAnnotation.class) != null) { - log.info("Found a @Query annotation on the method " + method); - //we don't know how to handle vendor-specific query methods - return null; - } - log.info("Extracting query description from the method by parsing the method"); - final QueryDescriptor descriptor = descriptionExtractor.extract(repositoryMetadata, configuration, method); - return new DescribedDataStoreOperation<>(new SelectDataStoreOperation<>(descriptor), functionRegistry); + @Override + public DataStoreOperation resolve(Method method) { + if (AnnotationUtils.findAnnotation(method, QueryAnnotation.class) != null) { + log.info("Found a @Query annotation on the method " + method); + // we don't know how to handle vendor-specific query methods + return null; } - + log.info("Extracting query description from the method by parsing the method"); + final QueryDescriptor descriptor = + descriptionExtractor.extract(repositoryMetadata, configuration, method); + return new DescribedDataStoreOperation<>( + new SelectDataStoreOperation<>(descriptor), functionRegistry); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolver.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolver.java index b625bcbd..a3df0621 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolver.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolver.java @@ -13,13 +13,15 @@ import java.util.List; /** - *

This class will resolve methods to the equivalent methods of the mapped implementations.

+ * This class will resolve methods to the equivalent methods of the mapped implementations. * - *

The process of equating methods to their implementation finds methods on the nearest implementation - * that can handle the given parameters, and whose name is the exact same as the invoked method.

+ *

The process of equating methods to their implementation finds methods on the nearest + * implementation that can handle the given parameters, and whose name is the exact same as the + * invoked method. * - *

Since the return value of the method can and will be adapted to the return value of the invoked method, - * return values are not considered to be so important, and they are not checked or considered.

+ *

Since the return value of the method can and will be adapted to the return value of the + * invoked method, return values are not considered to be so important, and they are not checked or + * considered. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) @@ -27,57 +29,64 @@ @SuppressWarnings("WeakerAccess") public class SignatureDataOperationResolver implements DataOperationResolver { - private static final Log log = LogFactory.getLog(SignatureDataOperationResolver.class); - private final List> mappings; + private static final Log log = LogFactory.getLog(SignatureDataOperationResolver.class); + private final List> mappings; - public SignatureDataOperationResolver(List> mappings) { - this.mappings = mappings; - } + public SignatureDataOperationResolver(List> mappings) { + this.mappings = mappings; + } - @Override - public DataStoreOperation resolve(Method method) { - log.info("Trying to resolve the data operation for method " + method - + " by going through the previously set up type mappings"); - for (TypeMapping mapping : mappings) { - final Class type = mapping.getType(); - final Method declaration = findMethod(type, method.getName(), method.getParameterTypes()); - if (declaration != null) { - log.info("Setting the resolution as a method invocation on the previously prepared type mapping"); - final Object instance = mapping.getInstance(); - return new MethodInvocationDataStoreOperation<>(instance, declaration); - } - } - return null; + @Override + public DataStoreOperation resolve(Method method) { + log.info( + "Trying to resolve the data operation for method " + + method + + " by going through the previously set up type mappings"); + for (TypeMapping mapping : mappings) { + final Class type = mapping.getType(); + final Method declaration = findMethod(type, method.getName(), method.getParameterTypes()); + if (declaration != null) { + log.info( + "Setting the resolution as a method invocation on the previously prepared type mapping"); + final Object instance = mapping.getInstance(); + return new MethodInvocationDataStoreOperation<>(instance, declaration); + } } + return null; + } - private static Method findMethod(Class type, String name, Class... parameterTypes) { - log.debug( - "Attempting to look for the actual declaration of the method named '" + name + "' with parameter types " - + Arrays.toString(parameterTypes) + " on the child type " + type); - Class searchType = type; - while (searchType != null) { - log.trace("Looking at type " + type + " for method " + name); - final Method[] methods = - searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods(); - for (Method method : methods) { - if (method.getName().equals(name) && parameterTypes.length == method.getParameterTypes().length) { - boolean matches = true; - for (int i = 0; i < parameterTypes.length; i++) { - final Class parameterType = parameterTypes[i]; - if (!PropertyUtils.getTypeOf(method.getParameterTypes()[i]).isAssignableFrom( - PropertyUtils.getTypeOf(parameterType))) { - matches = false; - break; - } - } - if (matches) { - return method; - } - } + private static Method findMethod(Class type, String name, Class... parameterTypes) { + log.debug( + "Attempting to look for the actual declaration of the method named '" + + name + + "' with parameter types " + + Arrays.toString(parameterTypes) + + " on the child type " + + type); + Class searchType = type; + while (searchType != null) { + log.trace("Looking at type " + type + " for method " + name); + final Method[] methods = + searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods(); + for (Method method : methods) { + if (method.getName().equals(name) + && parameterTypes.length == method.getParameterTypes().length) { + boolean matches = true; + for (int i = 0; i < parameterTypes.length; i++) { + final Class parameterType = parameterTypes[i]; + if (!PropertyUtils.getTypeOf(method.getParameterTypes()[i]) + .isAssignableFrom(PropertyUtils.getTypeOf(parameterType))) { + matches = false; + break; } - searchType = searchType.getSuperclass(); + } + if (matches) { + return method; + } } - return null; + } + searchType = searchType.getSuperclass(); } - + return null; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/DataFunction.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/DataFunction.java index e009b879..8941548d 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/DataFunction.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/DataFunction.java @@ -6,18 +6,20 @@ import java.util.List; /** - *

This interface encapsulates a data function. A data function is a function that applies to an already aggregated - * selection of entities, and can return any value.

+ * This interface encapsulates a data function. A data function is a function that applies to an + * already aggregated selection of entities, and can return any value. * - *

An example for a data function would be returning the number of items from a selection (count function) or - * duplicating all the selected entities.

+ *

An example for a data function would be returning the number of items from a selection (count + * function) or duplicating all the selected entities. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public interface DataFunction { - R apply(DataStore dataStore, QueryDescriptor query, RepositoryConfiguration configuration, - List selection); - + R apply( + DataStore dataStore, + QueryDescriptor query, + RepositoryConfiguration configuration, + List selection); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/DataFunctionRegistry.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/DataFunctionRegistry.java index 629fa75f..0ba40cc7 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/DataFunctionRegistry.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/DataFunctionRegistry.java @@ -13,27 +13,24 @@ @SuppressWarnings("unused") public interface DataFunctionRegistry { - /** - * Registers a new data function - * - * @param name the name under which the function will be known - * @param function the actual function - */ - void register(String name, DataFunction function); + /** + * Registers a new data function + * + * @param name the name under which the function will be known + * @param function the actual function + */ + void register(String name, DataFunction function); - /** - * Finds the function associated with the given name. If a function with that name does not exist, throws an - * exception. - * - * @param name the name of the function. - * @return the data function - * @throws FunctionNotFoundException If no function for the provided name can be found. - */ - DataFunction getFunction(String name); - - /** - * @return the set of all registered functions - */ - Set getFunctions(); + /** + * Finds the function associated with the given name. If a function with that name does not exist, + * throws an exception. + * + * @param name the name of the function. + * @return the data function + * @throws FunctionNotFoundException If no function for the provided name can be found. + */ + DataFunction getFunction(String name); + /** @return the set of all registered functions */ + Set getFunctions(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/NullHandling.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/NullHandling.java index 20eb2822..ce2dceca 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/NullHandling.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/NullHandling.java @@ -8,17 +8,10 @@ */ public enum NullHandling { - /** - * The null values should come before non-null values. - */ - NULLS_FIRST, - /** - * The null values should appear last when compared to non-null values. - */ - NULLS_LAST, - /** - * Pick one of the above as per the specifications of the underlying data store. - */ - DEFAULT - + /** The null values should come before non-null values. */ + NULLS_FIRST, + /** The null values should appear last when compared to non-null values. */ + NULLS_LAST, + /** Pick one of the above as per the specifications of the underlying data store. */ + DEFAULT } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Order.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Order.java index 5ab2d349..23add1f1 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Order.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Order.java @@ -8,19 +8,12 @@ */ public interface Order { - /** - * @return the direction of the sort - */ - SortDirection getDirection(); + /** @return the direction of the sort */ + SortDirection getDirection(); - /** - * @return the property for which the ordering is taking place - */ - String getProperty(); - - /** - * @return how null values should be handled - */ - NullHandling getNullHandling(); + /** @return the property for which the ordering is taking place */ + String getProperty(); + /** @return how null values should be handled */ + NullHandling getNullHandling(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Page.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Page.java index da7ed906..e2dca0be 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Page.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Page.java @@ -8,14 +8,9 @@ */ public interface Page { - /** - * @return the size of the page - */ - int getPageSize(); - - /** - * @return the maximum number of the items in each page - */ - int getPageNumber(); + /** @return the size of the page */ + int getPageSize(); + /** @return the maximum number of the items in each page */ + int getPageNumber(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/PageParameterExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/PageParameterExtractor.java index 0dba475a..90e80a99 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/PageParameterExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/PageParameterExtractor.java @@ -6,6 +6,4 @@ * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/19/15) */ -public interface PageParameterExtractor extends ParameterMetadataExtractor { - -} +public interface PageParameterExtractor extends ParameterMetadataExtractor {} diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/ParameterMetadataExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/ParameterMetadataExtractor.java index ae7c54d1..a56a7328 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/ParameterMetadataExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/ParameterMetadataExtractor.java @@ -3,8 +3,8 @@ import com.mmnaseri.utils.spring.data.domain.Invocation; /** - * This interface encapsulates the process of extracting metadata for a query execution from a given query method - * invocation. + * This interface encapsulates the process of extracting metadata for a query execution from a given + * query method invocation. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/19/15) @@ -12,12 +12,11 @@ @SuppressWarnings("WeakerAccess") public interface ParameterMetadataExtractor { - /** - * Extracts the promised metadata as per this invocation. - * - * @param invocation the invocation - * @return the promised metadata or {@literal null} if nothing relevant can be found - */ - E extract(Invocation invocation); - + /** + * Extracts the promised metadata as per this invocation. + * + * @param invocation the invocation + * @return the promised metadata or {@literal null} if nothing relevant can be found + */ + E extract(Invocation invocation); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/PropertyDescriptor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/PropertyDescriptor.java index 0f142637..9f148817 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/PropertyDescriptor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/PropertyDescriptor.java @@ -8,15 +8,12 @@ */ public interface PropertyDescriptor { - /** - * @return the path leading to the property - * @see com.mmnaseri.utils.spring.data.tools.PropertyUtils#getPropertyValue(Object, String) - */ - String getPath(); - - /** - * @return the type of the property - */ - Class getType(); + /** + * @return the path leading to the property + * @see com.mmnaseri.utils.spring.data.tools.PropertyUtils#getPropertyValue(Object, String) + */ + String getPath(); + /** @return the type of the property */ + Class getType(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/QueryDescriptor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/QueryDescriptor.java index d959d825..29107e6e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/QueryDescriptor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/QueryDescriptor.java @@ -16,56 +16,54 @@ */ public interface QueryDescriptor extends InvocationMatcher { - /** - * @return the repository factory configuration that were used when the current query was discovered - */ - RepositoryFactoryConfiguration getConfiguration(); + /** + * @return the repository factory configuration that were used when the current query was + * discovered + */ + RepositoryFactoryConfiguration getConfiguration(); - /** - * @return metadata pertaining to the repository to which this query belongs - */ - RepositoryMetadata getRepositoryMetadata(); + /** @return metadata pertaining to the repository to which this query belongs */ + RepositoryMetadata getRepositoryMetadata(); - /** - * @return whether query results are expected to be distinct - */ - boolean isDistinct(); + /** @return whether query results are expected to be distinct */ + boolean isDistinct(); - /** - * @return the function name that should be applied to the entities selected as per this query. Could be {@literal - * null} to indicate that no function should be applied. - */ - String getFunction(); + /** + * @return the function name that should be applied to the entities selected as per this query. + * Could be {@literal null} to indicate that no function should be applied. + */ + String getFunction(); - /** - * @return the maximum number of items this query is expected to return. A non-positive value indicates no limit. - */ - int getLimit(); + /** + * @return the maximum number of items this query is expected to return. A non-positive value + * indicates no limit. + */ + int getLimit(); - /** - * Given an actual, runtime invocation, returns the page metadata for that invocation as per this query, or - * {@literal null} if no pagination was indicated. - * - * @param invocation the invocation - * @return the pagination metadata - */ - Page getPage(Invocation invocation); + /** + * Given an actual, runtime invocation, returns the page metadata for that invocation as per this + * query, or {@literal null} if no pagination was indicated. + * + * @param invocation the invocation + * @return the pagination metadata + */ + Page getPage(Invocation invocation); - /** - * Given an actual, runtime invocation, returns the sort metadata for that invocation as per this query, or returns - * {@literal null} to indicate no ordering is required. - * - * @param invocation the invocation - * @return the sort metadata - */ - Sort getSort(Invocation invocation); - - /** - * @return a list of decision branches which forms this query. Each decision branch is a set of conjunctive criteria - * about any single entity. This means to be evaluated to {@literal true}, all of the parameters in that branch must - * match the entity. Decision branches are disjunctive towards each other, meaning that the moment one of them was - * evaluated to {@literal true} the rest will be disregarded. - */ - List> getBranches(); + /** + * Given an actual, runtime invocation, returns the sort metadata for that invocation as per this + * query, or returns {@literal null} to indicate no ordering is required. + * + * @param invocation the invocation + * @return the sort metadata + */ + Sort getSort(Invocation invocation); + /** + * @return a list of decision branches which forms this query. Each decision branch is a set of + * conjunctive criteria about any single entity. This means to be evaluated to {@literal + * true}, all of the parameters in that branch must match the entity. Decision branches are + * disjunctive towards each other, meaning that the moment one of them was evaluated to + * {@literal true} the rest will be disregarded. + */ + List> getBranches(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Sort.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Sort.java index c997b1b5..582810a0 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Sort.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/Sort.java @@ -3,16 +3,14 @@ import java.util.List; /** - * This interface represents a sort specification, which is in turn a collection of {@link Order orders}. + * This interface represents a sort specification, which is in turn a collection of {@link Order + * orders}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public interface Sort { - /** - * @return the orders comprising this sort specification - */ - List getOrders(); - + /** @return the orders comprising this sort specification */ + List getOrders(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/SortDirection.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/SortDirection.java index 3dff3670..857c431c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/SortDirection.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/SortDirection.java @@ -8,13 +8,8 @@ */ public enum SortDirection { - /** - * Items should be sorted as per their natural ordering - */ - ASCENDING, - /** - * Items should be sorted in the reverse direction of their natural ordering - */ - DESCENDING - + /** Items should be sorted as per their natural ordering */ + ASCENDING, + /** Items should be sorted in the reverse direction of their natural ordering */ + DESCENDING } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/SortParameterExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/SortParameterExtractor.java index 4ab7983b..a75d20de 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/SortParameterExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/SortParameterExtractor.java @@ -1,11 +1,10 @@ package com.mmnaseri.utils.spring.data.query; /** - * This interface encapsulates the process of extracting {@link Sort} metadata from a given query method invocation. + * This interface encapsulates the process of extracting {@link Sort} metadata from a given query + * method invocation. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/19/15) */ -public interface SortParameterExtractor extends ParameterMetadataExtractor { - -} +public interface SortParameterExtractor extends ParameterMetadataExtractor {} diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/AbstractSortParameterExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/AbstractSortParameterExtractor.java index 48256372..5027afd3 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/AbstractSortParameterExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/AbstractSortParameterExtractor.java @@ -1,6 +1,10 @@ package com.mmnaseri.utils.spring.data.query.impl; -import com.mmnaseri.utils.spring.data.query.*; +import com.mmnaseri.utils.spring.data.query.NullHandling; +import com.mmnaseri.utils.spring.data.query.Order; +import com.mmnaseri.utils.spring.data.query.Sort; +import com.mmnaseri.utils.spring.data.query.SortDirection; +import com.mmnaseri.utils.spring.data.query.SortParameterExtractor; import java.util.ArrayList; import java.util.List; @@ -10,8 +14,8 @@ import static org.springframework.data.domain.Sort.NullHandling.NULLS_LAST; /** - * This class will provide support for converting {@link org.springframework.data.domain.Sort Spring Data sort objects} - * into {@link Sort sort objects} defined within this framework. + * This class will provide support for converting {@link org.springframework.data.domain.Sort Spring + * Data sort objects} into {@link Sort sort objects} defined within this framework. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/19/15) @@ -19,23 +23,26 @@ @SuppressWarnings("WeakerAccess") public abstract class AbstractSortParameterExtractor implements SortParameterExtractor { - /** - * Given a sort parameter from the Spring Data framework, will determine the appropriate sort metadata compatible - * with this framework - * - * @param sort the sort specification - * @return converted sort metadata - */ - protected Sort getSort(org.springframework.data.domain.Sort sort) { - final List orders = new ArrayList<>(); - for (org.springframework.data.domain.Sort.Order order : sort) { - final SortDirection sortDirection = order.getDirection().equals(ASC) ? SortDirection.ASCENDING - : SortDirection.DESCENDING; - final NullHandling nullHandling = order.getNullHandling().equals(NULLS_FIRST) ? NullHandling.NULLS_FIRST - : (order.getNullHandling().equals(NULLS_LAST) ? NullHandling.NULLS_LAST : NullHandling.DEFAULT); - orders.add(new ImmutableOrder(sortDirection, order.getProperty(), nullHandling)); - } - return new ImmutableSort(orders); + /** + * Given a sort parameter from the Spring Data framework, will determine the appropriate sort + * metadata compatible with this framework + * + * @param sort the sort specification + * @return converted sort metadata + */ + protected Sort getSort(org.springframework.data.domain.Sort sort) { + final List orders = new ArrayList<>(); + for (org.springframework.data.domain.Sort.Order order : sort) { + final SortDirection sortDirection = + order.getDirection().equals(ASC) ? SortDirection.ASCENDING : SortDirection.DESCENDING; + final NullHandling nullHandling = + order.getNullHandling().equals(NULLS_FIRST) + ? NullHandling.NULLS_FIRST + : (order.getNullHandling().equals(NULLS_LAST) + ? NullHandling.NULLS_LAST + : NullHandling.DEFAULT); + orders.add(new ImmutableOrder(sortDirection, order.getProperty(), nullHandling)); } - + return new ImmutableSort(orders); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunction.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunction.java index bbc99fa6..3687871c 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunction.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunction.java @@ -19,16 +19,18 @@ @SuppressWarnings("WeakerAccess") public class CountDataFunction implements DataFunction { - private static final Log log = LogFactory.getLog(CountDataFunction.class); + private static final Log log = LogFactory.getLog(CountDataFunction.class); - @Override - public Long apply(DataStore dataStore, QueryDescriptor query, - RepositoryConfiguration repositoryConfiguration, List selection) { - if (selection == null) { - log.error("Cannot calculate the count if the selection is null"); - throw new InvalidArgumentException("Selection cannot be null"); - } - return ((Integer) selection.size()).longValue(); + @Override + public Long apply( + DataStore dataStore, + QueryDescriptor query, + RepositoryConfiguration repositoryConfiguration, + List selection) { + if (selection == null) { + log.error("Cannot calculate the count if the selection is null"); + throw new InvalidArgumentException("Selection cannot be null"); } - + return ((Integer) selection.size()).longValue(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistry.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistry.java index 0b629f0f..d2d056bb 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistry.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistry.java @@ -12,8 +12,8 @@ import java.util.concurrent.ConcurrentHashMap; /** - * This class provides support for registering data functions. Also, it comes with the option to register the default - * functions out-of-the-box. + * This class provides support for registering data functions. Also, it comes with the option to + * register the default functions out-of-the-box. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) @@ -21,45 +21,45 @@ @SuppressWarnings("WeakerAccess") public class DefaultDataFunctionRegistry implements DataFunctionRegistry { - private static final Log log = LogFactory.getLog(DefaultDataFunctionRegistry.class); + private static final Log log = LogFactory.getLog(DefaultDataFunctionRegistry.class); - private final Map> functions; + private final Map> functions; - public DefaultDataFunctionRegistry() { - this(true); - } - - public DefaultDataFunctionRegistry(boolean registerDefaults) { - functions = new ConcurrentHashMap<>(); - if (registerDefaults) { - log.info("Registering the default functions"); - register("count", new CountDataFunction()); - register("delete", new DeleteDataFunction()); - } - } + public DefaultDataFunctionRegistry() { + this(true); + } - @Override - public void register(String name, DataFunction function) { - if (functions.containsKey(name)) { - log.error("Cannot register a function with name " + name + " because that name is already taken"); - throw new DuplicateFunctionException(name); - } - log.info("Registering function with name " + name); - functions.put(name, function); + public DefaultDataFunctionRegistry(boolean registerDefaults) { + functions = new ConcurrentHashMap<>(); + if (registerDefaults) { + log.info("Registering the default functions"); + register("count", new CountDataFunction()); + register("delete", new DeleteDataFunction()); } + } - @Override - public DataFunction getFunction(String name) { - if (!functions.containsKey(name)) { - log.error("No function could be found with name " + name); - throw new FunctionNotFoundException(name); - } - return functions.get(name); + @Override + public void register(String name, DataFunction function) { + if (functions.containsKey(name)) { + log.error( + "Cannot register a function with name " + name + " because that name is already taken"); + throw new DuplicateFunctionException(name); } + log.info("Registering function with name " + name); + functions.put(name, function); + } - @Override - public Set getFunctions() { - return functions.keySet(); + @Override + public DataFunction getFunction(String name) { + if (!functions.containsKey(name)) { + log.error("No function could be found with name " + name); + throw new FunctionNotFoundException(name); } + return functions.get(name); + } + @Override + public Set getFunctions() { + return functions.keySet(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptor.java index 2b519840..bffa1ca6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptor.java @@ -1,8 +1,17 @@ package com.mmnaseri.utils.spring.data.query.impl; -import com.mmnaseri.utils.spring.data.domain.*; +import com.mmnaseri.utils.spring.data.domain.Invocation; +import com.mmnaseri.utils.spring.data.domain.InvocationMatcher; +import com.mmnaseri.utils.spring.data.domain.Modifier; +import com.mmnaseri.utils.spring.data.domain.Operator; +import com.mmnaseri.utils.spring.data.domain.Parameter; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata; import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration; -import com.mmnaseri.utils.spring.data.query.*; +import com.mmnaseri.utils.spring.data.query.Page; +import com.mmnaseri.utils.spring.data.query.PageParameterExtractor; +import com.mmnaseri.utils.spring.data.query.QueryDescriptor; +import com.mmnaseri.utils.spring.data.query.Sort; +import com.mmnaseri.utils.spring.data.query.SortParameterExtractor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanWrapper; @@ -18,110 +27,117 @@ */ public class DefaultQueryDescriptor implements QueryDescriptor { - private static final Log log = LogFactory.getLog(InvocationMatcher.class); - - private final boolean distinct; - private final String function; - private final int limit; - private final PageParameterExtractor pageExtractor; - private final SortParameterExtractor sortExtractor; - private final List> branches; - private final RepositoryFactoryConfiguration configuration; - private final RepositoryMetadata repositoryMetadata; - - public DefaultQueryDescriptor(boolean distinct, String function, int limit, PageParameterExtractor pageExtractor, - SortParameterExtractor sortExtractor, List> branches, - RepositoryFactoryConfiguration configuration, RepositoryMetadata repositoryMetadata) { - this.distinct = distinct; - this.function = function; - this.limit = limit; - this.pageExtractor = pageExtractor; - this.sortExtractor = sortExtractor; - this.branches = branches; - this.configuration = configuration; - this.repositoryMetadata = repositoryMetadata; + private static final Log log = LogFactory.getLog(InvocationMatcher.class); + + private final boolean distinct; + private final String function; + private final int limit; + private final PageParameterExtractor pageExtractor; + private final SortParameterExtractor sortExtractor; + private final List> branches; + private final RepositoryFactoryConfiguration configuration; + private final RepositoryMetadata repositoryMetadata; + + public DefaultQueryDescriptor( + boolean distinct, + String function, + int limit, + PageParameterExtractor pageExtractor, + SortParameterExtractor sortExtractor, + List> branches, + RepositoryFactoryConfiguration configuration, + RepositoryMetadata repositoryMetadata) { + this.distinct = distinct; + this.function = function; + this.limit = limit; + this.pageExtractor = pageExtractor; + this.sortExtractor = sortExtractor; + this.branches = branches; + this.configuration = configuration; + this.repositoryMetadata = repositoryMetadata; + } + + @Override + public RepositoryFactoryConfiguration getConfiguration() { + return configuration; + } + + @Override + public RepositoryMetadata getRepositoryMetadata() { + return repositoryMetadata; + } + + @Override + public boolean isDistinct() { + return distinct; + } + + @Override + public String getFunction() { + return function; + } + + @Override + public int getLimit() { + return limit; + } + + @Override + public Page getPage(Invocation invocation) { + return pageExtractor == null ? null : pageExtractor.extract(invocation); + } + + @Override + public Sort getSort(Invocation invocation) { + return sortExtractor == null ? null : sortExtractor.extract(invocation); + } + + @Override + public List> getBranches() { + return branches; + } + + @Override + public boolean matches(Object entity, Invocation invocation) { + log.info("Matching " + entity + " against " + invocation); + final List> branches = getBranches(); + if (branches.isEmpty()) { + return entity != null; } - - @Override - public RepositoryFactoryConfiguration getConfiguration() { - return configuration; - } - - @Override - public RepositoryMetadata getRepositoryMetadata() { - return repositoryMetadata; - } - - @Override - public boolean isDistinct() { - return distinct; - } - - @Override - public String getFunction() { - return function; - } - - @Override - public int getLimit() { - return limit; - } - - @Override - public Page getPage(Invocation invocation) { - return pageExtractor == null ? null : pageExtractor.extract(invocation); - } - - @Override - public Sort getSort(Invocation invocation) { - return sortExtractor == null ? null : sortExtractor.extract(invocation); - } - - @Override - public List> getBranches() { - return branches; - } - - @Override - public boolean matches(Object entity, Invocation invocation) { - log.info("Matching " + entity + " against " + invocation); - final List> branches = getBranches(); - if (branches.isEmpty()) { - return entity != null; + final BeanWrapper wrapper = new BeanWrapperImpl(entity); + for (List branch : branches) { + boolean matches = true; + for (Parameter parameter : branch) { + final boolean ignoreCase; + ignoreCase = parameter.getModifiers().contains(Modifier.IGNORE_CASE); + Object value = wrapper.getPropertyValue(parameter.getPath()); + if (ignoreCase && value instanceof String) { + value = ((String) value).toLowerCase(); } - final BeanWrapper wrapper = new BeanWrapperImpl(entity); - for (List branch : branches) { - boolean matches = true; - for (Parameter parameter : branch) { - final boolean ignoreCase; - ignoreCase = parameter.getModifiers().contains(Modifier.IGNORE_CASE); - Object value = wrapper.getPropertyValue(parameter.getPath()); - if (ignoreCase && value instanceof String) { - value = ((String) value).toLowerCase(); - } - final Operator operator = parameter.getOperator(); - final Object[] properties = new Object[operator.getOperands()]; - for (int i = 0; i < operator.getOperands(); i++) { - properties[i] = invocation.getArguments()[parameter.getIndices()[i]]; - if (ignoreCase && properties[i] != null && properties[i] instanceof String) { - properties[i] = ((String) properties[i]).toLowerCase(); - } - } - if (!operator.getMatcher().matches(parameter, value, properties)) { - matches = false; - break; - } - } - if (matches) { - return true; - } + final Operator operator = parameter.getOperator(); + final Object[] properties = new Object[operator.getOperands()]; + for (int i = 0; i < operator.getOperands(); i++) { + properties[i] = invocation.getArguments()[parameter.getIndices()[i]]; + if (ignoreCase && properties[i] != null && properties[i] instanceof String) { + properties[i] = ((String) properties[i]).toLowerCase(); + } } - return false; - } - - @Override - public String toString() { - return (getFunction() != null ? getFunction() + " " : "") + (isDistinct() ? "distinct " : "") + getBranches(); + if (!operator.getMatcher().matches(parameter, value, properties)) { + matches = false; + break; + } + } + if (matches) { + return true; + } } - + return false; + } + + @Override + public String toString() { + return (getFunction() != null ? getFunction() + " " : "") + + (isDistinct() ? "distinct " : "") + + getBranches(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunction.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunction.java index eefc7053..aabcf953 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunction.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunction.java @@ -14,8 +14,8 @@ import java.util.List; /** - * This function provides support for the delete data operation, by issuing a delete request for every selected entity - * to the underlying data store. + * This function provides support for the delete data operation, by issuing a delete request for + * every selected entity to the underlying data store. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) @@ -23,46 +23,49 @@ @SuppressWarnings("WeakerAccess") public class DeleteDataFunction implements DataFunction> { - private static final Log log = LogFactory.getLog(DeleteDataFunction.class); + private static final Log log = LogFactory.getLog(DeleteDataFunction.class); - @Override - public List apply(DataStore dataStore, QueryDescriptor query, - RepositoryConfiguration repositoryConfiguration, List selection) { - if (dataStore == null) { - log.error("Cannot delete entities when the data store is null"); - throw new InvalidArgumentException("Data store cannot be null"); - } - if (query == null) { - log.error("Cannot delete entities when the query is null"); - throw new InvalidArgumentException("Query cannot be null"); - } - if (selection == null) { - log.error("Cannot delete entities when the selection is null"); - throw new InvalidArgumentException("Selection cannot be null"); - } - final String identifier = query.getRepositoryMetadata().getIdentifierProperty(); - log.info("Using property " + identifier + " to delete the entities"); - final List deleted = new LinkedList<>(); - for (E item : selection) { - final Object key; - try { - key = PropertyUtils.getPropertyValue(item, identifier); - } catch (Exception e) { - log.error("The value of property " + identifier + " could not be read "); - throw new DataFunctionException("Failed to read property value for property " + identifier, e); - } - if (key == null) { - log.error("Cannot delete an entity when the identifier property has been set to null"); - throw new DataFunctionException( - "Cannot delete an entity without the key property being set: " + identifier); - } - //noinspection unchecked - if (dataStore.delete((K) key)) { - deleted.add(item); - } - } - log.error("Deleted " + deleted.size() + " entities as the result of the delete call"); - return deleted; + @Override + public List apply( + DataStore dataStore, + QueryDescriptor query, + RepositoryConfiguration repositoryConfiguration, + List selection) { + if (dataStore == null) { + log.error("Cannot delete entities when the data store is null"); + throw new InvalidArgumentException("Data store cannot be null"); } - + if (query == null) { + log.error("Cannot delete entities when the query is null"); + throw new InvalidArgumentException("Query cannot be null"); + } + if (selection == null) { + log.error("Cannot delete entities when the selection is null"); + throw new InvalidArgumentException("Selection cannot be null"); + } + final String identifier = query.getRepositoryMetadata().getIdentifierProperty(); + log.info("Using property " + identifier + " to delete the entities"); + final List deleted = new LinkedList<>(); + for (E item : selection) { + final Object key; + try { + key = PropertyUtils.getPropertyValue(item, identifier); + } catch (Exception e) { + log.error("The value of property " + identifier + " could not be read "); + throw new DataFunctionException( + "Failed to read property value for property " + identifier, e); + } + if (key == null) { + log.error("Cannot delete an entity when the identifier property has been set to null"); + throw new DataFunctionException( + "Cannot delete an entity without the key property being set: " + identifier); + } + //noinspection unchecked + if (dataStore.delete((K) key)) { + deleted.add(item); + } + } + log.error("Deleted " + deleted.size() + " entities as the result of the delete call"); + return deleted; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractor.java index 16275c3a..83291eb8 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractor.java @@ -5,32 +5,33 @@ import com.mmnaseri.utils.spring.data.query.Sort; /** - * This extractor will expect to receive a {@link org.springframework.data.domain.Sort} object via the very last - * parameter of a query method invocation. + * This extractor will expect to receive a {@link org.springframework.data.domain.Sort} object via + * the very last parameter of a query method invocation. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/19/15) */ public class DirectSortParameterExtractor extends AbstractSortParameterExtractor { - private final int index; + private final int index; - public DirectSortParameterExtractor(int index) { - this.index = index; - } + public DirectSortParameterExtractor(int index) { + this.index = index; + } - @Override - public Sort extract(Invocation invocation) { - if (invocation == null) { - throw new InvalidArgumentException("Invocation cannot be null"); - } - final Object value = invocation.getArguments()[index]; - if (value == null) { - throw new InvalidArgumentException("Page value should not be empty"); - } - if (value instanceof org.springframework.data.domain.Sort) { - return getSort((org.springframework.data.domain.Sort) value); - } - throw new InvalidArgumentException("No valid value was passed to deduce the paging description from"); + @Override + public Sort extract(Invocation invocation) { + if (invocation == null) { + throw new InvalidArgumentException("Invocation cannot be null"); + } + final Object value = invocation.getArguments()[index]; + if (value == null) { + throw new InvalidArgumentException("Page value should not be empty"); + } + if (value instanceof org.springframework.data.domain.Sort) { + return getSort((org.springframework.data.domain.Sort) value); } + throw new InvalidArgumentException( + "No valid value was passed to deduce the paging description from"); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutableOrder.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutableOrder.java index ebb5ea93..a74a7783 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutableOrder.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutableOrder.java @@ -13,38 +13,37 @@ @SuppressWarnings("WeakerAccess") public class ImmutableOrder implements Order { - private final SortDirection direction; - private final String property; - private final NullHandling nullHandling; - - public ImmutableOrder(Order order) { - this(order.getDirection(), order.getProperty(), order.getNullHandling()); - } - - public ImmutableOrder(SortDirection direction, String property, NullHandling nullHandling) { - this.direction = direction; - this.property = property; - this.nullHandling = nullHandling; - } - - @Override - public SortDirection getDirection() { - return direction; - } - - @Override - public String getProperty() { - return property; - } - - @Override - public NullHandling getNullHandling() { - return nullHandling; - } - - @Override - public String toString() { - return property + " " + direction; - } - + private final SortDirection direction; + private final String property; + private final NullHandling nullHandling; + + public ImmutableOrder(Order order) { + this(order.getDirection(), order.getProperty(), order.getNullHandling()); + } + + public ImmutableOrder(SortDirection direction, String property, NullHandling nullHandling) { + this.direction = direction; + this.property = property; + this.nullHandling = nullHandling; + } + + @Override + public SortDirection getDirection() { + return direction; + } + + @Override + public String getProperty() { + return property; + } + + @Override + public NullHandling getNullHandling() { + return nullHandling; + } + + @Override + public String toString() { + return property + " " + direction; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutablePage.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutablePage.java index 5640840d..1204cf3a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutablePage.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutablePage.java @@ -11,22 +11,21 @@ @SuppressWarnings("WeakerAccess") public class ImmutablePage implements Page { - private final int pageSize; - private final int pageNumber; + private final int pageSize; + private final int pageNumber; - public ImmutablePage(int pageSize, int pageNumber) { - this.pageSize = pageSize; - this.pageNumber = pageNumber; - } + public ImmutablePage(int pageSize, int pageNumber) { + this.pageSize = pageSize; + this.pageNumber = pageNumber; + } - @Override - public int getPageSize() { - return pageSize; - } - - @Override - public int getPageNumber() { - return pageNumber; - } + @Override + public int getPageSize() { + return pageSize; + } + @Override + public int getPageNumber() { + return pageNumber; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutablePropertyDescriptor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutablePropertyDescriptor.java index 08877278..353b4e45 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutablePropertyDescriptor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutablePropertyDescriptor.java @@ -10,22 +10,21 @@ */ public class ImmutablePropertyDescriptor implements PropertyDescriptor { - private final String path; - private final Class type; + private final String path; + private final Class type; - public ImmutablePropertyDescriptor(String path, Class type) { - this.path = path; - this.type = type; - } + public ImmutablePropertyDescriptor(String path, Class type) { + this.path = path; + this.type = type; + } - @Override - public String getPath() { - return path; - } - - @Override - public Class getType() { - return type; - } + @Override + public String getPath() { + return path; + } + @Override + public Class getType() { + return type; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutableSort.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutableSort.java index 84b8bbd5..6574d42d 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutableSort.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/ImmutableSort.java @@ -15,20 +15,19 @@ */ public class ImmutableSort implements Sort { - private final List orders; + private final List orders; - public ImmutableSort(List orders) { - this.orders = new ArrayList<>(); - if (orders != null) { - for (Order order : orders) { - this.orders.add(new ImmutableOrder(order)); - } - } - } - - @Override - public List getOrders() { - return Collections.unmodifiableList(orders); + public ImmutableSort(List orders) { + this.orders = new ArrayList<>(); + if (orders != null) { + for (Order order : orders) { + this.orders.add(new ImmutableOrder(order)); + } } + } + @Override + public List getOrders() { + return Collections.unmodifiableList(orders); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractor.java index 46814165..8f5f6c4a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractor.java @@ -7,34 +7,34 @@ import org.springframework.data.domain.Pageable; /** - * This extractor will expect to see a {@link Pageable} as the last parameter passed to a query method invocation, and - * converts that to a valid page. + * This extractor will expect to see a {@link Pageable} as the last parameter passed to a query + * method invocation, and converts that to a valid page. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/19/15) */ public class PageablePageParameterExtractor implements PageParameterExtractor { - private final int index; + private final int index; - public PageablePageParameterExtractor(int index) { - this.index = index; - } + public PageablePageParameterExtractor(int index) { + this.index = index; + } - @Override - public Page extract(Invocation invocation) { - if (invocation == null) { - throw new InvalidArgumentException("Invocation cannot be null"); - } - final Object value = invocation.getArguments()[index]; - if (value == null) { - throw new InvalidArgumentException("Page value should not be empty"); - } - if (value instanceof Pageable) { - final Pageable pageable = (Pageable) value; - return new ImmutablePage(pageable.getPageSize(), pageable.getPageNumber()); - } - throw new InvalidArgumentException("No valid value was passed to deduce the paging description from"); + @Override + public Page extract(Invocation invocation) { + if (invocation == null) { + throw new InvalidArgumentException("Invocation cannot be null"); } - + final Object value = invocation.getArguments()[index]; + if (value == null) { + throw new InvalidArgumentException("Page value should not be empty"); + } + if (value instanceof Pageable) { + final Pageable pageable = (Pageable) value; + return new ImmutablePage(pageable.getPageSize(), pageable.getPageNumber()); + } + throw new InvalidArgumentException( + "No valid value was passed to deduce the paging description from"); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractor.java index 77879023..704b0811 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractor.java @@ -6,35 +6,35 @@ import org.springframework.data.domain.Pageable; /** - * This extractor expects to see a {@link Pageable} passed as the last argument to a query method call and tries to ask - * the pageable for the sort metadata. + * This extractor expects to see a {@link Pageable} passed as the last argument to a query method + * call and tries to ask the pageable for the sort metadata. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/19/15) */ public class PageableSortParameterExtractor extends AbstractSortParameterExtractor { - private final int index; + private final int index; - public PageableSortParameterExtractor(int index) { - this.index = index; - } + public PageableSortParameterExtractor(int index) { + this.index = index; + } - @Override - public Sort extract(Invocation invocation) { - if (invocation == null) { - throw new InvalidArgumentException("Invocation cannot be null"); - } - final Object value = invocation.getArguments()[index]; - if (value == null) { - throw new InvalidArgumentException("Page value should not be empty"); - } - if (value instanceof Pageable) { - final Pageable pageable = (Pageable) value; - final org.springframework.data.domain.Sort sort = pageable.getSort(); - return getSort(sort); - } - throw new InvalidArgumentException("No valid value was passed to deduce the sort description from"); + @Override + public Sort extract(Invocation invocation) { + if (invocation == null) { + throw new InvalidArgumentException("Invocation cannot be null"); } - + final Object value = invocation.getArguments()[index]; + if (value == null) { + throw new InvalidArgumentException("Page value should not be empty"); + } + if (value instanceof Pageable) { + final Pageable pageable = (Pageable) value; + final org.springframework.data.domain.Sort sort = pageable.getSort(); + return getSort(sort); + } + throw new InvalidArgumentException( + "No valid value was passed to deduce the sort description from"); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractor.java index 549692c1..109536c9 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractor.java @@ -7,28 +7,29 @@ import com.mmnaseri.utils.spring.data.query.SortParameterExtractor; /** - * This extractor will return the statically defined sort metadata for a query method (as parsed from the method name). + * This extractor will return the statically defined sort metadata for a query method (as parsed + * from the method name). * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/20/15) */ public class WrappedSortParameterExtractor implements SortParameterExtractor { - private final Sort sort; + private final Sort sort; - public WrappedSortParameterExtractor(Sort sort) { - if (sort == null) { - throw new RepositoryDefinitionException(null, "Predefined sort method must not resolve to null"); - } - this.sort = sort; + public WrappedSortParameterExtractor(Sort sort) { + if (sort == null) { + throw new RepositoryDefinitionException( + null, "Predefined sort method must not resolve to null"); } + this.sort = sort; + } - @Override - public Sort extract(Invocation invocation) { - if (invocation == null) { - throw new InvalidArgumentException("Invocation cannot be null"); - } - return sort; + @Override + public Sort extract(Invocation invocation) { + if (invocation == null) { + throw new InvalidArgumentException("Invocation cannot be null"); } - + return sort; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/CrudRepositorySupport.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/CrudRepositorySupport.java index a6990de7..f6d969bd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/CrudRepositorySupport.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/CrudRepositorySupport.java @@ -1,6 +1,10 @@ package com.mmnaseri.utils.spring.data.repository; -import com.mmnaseri.utils.spring.data.domain.*; +import com.mmnaseri.utils.spring.data.domain.DataStoreAware; +import com.mmnaseri.utils.spring.data.domain.KeyGenerator; +import com.mmnaseri.utils.spring.data.domain.KeyGeneratorAware; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataAware; import com.mmnaseri.utils.spring.data.store.DataStore; import com.mmnaseri.utils.spring.data.tools.PropertyUtils; import org.apache.commons.logging.Log; @@ -9,102 +13,103 @@ import java.util.LinkedList; import java.util.List; /** - *

This implementation is used to factor out the commonalities between various Spring interfaces extending the - * {@link org.springframework.data.repository.CrudRepository} interface.

+ * This implementation is used to factor out the commonalities between various Spring interfaces + * extending the {@link org.springframework.data.repository.CrudRepository} interface. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (2015/11/09, 21:40) */ @SuppressWarnings({"WeakerAccess", "unused"}) -public class CrudRepositorySupport implements DataStoreAware, RepositoryMetadataAware, KeyGeneratorAware { +public class CrudRepositorySupport + implements DataStoreAware, RepositoryMetadataAware, KeyGeneratorAware { - private static final Log log = LogFactory.getLog(CrudRepositorySupport.class); - private KeyGenerator keyGenerator; - private DataStore dataStore; - private RepositoryMetadata repositoryMetadata; + private static final Log log = LogFactory.getLog(CrudRepositorySupport.class); + private KeyGenerator keyGenerator; + private DataStore dataStore; + private RepositoryMetadata repositoryMetadata; - protected CrudRepositorySupport() { - } + protected CrudRepositorySupport() {} - /** - * Saves the entity in the underlying data store, creating keys in the process, if necessary. - * - * @param entity the entity to save - * @return the saved entity (the exact same instance, with the difference that if the entity was newly inserted, it - * will have a key). - */ - public Object save(Object entity) { - if (entity instanceof Iterable) { - return save((Iterable) entity); - } - Object key = PropertyUtils.getPropertyValue(entity, repositoryMetadata.getIdentifierProperty()); - log.info("The entity that is to be saved has a key with value " + key); - if (key == null && keyGenerator != null) { - log.info("The key was null, but the generator was not, so we are going to get a key for the entity"); - key = keyGenerator.generate(); - log.debug("The generated key for the entity was " + key); - PropertyUtils.setPropertyValue(entity, repositoryMetadata.getIdentifierProperty(), key); - } - if (key == null) { - log.warn( - "Attempting to save an entity without a key. This might result in an error. To fix this, specify " - + "a key generator."); - } - //noinspection unchecked - dataStore.save(key, entity); - return entity; + /** + * Saves the entity in the underlying data store, creating keys in the process, if necessary. + * + * @param entity the entity to save + * @return the saved entity (the exact same instance, with the difference that if the entity was + * newly inserted, it will have a key). + */ + public Object save(Object entity) { + if (entity instanceof Iterable) { + return save((Iterable) entity); } - - - /** - * Saves all the given entities - * @param entities entities to save (insert or update) - * @return saved entities - */ - public Iterable save(Iterable entities) { - final List list = new LinkedList<>(); - log.info("Going to save a number of entities in the underlying data store"); - log.debug(entities); - for (Object entity : entities) { - list.add(save(entity)); - } - return list; + Object key = PropertyUtils.getPropertyValue(entity, repositoryMetadata.getIdentifierProperty()); + log.info("The entity that is to be saved has a key with value " + key); + if (key == null && keyGenerator != null) { + log.info( + "The key was null, but the generator was not, so we are going to get a key for the entity"); + key = keyGenerator.generate(); + log.debug("The generated key for the entity was " + key); + PropertyUtils.setPropertyValue(entity, repositoryMetadata.getIdentifierProperty(), key); } - - /** - * Inserts the given entity via the {@link #save(Object)} method. - * @param entity the entity to be inserted. - * @return the saved entity. This should result in the entity having a key. - */ - public Object insert(Object entity) { - return save(entity); + if (key == null) { + log.warn( + "Attempting to save an entity without a key. This might result in an error. To fix this, specify " + + "a key generator."); } + //noinspection unchecked + dataStore.save(key, entity); + return entity; + } - @Override - public final void setDataStore(DataStore dataStore) { - this.dataStore = dataStore; + /** + * Saves all the given entities + * + * @param entities entities to save (insert or update) + * @return saved entities + */ + public Iterable save(Iterable entities) { + final List list = new LinkedList<>(); + log.info("Going to save a number of entities in the underlying data store"); + log.debug(entities); + for (Object entity : entities) { + list.add(save(entity)); } + return list; + } - @Override - public final void setKeyGenerator(KeyGenerator keyGenerator) { - this.keyGenerator = keyGenerator; - } + /** + * Inserts the given entity via the {@link #save(Object)} method. + * + * @param entity the entity to be inserted. + * @return the saved entity. This should result in the entity having a key. + */ + public Object insert(Object entity) { + return save(entity); + } - @Override - public final void setRepositoryMetadata(RepositoryMetadata repositoryMetadata) { - this.repositoryMetadata = repositoryMetadata; - } + protected KeyGenerator getKeyGenerator() { + return keyGenerator; + } - protected KeyGenerator getKeyGenerator() { - return keyGenerator; - } + @Override + public final void setKeyGenerator(KeyGenerator keyGenerator) { + this.keyGenerator = keyGenerator; + } - protected DataStore getDataStore() { - return dataStore; - } + protected DataStore getDataStore() { + return dataStore; + } - protected RepositoryMetadata getRepositoryMetadata() { - return repositoryMetadata; - } + @Override + public final void setDataStore(DataStore dataStore) { + this.dataStore = dataStore; + } + + protected RepositoryMetadata getRepositoryMetadata() { + return repositoryMetadata; + } + @Override + public final void setRepositoryMetadata(RepositoryMetadata repositoryMetadata) { + this.repositoryMetadata = repositoryMetadata; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultCrudRepository.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultCrudRepository.java index d764b37e..bf3359f6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultCrudRepository.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultCrudRepository.java @@ -11,9 +11,8 @@ import java.util.Optional; /** - *

- * This class will provide implementations for the methods introduced by the Spring framework through {@link - * org.springframework.data.repository.CrudRepository}.

+ * This class will provide implementations for the methods introduced by the Spring framework + * through {@link org.springframework.data.repository.CrudRepository}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/6/15) @@ -21,138 +20,149 @@ @SuppressWarnings({"unchecked", "WeakerAccess", "UnusedReturnValue"}) public class DefaultCrudRepository extends CrudRepositorySupport { - private static final Log log = LogFactory.getLog(DefaultCrudRepository.class); + private static final Log log = LogFactory.getLog(DefaultCrudRepository.class); - /** - * Saves all the given entities - * - * @param entities entities to save (insert or update) - * @return saved entities - */ - public Iterable saveAll(Iterable entities) { - return save(entities); - } + /** + * Saves all the given entities + * + * @param entities entities to save (insert or update) + * @return saved entities + */ + public Iterable saveAll(Iterable entities) { + return save(entities); + } - /** - * Finds the entity that was saved with this key, or returns {@literal null} - * - * @param key the key - * @return the entity - */ - public Optional findById(Object key) { - log.info("Attempting to load the entity with key " + key); - return Optional.ofNullable(getDataStore().retrieve(key)); - } + /** + * Finds the entity that was saved with this key, or returns {@literal null} + * + * @param key the key + * @return the entity + */ + public Optional findById(Object key) { + log.info("Attempting to load the entity with key " + key); + return Optional.ofNullable(getDataStore().retrieve(key)); + } - /** - * Checks whether the given key represents an entity in the data store - * - * @param key the key - * @return {@literal true} if the key is valid - */ - public boolean existsById(Object key) { - return getDataStore().hasKey(key); - } + /** + * Checks whether the given key represents an entity in the data store + * + * @param key the key + * @return {@literal true} if the key is valid + */ + public boolean existsById(Object key) { + return getDataStore().hasKey(key); + } - /** - * Finds all the entities that match the given set of ids - * - * @param ids ids to look for - * @return entities that matched the ids. - */ - public Iterable findAllById(Iterable ids) { - final List entities = new LinkedList(); - log.info("Looking for multiple entities for a number of ids"); - log.debug(ids); - for (Object id : ids) { - final Optional found = findById(id); - if (found.isPresent()) { - log.trace("Entity found for key " + id + ", adding the found entity to the list of returned entity"); - entities.add(found.get()); - } - } - return entities; + /** + * Finds all the entities that match the given set of ids + * + * @param ids ids to look for + * @return entities that matched the ids. + */ + public Iterable findAllById(Iterable ids) { + final List entities = new LinkedList(); + log.info("Looking for multiple entities for a number of ids"); + log.debug(ids); + for (Object id : ids) { + final Optional found = findById(id); + if (found.isPresent()) { + log.trace( + "Entity found for key " + + id + + ", adding the found entity to the list of returned entity"); + entities.add(found.get()); + } } + return entities; + } - /** - * Deletes the entity with the given id and returns the actual entity that was just deleted. - * - * @param id the id - * @return the entity that was deleted or {@literal null} if it wasn't found - */ - public Object delete(Object id) { - Object retrieved = getDataStore().retrieve(id); - log.info("Attempting to delete the entity with key " + id); - if (retrieved == null) { - log.info("Object not found with key " + id + ", try to find by identifier property"); - try { - id = PropertyUtils.getPropertyValue(id, getRepositoryMetadata().getIdentifierProperty()); - retrieved = getDataStore().retrieve(id); - } catch (IllegalStateException exception) { - log.info("Serialized id doesn't have a identifier property"); - } - } - getDataStore().delete(id); - return retrieved; + /** + * Deletes the entity with the given id and returns the actual entity that was just deleted. + * + * @param id the id + * @return the entity that was deleted or {@literal null} if it wasn't found + */ + public Object delete(Object id) { + Object retrieved = getDataStore().retrieve(id); + log.info("Attempting to delete the entity with key " + id); + if (retrieved == null) { + log.info("Object not found with key " + id + ", try to find by identifier property"); + try { + id = PropertyUtils.getPropertyValue(id, getRepositoryMetadata().getIdentifierProperty()); + retrieved = getDataStore().retrieve(id); + } catch (IllegalStateException exception) { + log.info("Serialized id doesn't have a identifier property"); + } } + getDataStore().delete(id); + return retrieved; + } - /** - * Deletes the entity matching this entity's key from the data store - * - * @param entity the entity - * @return the deleted entity - * @throws EntityMissingKeyException if the passed entity doesn't have a key - */ - public Object deleteById(Object entity) { - final Object key = PropertyUtils.getPropertyValue(entity, getRepositoryMetadata().getIdentifierProperty()); - if (key == null) { - log.error("The entity that was supposed to be deleted, does not have a key"); - throw new EntityMissingKeyException(getRepositoryMetadata().getEntityType(), - getRepositoryMetadata().getIdentifierProperty()); - } - return delete(key); + /** + * Deletes the entity matching this entity's key from the data store + * + * @param entity the entity + * @return the deleted entity + * @throws EntityMissingKeyException if the passed entity doesn't have a key + */ + public Object deleteById(Object entity) { + final Object key = + PropertyUtils.getPropertyValue(entity, getRepositoryMetadata().getIdentifierProperty()); + if (key == null) { + log.error("The entity that was supposed to be deleted, does not have a key"); + throw new EntityMissingKeyException( + getRepositoryMetadata().getEntityType(), getRepositoryMetadata().getIdentifierProperty()); } + return delete(key); + } - /** - * Deletes all specified entities from the data store. - * - * @param entities the entities to delete - * @return the entities that were actually deleted - */ - public Iterable delete(Iterable entities) { - log.info("Attempting to delete multiple entities via entity objects themselves"); - log.debug(entities); - final List list = new LinkedList(); - for (Object entity : entities) { - final Object deleted = deleteById(entity); - if (deleted != null) { - log.debug("The entity was deleted successfully and will be added to the list of deleted entities"); - list.add(deleted); - } - } - return list; + /** + * Deletes all specified entities from the data store. + * + * @param entities the entities to delete + * @return the entities that were actually deleted + */ + public Iterable delete(Iterable entities) { + log.info("Attempting to delete multiple entities via entity objects themselves"); + log.debug(entities); + final List list = new LinkedList(); + for (Object entity : entities) { + final Object deleted = deleteById(entity); + if (deleted != null) { + log.debug( + "The entity was deleted successfully and will be added to the list of deleted entities"); + list.add(deleted); + } } + return list; + } - /** - * Deletes everything from the data store - * - * @return all the entities that were removed - */ - public Iterable deleteAll() { - log.info("Attempting to delete all entities at once"); - final List list = new LinkedList(); - final Collection keys = getDataStore().keys(); - log.debug("There are " + keys.size() + " entities altogether in the data store that are going to be deleted"); - for (Object key : keys) { - final Object deleted = delete((key)); - if (deleted != null) { - log.debug("The entity was deleted successfully and will be added to the list of deleted entities"); - list.add(deleted); - } - } - final Collection remainingKeys = getDataStore().keys(); - log.debug("There are " + remainingKeys.size() + " keys remaining in the data store after the delete operation"); - return list; + /** + * Deletes everything from the data store + * + * @return all the entities that were removed + */ + public Iterable deleteAll() { + log.info("Attempting to delete all entities at once"); + final List list = new LinkedList(); + final Collection keys = getDataStore().keys(); + log.debug( + "There are " + + keys.size() + + " entities altogether in the data store that are going to be deleted"); + for (Object key : keys) { + final Object deleted = delete((key)); + if (deleted != null) { + log.debug( + "The entity was deleted successfully and will be added to the list of deleted entities"); + list.add(deleted); + } } - + final Collection remainingKeys = getDataStore().keys(); + log.debug( + "There are " + + remainingKeys.size() + + " keys remaining in the data store after the delete operation"); + return list; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultGemfireRepository.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultGemfireRepository.java index f7b2efdd..0861c25f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultGemfireRepository.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultGemfireRepository.java @@ -15,39 +15,39 @@ */ public class DefaultGemfireRepository implements DataStoreAware, RepositoryMetadataAware { - private static final Log log = LogFactory.getLog(DefaultGemfireRepository.class); - private DataStore dataStore; - private RepositoryMetadata repositoryMetadata; + private static final Log log = LogFactory.getLog(DefaultGemfireRepository.class); + private DataStore dataStore; + private RepositoryMetadata repositoryMetadata; - /** - * Saves the wrapped data object into the data store. If the wrapped object is also an instance of the type bound to - * this data store, it will set the key on the object - * - * @param wrapper the wrapper for the key and the object - * @return the saved entity - */ - public Object save(Wrapper wrapper) { - log.info("Going to save a wrapped data store object"); - final Object entity = wrapper.getEntity(); - final Object key = wrapper.getKey(); - if (repositoryMetadata.getEntityType().isInstance(entity)) { - log.debug("Since the entity is of the same type as the actual entity type supported by the data store, " + - "we know how to set the key on the wrapped entity."); - PropertyUtils.setPropertyValue(entity, repositoryMetadata.getIdentifierProperty(), key); - } - //noinspection unchecked - dataStore.save(key, entity); - return entity; + /** + * Saves the wrapped data object into the data store. If the wrapped object is also an instance of + * the type bound to this data store, it will set the key on the object + * + * @param wrapper the wrapper for the key and the object + * @return the saved entity + */ + public Object save(Wrapper wrapper) { + log.info("Going to save a wrapped data store object"); + final Object entity = wrapper.getEntity(); + final Object key = wrapper.getKey(); + if (repositoryMetadata.getEntityType().isInstance(entity)) { + log.debug( + "Since the entity is of the same type as the actual entity type supported by the data store, " + + "we know how to set the key on the wrapped entity."); + PropertyUtils.setPropertyValue(entity, repositoryMetadata.getIdentifierProperty(), key); } + //noinspection unchecked + dataStore.save(key, entity); + return entity; + } - @Override - public void setDataStore(DataStore dataStore) { - this.dataStore = dataStore; - } - - @Override - public void setRepositoryMetadata(RepositoryMetadata repositoryMetadata) { - this.repositoryMetadata = repositoryMetadata; - } + @Override + public void setDataStore(DataStore dataStore) { + this.dataStore = dataStore; + } + @Override + public void setRepositoryMetadata(RepositoryMetadata repositoryMetadata) { + this.repositoryMetadata = repositoryMetadata; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultJpaRepository.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultJpaRepository.java index cedfe2e9..b327de3e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultJpaRepository.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultJpaRepository.java @@ -18,109 +18,110 @@ @SuppressWarnings({"unchecked", "WeakerAccess", "UnusedReturnValue"}) public class DefaultJpaRepository extends CrudRepositorySupport { - private static final Log log = LogFactory.getLog(DefaultJpaRepository.class); + private static final Log log = LogFactory.getLog(DefaultJpaRepository.class); - /** - * If the underlying data store supports {@link QueueingDataStore queueing} and needs the queue to be flushed, this - * method will flush the queue. Otherwise, it will not do anything - */ - public void flush() { - final DataStore dataStore = getDataStore(); - if (dataStore instanceof QueueingDataStore) { - log.info("Asking the data store to flush the underlying operation queue"); - final QueueingDataStore store = (QueueingDataStore) dataStore; - store.flush(); - } + /** + * If the underlying data store supports {@link QueueingDataStore queueing} and needs the queue to + * be flushed, this method will flush the queue. Otherwise, it will not do anything + */ + public void flush() { + final DataStore dataStore = getDataStore(); + if (dataStore instanceof QueueingDataStore) { + log.info("Asking the data store to flush the underlying operation queue"); + final QueueingDataStore store = (QueueingDataStore) dataStore; + store.flush(); } + } - /** - * Deletes the given entities by enclosing the actual delete in batch requests. If the underlying data store doesn't - * support {@link QueueingDataStore queueing}, this will be no different than simply sequentially deleting all the - * entities. - * - * @param entities entities to delete - * @return deleted entities - */ - public Iterable deleteInBatch(Iterable entities) { - final List keys = new LinkedList<>(); - for (Object entity : entities) { - final Object key = PropertyUtils.getPropertyValue(entity, getRepositoryMetadata().getIdentifierProperty()); - if (key == null) { - log.error("There is no key set for the entity we were trying to delete"); - throw new EntityMissingKeyException(getRepositoryMetadata().getEntityType(), - getRepositoryMetadata().getIdentifierProperty()); - } - keys.add(key); - } - return deleteByKeysInBatch(keys); + /** + * Deletes the given entities by enclosing the actual delete in batch requests. If the underlying + * data store doesn't support {@link QueueingDataStore queueing}, this will be no different than + * simply sequentially deleting all the entities. + * + * @param entities entities to delete + * @return deleted entities + */ + public Iterable deleteInBatch(Iterable entities) { + final List keys = new LinkedList<>(); + for (Object entity : entities) { + final Object key = + PropertyUtils.getPropertyValue(entity, getRepositoryMetadata().getIdentifierProperty()); + if (key == null) { + log.error("There is no key set for the entity we were trying to delete"); + throw new EntityMissingKeyException( + getRepositoryMetadata().getEntityType(), + getRepositoryMetadata().getIdentifierProperty()); + } + keys.add(key); } + return deleteByKeysInBatch(keys); + } - /** - * Deletes everything in the data store that's of the bound entity type - * - * @return deleted entities - */ - public Iterable deleteAllInBatch() { - log.info("Attempting to delete all the entities in the data store in a batch"); - return deleteByKeysInBatch(getDataStore().keys()); - } + /** + * Deletes everything in the data store that's of the bound entity type + * + * @return deleted entities + */ + public Iterable deleteAllInBatch() { + log.info("Attempting to delete all the entities in the data store in a batch"); + return deleteByKeysInBatch(getDataStore().keys()); + } - /** - * Deletes entities bound to the passed keys in batch - * - * @param keys the keys - * @return deleted entities - */ - private Iterable deleteByKeysInBatch(Collection keys) { - final Object batch; - if (getDataStore() instanceof QueueingDataStore) { - log.debug("The data store support queueing, so we are going to start a batch"); - batch = ((QueueingDataStore) getDataStore()).startBatch(); - } else { - log.debug("The data store does not support batching, so this is the same as a normal delete"); - batch = null; - } - final List result = new LinkedList(); - for (Object key : keys) { - if (getDataStore().hasKey(key)) { - result.add(getDataStore().retrieve(key)); - getDataStore().delete(key); - } - } - if (getDataStore() instanceof QueueingDataStore) { - log.debug("Ending the batch operation that was started previously."); - ((QueueingDataStore) getDataStore()).endBatch(batch); - } - return result; + /** + * Deletes entities bound to the passed keys in batch + * + * @param keys the keys + * @return deleted entities + */ + private Iterable deleteByKeysInBatch(Collection keys) { + final Object batch; + if (getDataStore() instanceof QueueingDataStore) { + log.debug("The data store support queueing, so we are going to start a batch"); + batch = ((QueueingDataStore) getDataStore()).startBatch(); + } else { + log.debug("The data store does not support batching, so this is the same as a normal delete"); + batch = null; } - - /** - * Returns the entity that has the given key - * - * @param key the key - * @return returns the entity or {@literal null} if it couldn't be found - */ - public Object getOne(Object key) { - if (getDataStore().hasKey(key)) { - log.info("Returning entity for key " + key); - return getDataStore().retrieve(key); - } - log.info("No entity was found with key " + key); - return null; + final List result = new LinkedList(); + for (Object key : keys) { + if (getDataStore().hasKey(key)) { + result.add(getDataStore().retrieve(key)); + getDataStore().delete(key); + } + } + if (getDataStore() instanceof QueueingDataStore) { + log.debug("Ending the batch operation that was started previously."); + ((QueueingDataStore) getDataStore()).endBatch(batch); } + return result; + } - /** - * Saves the entity to the database and flushes the queue - * - * @param entity the entity - * @return the saved entity - */ - public Object saveAndFlush(Object entity) { - log.info("Saving entity " + entity + " to the data store."); - final Object saved = save(entity); - log.info("Going to flush the data store after the save"); - flush(); - return saved; + /** + * Returns the entity that has the given key + * + * @param key the key + * @return returns the entity or {@literal null} if it couldn't be found + */ + public Object getOne(Object key) { + if (getDataStore().hasKey(key)) { + log.info("Returning entity for key " + key); + return getDataStore().retrieve(key); } + log.info("No entity was found with key " + key); + return null; + } + /** + * Saves the entity to the database and flushes the queue + * + * @param entity the entity + * @return the saved entity + */ + public Object saveAndFlush(Object entity) { + log.info("Saving entity " + entity + " to the data store."); + final Object saved = save(entity); + log.info("Going to flush the data store after the save"); + flush(); + return saved; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultPagingAndSortingRepository.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultPagingAndSortingRepository.java index 2f30ec0e..bc7c6a98 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultPagingAndSortingRepository.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultPagingAndSortingRepository.java @@ -16,40 +16,40 @@ * @since 1.0 (10/12/15) */ @SuppressWarnings("WeakerAccess") -public class DefaultPagingAndSortingRepository extends PagingAndSortingSupport implements DataStoreAware { - - private static final Log log = LogFactory.getLog(DefaultPagingAndSortingRepository.class); - - private DataStore dataStore; - - /** - * Finds everything and sorts it using the given sort property - * - * @param sort how to sort the data - * @return sorted entries, unless sort is null. - */ - public List findAll(Sort sort) { - return PagingAndSortingUtils.sort(retrieveAll(), sort); - } - - /** - * Loads everything, sorts them, and pages the according to the spec. - * - * @param pageable the pagination and sort spec - * @return the specified view of the data - */ - public Page findAll(Pageable pageable) { - return page(retrieveAll(), pageable); - } - - @Override - public void setDataStore(DataStore dataStore) { - this.dataStore = dataStore; - } - - private Collection retrieveAll() { - log.info("Loading all the data in the data store"); - return dataStore.retrieveAll(); - } - +public class DefaultPagingAndSortingRepository extends PagingAndSortingSupport + implements DataStoreAware { + + private static final Log log = LogFactory.getLog(DefaultPagingAndSortingRepository.class); + + private DataStore dataStore; + + /** + * Finds everything and sorts it using the given sort property + * + * @param sort how to sort the data + * @return sorted entries, unless sort is null. + */ + public List findAll(Sort sort) { + return PagingAndSortingUtils.sort(retrieveAll(), sort); + } + + /** + * Loads everything, sorts them, and pages the according to the spec. + * + * @param pageable the pagination and sort spec + * @return the specified view of the data + */ + public Page findAll(Pageable pageable) { + return page(retrieveAll(), pageable); + } + + @Override + public void setDataStore(DataStore dataStore) { + this.dataStore = dataStore; + } + + private Collection retrieveAll() { + log.info("Loading all the data in the data store"); + return dataStore.retrieveAll(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryByExampleExecutor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryByExampleExecutor.java index 4d37bf0c..cbd71ac4 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryByExampleExecutor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryByExampleExecutor.java @@ -1,6 +1,10 @@ package com.mmnaseri.utils.spring.data.repository; -import com.mmnaseri.utils.spring.data.domain.*; +import com.mmnaseri.utils.spring.data.domain.DataStoreAware; +import com.mmnaseri.utils.spring.data.domain.Invocation; +import com.mmnaseri.utils.spring.data.domain.Parameter; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadataAware; import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation; import com.mmnaseri.utils.spring.data.domain.impl.SelectDataStoreOperation; import com.mmnaseri.utils.spring.data.error.InvalidArgumentException; @@ -11,7 +15,11 @@ import com.mmnaseri.utils.spring.data.query.QueryDescriptor; import com.mmnaseri.utils.spring.data.store.DataStore; import com.mmnaseri.utils.spring.data.tools.PropertyUtils; -import org.springframework.data.domain.*; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import java.util.ArrayList; import java.util.Collection; @@ -23,110 +31,119 @@ * @since 1.0 (6/8/16, 11:57 AM) */ public class DefaultQueryByExampleExecutor - implements DataStoreAware, RepositoryConfigurationAware, RepositoryMetadataAware, - RepositoryFactoryConfigurationAware { - - private DataStore dataStore; - private final ExampleMatcherQueryDescriptionExtractor queryDescriptionExtractor; - private RepositoryConfiguration repositoryConfiguration; - private RepositoryMetadata repositoryMetadata; - private RepositoryFactoryConfiguration configuration; - - public DefaultQueryByExampleExecutor() { - queryDescriptionExtractor = new ExampleMatcherQueryDescriptionExtractor(); - } - - public Object findOne(Example example) { - final Collection found = retrieveAll(example); - if (found.isEmpty()) { - return null; - } else if (found.size() > 1) { - throw new InvalidArgumentException("Expected to see exactly one item found, but found " + found.size() - + ". You should use a better example."); - } - return found.iterator().next(); - } - - public Iterable findAll(Example example) { - return retrieveAll(example); - } - - public Iterable findAll(Example example, Sort sort) { - return PagingAndSortingUtils.sort(retrieveAll(example), sort); - } - - public Page findAll(Example example, Pageable pageable) { - return PagingAndSortingUtils.page(retrieveAll(example), pageable); - } - - public long count(Example example) { - return retrieveAll(example).size(); - } - - public boolean exists(Example example) { - return count(example) > 0; - } - - @Override - public void setDataStore(DataStore dataStore) { - //noinspection unchecked - this.dataStore = dataStore; + implements DataStoreAware, + RepositoryConfigurationAware, + RepositoryMetadataAware, + RepositoryFactoryConfigurationAware { + + private final ExampleMatcherQueryDescriptionExtractor queryDescriptionExtractor; + private DataStore dataStore; + private RepositoryConfiguration repositoryConfiguration; + private RepositoryMetadata repositoryMetadata; + private RepositoryFactoryConfiguration configuration; + + public DefaultQueryByExampleExecutor() { + queryDescriptionExtractor = new ExampleMatcherQueryDescriptionExtractor(); + } + + public Object findOne(Example example) { + final Collection found = retrieveAll(example); + if (found.isEmpty()) { + return null; + } else if (found.size() > 1) { + throw new InvalidArgumentException( + "Expected to see exactly one item found, but found " + + found.size() + + ". You should use a better example."); } - - @Override - public void setRepositoryConfiguration(RepositoryConfiguration repositoryConfiguration) { - this.repositoryConfiguration = repositoryConfiguration; + return found.iterator().next(); + } + + public Iterable findAll(Example example) { + return retrieveAll(example); + } + + public Iterable findAll(Example example, Sort sort) { + return PagingAndSortingUtils.sort(retrieveAll(example), sort); + } + + public Page findAll(Example example, Pageable pageable) { + return PagingAndSortingUtils.page(retrieveAll(example), pageable); + } + + public long count(Example example) { + return retrieveAll(example).size(); + } + + public boolean exists(Example example) { + return count(example) > 0; + } + + @Override + public void setDataStore(DataStore dataStore) { + //noinspection unchecked + this.dataStore = dataStore; + } + + @Override + public void setRepositoryConfiguration(RepositoryConfiguration repositoryConfiguration) { + this.repositoryConfiguration = repositoryConfiguration; + } + + @Override + public void setRepositoryMetadata(RepositoryMetadata repositoryMetadata) { + this.repositoryMetadata = repositoryMetadata; + } + + @Override + public void setRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) { + this.configuration = configuration; + } + + /** + * Retrieves all entities that match the given example + * + * @param example the example for finding the entities + * @return a collection of matched entities + */ + private Collection retrieveAll(Example example) { + final QueryDescriptor descriptor = + queryDescriptionExtractor.extract(repositoryMetadata, configuration, example); + final Invocation invocation = createInvocation(descriptor, example); + final SelectDataStoreOperation select = + new SelectDataStoreOperation<>(descriptor); + return select.execute(dataStore, repositoryConfiguration, invocation); + } + + /** + * This method will create an invocation that had it occurred on a query method would provide + * sufficient data for a parsed query method expression to be evaluated + * + * @param descriptor the query descriptor + * @param example the example that is used for evaluation + * @return the fake method invocation corresponding to the example probe + */ + private Invocation createInvocation(QueryDescriptor descriptor, Example example) { + final List values = new ArrayList<>(); + // since according to + // http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example + // the matcher only supports AND condition, so, we expect to see only one branch + final List> branches = descriptor.getBranches(); + final List parameters = branches.get(0); + for (Parameter parameter : parameters) { + final String propertyPath = parameter.getPath(); + final Object propertyValue = PropertyUtils.getPropertyValue(example.getProbe(), propertyPath); + final ExampleMatcher.PropertySpecifier specifier = + example.getMatcher().getPropertySpecifiers().getForPath(propertyPath); + //noinspection ConstantConditions + values.add( + specifier == null + ? propertyValue + : specifier + .getPropertyValueTransformer() + .apply(Optional.ofNullable(propertyValue)) + .orElse(null)); } - - @Override - public void setRepositoryMetadata(RepositoryMetadata repositoryMetadata) { - this.repositoryMetadata = repositoryMetadata; - } - - @Override - public void setRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) { - this.configuration = configuration; - } - - /** - * Retrieves all entities that match the given example - * - * @param example the example for finding the entities - * @return a collection of matched entities - */ - private Collection retrieveAll(Example example) { - final QueryDescriptor descriptor = queryDescriptionExtractor.extract(repositoryMetadata, configuration, - example); - final Invocation invocation = createInvocation(descriptor, example); - final SelectDataStoreOperation select = new SelectDataStoreOperation<>(descriptor); - return select.execute(dataStore, repositoryConfiguration, invocation); - } - - /** - * This method will create an invocation that had it occurred on a query method would provide sufficient data for a - * parsed query method expression to be evaluated - * - * @param descriptor the query descriptor - * @param example the example that is used for evaluation - * @return the fake method invocation corresponding to the example probe - */ - private Invocation createInvocation(QueryDescriptor descriptor, Example example) { - final List values = new ArrayList<>(); - //since according to http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example - //the matcher only supports AND condition, so, we expect to see only one branch - final List> branches = descriptor.getBranches(); - final List parameters = branches.get(0); - for (Parameter parameter : parameters) { - final String propertyPath = parameter.getPath(); - final Object propertyValue = PropertyUtils.getPropertyValue(example.getProbe(), propertyPath); - final ExampleMatcher.PropertySpecifier specifier = example.getMatcher().getPropertySpecifiers().getForPath( - propertyPath); - //noinspection ConstantConditions - values.add(specifier == null ? propertyValue - : specifier.getPropertyValueTransformer().apply(Optional.ofNullable(propertyValue)) - .orElse(null)); - } - return new ImmutableInvocation(null, values.toArray()); - } - + return new ImmutableInvocation(null, values.toArray()); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryDslPredicateExecutor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryDslPredicateExecutor.java index 037b683f..5f2c44a2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryDslPredicateExecutor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryDslPredicateExecutor.java @@ -14,56 +14,64 @@ /** * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (4/28/16) - * @deprecated This class is kept for backward compilation compatibility, however, it is not functional as of version - * 2.0. */ -@Deprecated -public class DefaultQueryDslPredicateExecutor extends PagingAndSortingSupport implements DataStoreAware { +public class DefaultQueryDslPredicateExecutor extends PagingAndSortingSupport + implements DataStoreAware { - private DataStore dataStore; - private Object alias; + private DataStore dataStore; + private Object alias; - public Object findOne(Predicate predicate) { - return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)).fetchOne(); - } + public Object findOne(Predicate predicate) { + return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)) + .fetchOne(); + } - public Iterable findAll(Predicate predicate) { - return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)).fetch(); - } + public Iterable findAll(Predicate predicate) { + return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)) + .fetch(); + } - public Iterable findAll(Predicate predicate, Sort sort) { - return PagingAndSortingUtils.sort(((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where( - predicate)).fetch(), sort); - } + public Iterable findAll(Predicate predicate, Sort sort) { + return PagingAndSortingUtils.sort( + ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)) + .fetch(), + sort); + } - public Page findAll(Predicate predicate, Pageable pageable) { - return page(((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)).fetch(), - pageable); - } + public Page findAll(Predicate predicate, Pageable pageable) { + return page( + ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)) + .fetch(), + pageable); + } - public long count(Predicate predicate) { - return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)).fetchCount(); - } + public long count(Predicate predicate) { + return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)) + .fetchCount(); + } - public boolean exists(Predicate predicate) { - return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)).fetchCount() > 0; - } + public boolean exists(Predicate predicate) { + return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate)) + .fetchCount() + > 0; + } - public Iterable findAll(OrderSpecifier... orders) { - //noinspection unchecked - return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).orderBy(orders)).fetch(); - } + public Iterable findAll(OrderSpecifier... orders) { + //noinspection unchecked + return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).orderBy(orders)) + .fetch(); + } - public Iterable findAll(Predicate predicate, OrderSpecifier... orders) { - //noinspection unchecked - return ((CollQuery) CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate).orderBy(orders)) - .fetch(); - } - - @Override - public void setDataStore(DataStore dataStore) { - this.dataStore = dataStore; - this.alias = Alias.alias(dataStore.getEntityType()); - } + public Iterable findAll(Predicate predicate, OrderSpecifier... orders) { + //noinspection unchecked + return ((CollQuery) + CollQueryFactory.from(alias, dataStore.retrieveAll()).where(predicate).orderBy(orders)) + .fetch(); + } + @Override + public void setDataStore(DataStore dataStore) { + this.dataStore = dataStore; + this.alias = Alias.alias(dataStore.getEntityType()); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/ExampleMatcherQueryDescriptionExtractor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/ExampleMatcherQueryDescriptionExtractor.java index 234db048..6d6e811b 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/ExampleMatcherQueryDescriptionExtractor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/ExampleMatcherQueryDescriptionExtractor.java @@ -1,6 +1,10 @@ package com.mmnaseri.utils.spring.data.repository; -import com.mmnaseri.utils.spring.data.domain.*; +import com.mmnaseri.utils.spring.data.domain.Modifier; +import com.mmnaseri.utils.spring.data.domain.Operator; +import com.mmnaseri.utils.spring.data.domain.OperatorContext; +import com.mmnaseri.utils.spring.data.domain.Parameter; +import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata; import com.mmnaseri.utils.spring.data.domain.impl.ImmutableParameter; import com.mmnaseri.utils.spring.data.domain.impl.QueryDescriptionExtractor; import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration; @@ -13,7 +17,13 @@ import org.springframework.data.domain.ExampleMatcher; import java.beans.PropertyDescriptor; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -21,105 +31,121 @@ */ public class ExampleMatcherQueryDescriptionExtractor implements QueryDescriptionExtractor { - @Override - public QueryDescriptor extract(RepositoryMetadata repositoryMetadata, RepositoryFactoryConfiguration configuration, - Example example) { - final OperatorContext operatorContext = configuration.getDescriptionExtractor().getOperatorContext(); - final Map values = extractValues(example.getProbe()); - final ExampleMatcher matcher = example.getMatcher(); - final List parameters = new ArrayList<>(); - int index = 0; - for (Map.Entry entry : values.entrySet()) { - final String propertyPath = entry.getKey(); - if (matcher.isIgnoredPath(propertyPath)) { - continue; - } - final Set modifiers = new HashSet<>(); - final Operator operator; - if (entry.getValue() == null) { - if (ExampleMatcher.NullHandler.IGNORE.equals(matcher.getNullHandler())) { - continue; - } else { - operator = operatorContext.getBySuffix("IsNull"); - } - } else { - if (ignoreCase(matcher, propertyPath)) { - modifiers.add(Modifier.IGNORE_CASE); - } - final ExampleMatcher.StringMatcher stringMatcher = stringMatcher(matcher, propertyPath); - if (ExampleMatcher.StringMatcher.STARTING.equals(stringMatcher)) { - operator = operatorContext.getBySuffix("StartsWith"); - } else if (ExampleMatcher.StringMatcher.ENDING.equals(stringMatcher)) { - operator = operatorContext.getBySuffix("EndsWith"); - } else if (ExampleMatcher.StringMatcher.CONTAINING.equals(stringMatcher)) { - operator = operatorContext.getBySuffix("Contains"); - } else if (ExampleMatcher.StringMatcher.REGEX.equals(stringMatcher)) { - operator = operatorContext.getBySuffix("Matches"); - } else { - operator = operatorContext.getBySuffix("Is"); - } - } - parameters.add(new ImmutableParameter(propertyPath, modifiers, new int[]{index++}, operator)); + @Override + public QueryDescriptor extract( + RepositoryMetadata repositoryMetadata, + RepositoryFactoryConfiguration configuration, + Example example) { + final OperatorContext operatorContext = + configuration.getDescriptionExtractor().getOperatorContext(); + final Map values = extractValues(example.getProbe()); + final ExampleMatcher matcher = example.getMatcher(); + final List parameters = new ArrayList<>(); + int index = 0; + for (Map.Entry entry : values.entrySet()) { + final String propertyPath = entry.getKey(); + if (matcher.isIgnoredPath(propertyPath)) { + continue; + } + final Set modifiers = new HashSet<>(); + final Operator operator; + if (entry.getValue() == null) { + if (ExampleMatcher.NullHandler.IGNORE.equals(matcher.getNullHandler())) { + continue; + } else { + operator = operatorContext.getBySuffix("IsNull"); } - return new DefaultQueryDescriptor(false, null, 0, null, null, Collections.singletonList(parameters), - configuration, repositoryMetadata); + } else { + if (ignoreCase(matcher, propertyPath)) { + modifiers.add(Modifier.IGNORE_CASE); + } + final ExampleMatcher.StringMatcher stringMatcher = stringMatcher(matcher, propertyPath); + if (ExampleMatcher.StringMatcher.STARTING.equals(stringMatcher)) { + operator = operatorContext.getBySuffix("StartsWith"); + } else if (ExampleMatcher.StringMatcher.ENDING.equals(stringMatcher)) { + operator = operatorContext.getBySuffix("EndsWith"); + } else if (ExampleMatcher.StringMatcher.CONTAINING.equals(stringMatcher)) { + operator = operatorContext.getBySuffix("Contains"); + } else if (ExampleMatcher.StringMatcher.REGEX.equals(stringMatcher)) { + operator = operatorContext.getBySuffix("Matches"); + } else { + operator = operatorContext.getBySuffix("Is"); + } + } + parameters.add( + new ImmutableParameter(propertyPath, modifiers, new int[] {index++}, operator)); } + return new DefaultQueryDescriptor( + false, + null, + 0, + null, + null, + Collections.singletonList(parameters), + configuration, + repositoryMetadata); + } - private ExampleMatcher.StringMatcher stringMatcher(ExampleMatcher matcher, String path) { - final ExampleMatcher.PropertySpecifier specifier = matcher.getPropertySpecifiers().getForPath(path); - //noinspection ConstantConditions - return specifier != null ? specifier.getStringMatcher() : matcher.getDefaultStringMatcher(); - } + private ExampleMatcher.StringMatcher stringMatcher(ExampleMatcher matcher, String path) { + final ExampleMatcher.PropertySpecifier specifier = + matcher.getPropertySpecifiers().getForPath(path); + //noinspection ConstantConditions + return specifier != null ? specifier.getStringMatcher() : matcher.getDefaultStringMatcher(); + } - private boolean ignoreCase(ExampleMatcher matcher, String path) { - final ExampleMatcher.PropertySpecifier specifier = matcher.getPropertySpecifiers().getForPath(path); - //noinspection ConstantConditions - return matcher.isIgnoreCaseEnabled() || specifier != null && Boolean.TRUE.equals(specifier.getIgnoreCase()); - } - - /** - * Given an input object, this method will return a map from the property paths to their corresponding values - * - * @param object the input object - * @return the map of values - */ - private Map extractValues(Object object) { - final Map result = new HashMap<>(); - final BeanWrapper wrapper = new BeanWrapperImpl(object); - for (PropertyDescriptor descriptor : wrapper.getPropertyDescriptors()) { - if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) { - continue; - } - final String propertyName = descriptor.getName(); - final Object value = PropertyUtils.getPropertyValue(object, propertyName); - if (value == null) { - result.put(propertyName, null); - continue; - } - if (isIntractable(descriptor, value)) { - result.put(propertyName, value); - continue; - } - final Map children = extractValues(value); - for (Map.Entry entry : children.entrySet()) { - result.put(propertyName + "." + entry.getKey(), entry.getValue()); - } - } - return result; - } + private boolean ignoreCase(ExampleMatcher matcher, String path) { + final ExampleMatcher.PropertySpecifier specifier = + matcher.getPropertySpecifiers().getForPath(path); + //noinspection ConstantConditions + return matcher.isIgnoreCaseEnabled() + || specifier != null && Boolean.TRUE.equals(specifier.getIgnoreCase()); + } - /** - * This method is used to determine if a given value should be broken down further or should it be passed in as it - * is - * - * @param descriptor the descriptor for the property - * @param value the value for the property - * @return {@literal true} if the value should be left alone - */ - private boolean isIntractable(PropertyDescriptor descriptor, Object value) { - final Class type = descriptor.getPropertyType(); - return type.isPrimitive() || type.getName().startsWith("java.lang.") || value instanceof Iterable - || value instanceof Map; + /** + * Given an input object, this method will return a map from the property paths to their + * corresponding values + * + * @param object the input object + * @return the map of values + */ + private Map extractValues(Object object) { + final Map result = new HashMap<>(); + final BeanWrapper wrapper = new BeanWrapperImpl(object); + for (PropertyDescriptor descriptor : wrapper.getPropertyDescriptors()) { + if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) { + continue; + } + final String propertyName = descriptor.getName(); + final Object value = PropertyUtils.getPropertyValue(object, propertyName); + if (value == null) { + result.put(propertyName, null); + continue; + } + if (isIntractable(descriptor, value)) { + result.put(propertyName, value); + continue; + } + final Map children = extractValues(value); + for (Map.Entry entry : children.entrySet()) { + result.put(propertyName + "." + entry.getKey(), entry.getValue()); + } } + return result; + } + /** + * This method is used to determine if a given value should be broken down further or should it be + * passed in as it is + * + * @param descriptor the descriptor for the property + * @param value the value for the property + * @return {@literal true} if the value should be left alone + */ + private boolean isIntractable(PropertyDescriptor descriptor, Object value) { + final Class type = descriptor.getPropertyType(); + return type.isPrimitive() + || type.getName().startsWith("java.lang.") + || value instanceof Iterable + || value instanceof Map; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/PagingAndSortingSupport.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/PagingAndSortingSupport.java index 105b8d08..7acc5f8d 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/PagingAndSortingSupport.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/PagingAndSortingSupport.java @@ -11,8 +11,7 @@ */ public abstract class PagingAndSortingSupport { - public static Page page(Collection entries, Pageable pageable) { - return PagingAndSortingUtils.page(entries, pageable); - } - + public static Page page(Collection entries, Pageable pageable) { + return PagingAndSortingUtils.page(entries, pageable); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/PagingAndSortingUtils.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/PagingAndSortingUtils.java index d71fb996..2075d3f6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/PagingAndSortingUtils.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/PagingAndSortingUtils.java @@ -23,76 +23,83 @@ */ final class PagingAndSortingUtils { - private static final Log log = LogFactory.getLog(PagingAndSortingUtils.class); + private static final Log log = LogFactory.getLog(PagingAndSortingUtils.class); - private PagingAndSortingUtils() { - throw new UnsupportedOperationException(); - } + private PagingAndSortingUtils() { + throw new UnsupportedOperationException(); + } - /** - * Finds everything and sorts it using the given sort property - * - * @param entries the entries to be sorted - * @param sort how to sort the data - * @return sorted entries, unless sort is null. - */ - public static List sort(Collection entries, Sort sort) { - //noinspection unchecked - final List list = new LinkedList(entries); - if (sort == null) { - log.info("No sort was specified, so we are just going to return the data as-is"); - return list; - } - final List orders = new LinkedList<>(); - for (Sort.Order order : sort) { - final SortDirection direction = order.getDirection().equals(Sort.Direction.ASC) ? SortDirection.ASCENDING - : SortDirection.DESCENDING; - final NullHandling nullHandling; - switch (order.getNullHandling()) { - case NULLS_FIRST: - nullHandling = NullHandling.NULLS_FIRST; - break; - case NULLS_LAST: - nullHandling = NullHandling.NULLS_LAST; - break; - default: - nullHandling = NullHandling.DEFAULT; - break; - } - final Order derivedOrder = new ImmutableOrder(direction, order.getProperty(), nullHandling); - orders.add(derivedOrder); - } - log.info("Sorting the retrieved data: " + orders); - PropertyComparator.sort(list, new ImmutableSort(orders)); - return list; + /** + * Finds everything and sorts it using the given sort property + * + * @param entries the entries to be sorted + * @param sort how to sort the data + * @return sorted entries, unless sort is null. + */ + public static List sort(Collection entries, Sort sort) { + //noinspection unchecked + final List list = new LinkedList(entries); + if (sort == null) { + log.info("No sort was specified, so we are just going to return the data as-is"); + return list; } - - /** - * Loads everything, sorts them, and pages the according to the spec. - * - * @param entries the entries to be paged - * @param pageable the pagination and sort spec - * @return the specified view of the data - */ - public static Page page(Collection entries, Pageable pageable) { - final List all; - if (pageable.getSort().isSorted()) { - log.info("The page specification requests sorting, so we are going to sort the data first"); - all = sort(entries, pageable.getSort()); - } else { - log.info("The page specification does not need sorting, so we are going to load the data as-is"); - //noinspection unchecked - all = new LinkedList(entries); - } - int start = Math.max(0, pageable.getPageNumber() * pageable.getPageSize()); - int end = start + pageable.getPageSize(); - start = Math.min(start, all.size()); - end = Math.min(end, all.size()); - log.info("Trimming the selection down for page " + pageable.getPageNumber() + " to include items from " + start - + " to " + end); - final List selection = new LinkedList<>(all.subList(start, end)); - //noinspection unchecked - return new PageImpl(selection, pageable, all.size()); + final List orders = new LinkedList<>(); + for (Sort.Order order : sort) { + final SortDirection direction = + order.getDirection().equals(Sort.Direction.ASC) + ? SortDirection.ASCENDING + : SortDirection.DESCENDING; + final NullHandling nullHandling; + switch (order.getNullHandling()) { + case NULLS_FIRST: + nullHandling = NullHandling.NULLS_FIRST; + break; + case NULLS_LAST: + nullHandling = NullHandling.NULLS_LAST; + break; + default: + nullHandling = NullHandling.DEFAULT; + break; + } + final Order derivedOrder = new ImmutableOrder(direction, order.getProperty(), nullHandling); + orders.add(derivedOrder); } + log.info("Sorting the retrieved data: " + orders); + PropertyComparator.sort(list, new ImmutableSort(orders)); + return list; + } + /** + * Loads everything, sorts them, and pages the according to the spec. + * + * @param entries the entries to be paged + * @param pageable the pagination and sort spec + * @return the specified view of the data + */ + public static Page page(Collection entries, Pageable pageable) { + final List all; + if (pageable.getSort().isSorted()) { + log.info("The page specification requests sorting, so we are going to sort the data first"); + all = sort(entries, pageable.getSort()); + } else { + log.info( + "The page specification does not need sorting, so we are going to load the data as-is"); + //noinspection unchecked + all = new LinkedList(entries); + } + int start = Math.max(0, pageable.getPageNumber() * pageable.getPageSize()); + int end = start + pageable.getPageSize(); + start = Math.min(start, all.size()); + end = Math.min(end, all.size()); + log.info( + "Trimming the selection down for page " + + pageable.getPageNumber() + + " to include items from " + + start + + " to " + + end); + final List selection = new LinkedList<>(all.subList(start, end)); + //noinspection unchecked + return new PageImpl(selection, pageable, all.size()); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/package-info.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/package-info.java index 348602d5..c293c36f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/package-info.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/repository/package-info.java @@ -1,11 +1,13 @@ /** - *

This package implements the bridge pattern over the various repository interfaces in the Spring Data project. - * Each class should represent exactly one repository interface in the Spring data project.

+ * This package implements the bridge pattern over the various repository interfaces in the Spring + * Data project. Each class should represent exactly one repository interface in the Spring data + * project. * - *

Many of the interfaces in the Spring data project come with their own packaging and project. We have to check - * for the presence of such an interface before adding the bridge for it to the classpath.

+ *

Many of the interfaces in the Spring data project come with their own packaging and project. + * We have to check for the presence of such an interface before adding the bridge for it to the + * classpath. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (4/12/16, 8:47 PM) */ -package com.mmnaseri.utils.spring.data.repository; \ No newline at end of file +package com.mmnaseri.utils.spring.data.repository; diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStore.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStore.java index ab5f3788..51da75fc 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStore.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStore.java @@ -10,64 +10,57 @@ */ public interface DataStore { - /** - * Determines whether or not an entity with the given key exists in the data store. - * - * @param key the key - * @return {@literal boolean} if such a key is known by the data store - */ - boolean hasKey(K key); + /** + * Determines whether or not an entity with the given key exists in the data store. + * + * @param key the key + * @return {@literal boolean} if such a key is known by the data store + */ + boolean hasKey(K key); - /** - * Saves the given entity into the data store under the provided key. Whether or not the key is actually used by the - * data store in some sort of mapping does not matter. The only expectation is that after this call, should the save - * be successful a call to {@link #hasKey(Object)} should yield {@literal true} and the very same entity (or an - * equal value entity) can be retrieved by calling {@link #retrieve(Object)}. - * - * @param key the key - * @param entity the entity - * @return {@literal true} to indicate the entity was a new entry, and {@literal false} to indicate another entity - * had to be replaced/updated with the provided entity - */ - boolean save(K key, E entity); + /** + * Saves the given entity into the data store under the provided key. Whether or not the key is + * actually used by the data store in some sort of mapping does not matter. The only expectation + * is that after this call, should the save be successful a call to {@link #hasKey(Object)} should + * yield {@literal true} and the very same entity (or an equal value entity) can be retrieved by + * calling {@link #retrieve(Object)}. + * + * @param key the key + * @param entity the entity + * @return {@literal true} to indicate the entity was a new entry, and {@literal false} to + * indicate another entity had to be replaced/updated with the provided entity + */ + boolean save(K key, E entity); - /** - * Deletes the entity identifiable with the provided key, or does nothing if no such entity exists. It is expected - * that as a side effect, once this method returns successfully, {@link #hasKey(Object)} should return {@literal - * false} and {@link #retrieve(Object)} should return {@literal null} for the same key. - * - * @param key the key for which the removal should happen - * @return {@literal true} to indicate the entity was located and removed and {@literal false} to indicate that no - * such entity existed in the first place. - */ - boolean delete(K key); + /** + * Deletes the entity identifiable with the provided key, or does nothing if no such entity + * exists. It is expected that as a side effect, once this method returns successfully, {@link + * #hasKey(Object)} should return {@literal false} and {@link #retrieve(Object)} should return + * {@literal null} for the same key. + * + * @param key the key for which the removal should happen + * @return {@literal true} to indicate the entity was located and removed and {@literal false} to + * indicate that no such entity existed in the first place. + */ + boolean delete(K key); - /** - * Given a key, retrieves the entity associated with that key in the data store. - * - * @param key the key - * @return the entity or {@literal null} if no such entity could be found - */ - E retrieve(K key); + /** + * Given a key, retrieves the entity associated with that key in the data store. + * + * @param key the key + * @return the entity or {@literal null} if no such entity could be found + */ + E retrieve(K key); - /** - * @return a collection of all the keys registered in the data store. - */ - Collection keys(); + /** @return a collection of all the keys registered in the data store. */ + Collection keys(); - /** - * @return retrieves all the entities in the data store - */ - Collection retrieveAll(); + /** @return retrieves all the entities in the data store */ + Collection retrieveAll(); - /** - * @return the entity type bound to this data store - */ - Class getEntityType(); - - /** - * Does a hard remove of all the entities in the data store - */ - void truncate(); + /** @return the entity type bound to this data store */ + Class getEntityType(); + /** Does a hard remove of all the entities in the data store */ + void truncate(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEvent.java index b53bf86a..b1221d3f 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEvent.java @@ -10,14 +10,9 @@ */ public interface DataStoreEvent { - /** - * @return the repository metadata associated with the given data store - */ - RepositoryMetadata getRepositoryMetadata(); - - /** - * @return the data store that triggered this event - */ - DataStore getDataStore(); + /** @return the repository metadata associated with the given data store */ + RepositoryMetadata getRepositoryMetadata(); + /** @return the data store that triggered this event */ + DataStore getDataStore(); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListener.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListener.java index dea7de4d..eab0bc55 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListener.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListener.java @@ -9,11 +9,10 @@ */ public interface DataStoreEventListener { - /** - * Will be called by the data store when a relevant event happens - * - * @param event the event that has taken place - */ - void onEvent(E event); - + /** + * Will be called by the data store when a relevant event happens + * + * @param event the event that has taken place + */ + void onEvent(E event); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListenerContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListenerContext.java index 389b12b1..8834dec7 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListenerContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventListenerContext.java @@ -10,28 +10,29 @@ */ public interface DataStoreEventListenerContext { - /** - * Registers a new listener - * - * @param listener the listener - * @param the type of events to which the listener wants to subscribe - */ - void register(DataStoreEventListener listener); + /** + * Registers a new listener + * + * @param listener the listener + * @param the type of events to which the listener wants to subscribe + */ + void register(DataStoreEventListener listener); - /** - * Triggers an event on the context - * - * @param event the event - */ - void trigger(DataStoreEvent event); - - /** - * Returns a list of all event listeners that would be triggered by an event of the given type through this context - * - * @param eventType the event type - * @param the event type - * @return a list of listeners in the order in which they would be called - */ - List> getListeners(Class eventType); + /** + * Triggers an event on the context + * + * @param event the event + */ + void trigger(DataStoreEvent event); + /** + * Returns a list of all event listeners that would be triggered by an event of the given type + * through this context + * + * @param eventType the event type + * @param the event type + * @return a list of listeners in the order in which they would be called + */ + List> getListeners( + Class eventType); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventPublisher.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventPublisher.java index de2e95f3..5d1ba1f6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventPublisher.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreEventPublisher.java @@ -9,11 +9,10 @@ @SuppressWarnings("unused") public interface DataStoreEventPublisher { - /** - * This method is called to publish a data store event - * - * @param event the event that should be published - */ - void publishEvent(DataStoreEvent event); - + /** + * This method is called to publish a data store event + * + * @param event the event that should be published + */ + void publishEvent(DataStoreEvent event); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreOperation.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreOperation.java index ffd3799e..b6e7aa05 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreOperation.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreOperation.java @@ -11,14 +11,13 @@ */ public interface DataStoreOperation { - /** - * Called to trigger the actual operation - * - * @param store the data store on which this operation is taking place - * @param configuration the configuration for the data store - * @param invocation the invocation that triggered this operation - * @return the result of the operation - */ - R execute(DataStore store, RepositoryConfiguration configuration, Invocation invocation); - + /** + * Called to trigger the actual operation + * + * @param store the data store on which this operation is taking place + * @param configuration the configuration for the data store + * @param invocation the invocation that triggered this operation + * @return the result of the operation + */ + R execute(DataStore store, RepositoryConfiguration configuration, Invocation invocation); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreRegistry.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreRegistry.java index 5e2d3121..779aabbd 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreRegistry.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/DataStoreRegistry.java @@ -8,34 +8,35 @@ */ public interface DataStoreRegistry { - /** - * Registers a new data store. Note that you can override an existing data store for an entity by registering - * another one that supports the same sort of entity. - * - * @param dataStore the data store - * @param the type of the entities - * @param the type of the keys - */ - void register(DataStore dataStore); + /** + * Registers a new data store. Note that you can override an existing data store for an entity by + * registering another one that supports the same sort of entity. + * + * @param dataStore the data store + * @param the type of the entities + * @param the type of the keys + */ + void register(DataStore dataStore); - /** - * Finds the data store for the given entity type - * - * @param entityType the entity type - * @param the type of the entities - * @param the type of the keys - * @return the data store that can handle the provided type of entity - * @throws com.mmnaseri.utils.spring.data.error.DataStoreNotFoundException if no data store can be found for the - * given entity type - */ - DataStore getDataStore(Class entityType); - - /** - * Used to determine whether or not a data store has been registered that supports the given entity type. - * - * @param entityType the entity type - * @return {@literal true} to indicate that the entity type has a corresponding data store in this registry - */ - boolean has(Class entityType); + /** + * Finds the data store for the given entity type + * + * @param entityType the entity type + * @param the type of the entities + * @param the type of the keys + * @return the data store that can handle the provided type of entity + * @throws com.mmnaseri.utils.spring.data.error.DataStoreNotFoundException if no data store can be + * found for the given entity type + */ + DataStore getDataStore(Class entityType); + /** + * Used to determine whether or not a data store has been registered that supports the given + * entity type. + * + * @param entityType the entity type + * @return {@literal true} to indicate that the entity type has a corresponding data store in this + * registry + */ + boolean has(Class entityType); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/QueueingDataStore.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/QueueingDataStore.java index 57a71168..339f0ad0 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/QueueingDataStore.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/QueueingDataStore.java @@ -1,33 +1,31 @@ package com.mmnaseri.utils.spring.data.store; /** - * This interface indicates that the implementing data store has queueing capabilities and can thus be called upon to - * flush the queue and commit the results, and more over, handle operations in batches by refraining to flush the queue - * automatically while a batch is in progress. + * This interface indicates that the implementing data store has queueing capabilities and can thus + * be called upon to flush the queue and commit the results, and more over, handle operations in + * batches by refraining to flush the queue automatically while a batch is in progress. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (4/11/16, 1:18 PM) */ public interface QueueingDataStore extends DataStore { - /** - * Should be called to manually trigger a flush - */ - void flush(); + /** Should be called to manually trigger a flush */ + void flush(); - /** - * Starts a batch - * - * @return returns a key that can be used to identify this batch and {@link #endBatch(Object) end it} - */ - B startBatch(); - - /** - * Ends the indicated batch. Note that ending the batch does not necessarily flush the queue if the threshold for - * the underlying data store has not been reached. - * - * @param batch the batch to end - */ - void endBatch(B batch); + /** + * Starts a batch + * + * @return returns a key that can be used to identify this batch and {@link #endBatch(Object) end + * it} + */ + B startBatch(); + /** + * Ends the indicated batch. Note that ending the batch does not necessarily flush the queue if + * the threshold for the underlying data store has not been reached. + * + * @param batch the batch to end + */ + void endBatch(B batch); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractDataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractDataStoreEvent.java index 122f9549..71a92bef 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractDataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractDataStoreEvent.java @@ -13,21 +13,21 @@ @SuppressWarnings("WeakerAccess") public abstract class AbstractDataStoreEvent implements DataStoreEvent { - private final RepositoryMetadata repositoryMetadata; - private final DataStore dataStore; + private final RepositoryMetadata repositoryMetadata; + private final DataStore dataStore; - public AbstractDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore) { - this.repositoryMetadata = repositoryMetadata; - this.dataStore = dataStore; - } + public AbstractDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore) { + this.repositoryMetadata = repositoryMetadata; + this.dataStore = dataStore; + } - @Override - public RepositoryMetadata getRepositoryMetadata() { - return repositoryMetadata; - } + @Override + public RepositoryMetadata getRepositoryMetadata() { + return repositoryMetadata; + } - @Override - public DataStore getDataStore() { - return dataStore; - } + @Override + public DataStore getDataStore() { + return dataStore; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractEntityDataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractEntityDataStoreEvent.java index 7223bfb3..ee1f6875 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractEntityDataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AbstractEntityDataStoreEvent.java @@ -4,7 +4,8 @@ import com.mmnaseri.utils.spring.data.store.DataStore; /** - * This class is the base class for any data store event that indicates a particular entity was involved in the event. + * This class is the base class for any data store event that indicates a particular entity was + * involved in the event. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/6/15) @@ -12,16 +13,15 @@ @SuppressWarnings("WeakerAccess") public abstract class AbstractEntityDataStoreEvent extends AbstractDataStoreEvent { - private final Object entity; + private final Object entity; - public AbstractEntityDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore, - Object entity) { - super(repositoryMetadata, dataStore); - this.entity = entity; - } - - public Object getEntity() { - return entity; - } + public AbstractEntityDataStoreEvent( + RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { + super(repositoryMetadata, dataStore); + this.entity = entity; + } + public Object getEntity() { + return entity; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterDeleteDataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterDeleteDataStoreEvent.java index 02baf76f..0da91ec2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterDeleteDataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterDeleteDataStoreEvent.java @@ -12,8 +12,8 @@ @SuppressWarnings("WeakerAccess") public class AfterDeleteDataStoreEvent extends AbstractEntityDataStoreEvent { - public AfterDeleteDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { - super(repositoryMetadata, dataStore, entity); - } - + public AfterDeleteDataStoreEvent( + RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { + super(repositoryMetadata, dataStore, entity); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterInsertDataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterInsertDataStoreEvent.java index 893e8aba..5d18f6c2 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterInsertDataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterInsertDataStoreEvent.java @@ -12,8 +12,8 @@ @SuppressWarnings("WeakerAccess") public class AfterInsertDataStoreEvent extends AbstractEntityDataStoreEvent { - public AfterInsertDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { - super(repositoryMetadata, dataStore, entity); - } - + public AfterInsertDataStoreEvent( + RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { + super(repositoryMetadata, dataStore, entity); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterUpdateDataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterUpdateDataStoreEvent.java index 569a8dc9..e378dd84 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterUpdateDataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AfterUpdateDataStoreEvent.java @@ -12,8 +12,8 @@ @SuppressWarnings("WeakerAccess") public class AfterUpdateDataStoreEvent extends AbstractEntityDataStoreEvent { - public AfterUpdateDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { - super(repositoryMetadata, dataStore, entity); - } - + public AfterUpdateDataStoreEvent( + RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { + super(repositoryMetadata, dataStore, entity); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListener.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListener.java index 4844dd86..9271bcb6 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListener.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListener.java @@ -9,59 +9,61 @@ import java.time.Instant; /** - * This event listener can be registered with an - * {@link com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext - * event listener context} to add support for auditing entities as per the specifications set forth by Spring Data - * Commons. + * This event listener can be registered with an {@link + * com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext event listener context} to add + * support for auditing entities as per the specifications set forth by Spring Data Commons. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/12/15) */ public class AuditDataEventListener implements DataStoreEventListener { - private final AuditorAware auditorAware; + private final AuditorAware auditorAware; - public AuditDataEventListener(AuditorAware auditorAware) { - this.auditorAware = auditorAware; - } + public AuditDataEventListener(AuditorAware auditorAware) { + this.auditorAware = auditorAware; + } - @SuppressWarnings({"unchecked", "ConstantConditions"}) - @Override - public void onEvent(DataStoreEvent event) { - if (event instanceof BeforeInsertDataStoreEvent) { - final Object entity = ((BeforeInsertDataStoreEvent) event).getEntity(); - final Auditable wrapper = getAuditable(entity, event.getRepositoryMetadata()); - wrapper.setCreatedBy(auditorAware == null ? null : auditorAware.getCurrentAuditor().orElse(null)); - wrapper.setCreatedDate(Instant.now()); - } else if (event instanceof BeforeUpdateDataStoreEvent) { - final Object entity = ((BeforeUpdateDataStoreEvent) event).getEntity(); - final Auditable wrapper = getAuditable(entity, event.getRepositoryMetadata()); - wrapper.setLastModifiedBy(auditorAware == null ? null : auditorAware.getCurrentAuditor().orElse(null)); - wrapper.setLastModifiedDate(Instant.now()); - } + @SuppressWarnings({"unchecked", "ConstantConditions"}) + @Override + public void onEvent(DataStoreEvent event) { + if (event instanceof BeforeInsertDataStoreEvent) { + final Object entity = ((BeforeInsertDataStoreEvent) event).getEntity(); + final Auditable wrapper = getAuditable(entity, event.getRepositoryMetadata()); + wrapper.setCreatedBy( + auditorAware == null ? null : auditorAware.getCurrentAuditor().orElse(null)); + wrapper.setCreatedDate(Instant.now()); + } else if (event instanceof BeforeUpdateDataStoreEvent) { + final Object entity = ((BeforeUpdateDataStoreEvent) event).getEntity(); + final Auditable wrapper = getAuditable(entity, event.getRepositoryMetadata()); + wrapper.setLastModifiedBy( + auditorAware == null ? null : auditorAware.getCurrentAuditor().orElse(null)); + wrapper.setLastModifiedDate(Instant.now()); } + } - /** - * Given an entity returns an {@link Auditable} for it. If the entity itself implements that interface, it will be - * returned without any changes, otherwise it will be wrapped in an {@link AuditableWrapper}. - * - * @param entity the entity - * @param repositoryMetadata the repository metadata for the entity - * @return the auditable entity - */ - private static Auditable getAuditable(Object entity, RepositoryMetadata repositoryMetadata) { - if (entity instanceof Auditable) { - return (Auditable) entity; - } else { - return new AuditableWrapper(entity, repositoryMetadata); - } - } + /** + * @return the auditor aware that is being used by this listener for setting auditor related + * properties + */ + public AuditorAware getAuditorAware() { + return auditorAware; + } - /** - * @return the auditor aware that is being used by this listener for setting auditor related properties - */ - public AuditorAware getAuditorAware() { - return auditorAware; + /** + * Given an entity returns an {@link Auditable} for it. If the entity itself implements that + * interface, it will be returned without any changes, otherwise it will be wrapped in an {@link + * AuditableWrapper}. + * + * @param entity the entity + * @param repositoryMetadata the repository metadata for the entity + * @return the auditable entity + */ + private static Auditable getAuditable(Object entity, RepositoryMetadata repositoryMetadata) { + if (entity instanceof Auditable) { + return (Auditable) entity; + } else { + return new AuditableWrapper(entity, repositoryMetadata); } - + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapper.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapper.java index 85f867d1..be1c85d7 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapper.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapper.java @@ -20,11 +20,11 @@ import java.util.Optional; /** - * This class is used to wrap a normal entity in an entity that supports {@link Auditable auditing}. If the underlying - * entity does not exhibit auditable behavior (either by implementing {@link Auditable} or by having properties that are - * annotated with one of the audit annotations provided by Spring Data Commons) this class will simply ignore audit - * requests. Otherwise, it will convert the values to their appropriate types and sets and gets the appropriate - * properties. + * This class is used to wrap a normal entity in an entity that supports {@link Auditable auditing}. + * If the underlying entity does not exhibit auditable behavior (either by implementing {@link + * Auditable} or by having properties that are annotated with one of the audit annotations provided + * by Spring Data Commons) this class will simply ignore audit requests. Otherwise, it will convert + * the values to their appropriate types and sets and gets the appropriate properties. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/12/15) @@ -32,130 +32,131 @@ @SuppressWarnings("WeakerAccess") public class AuditableWrapper implements Auditable { - private final BeanWrapper wrapper; - private final RepositoryMetadata repositoryMetadata; - private final String createdBy; - private final String createdDate; - private final String lastModifiedBy; - private final String lastModifiedDate; - - private static String findProperty(Class entityType, Class annotationType) { - final PropertyVisitor visitor = new PropertyVisitor(annotationType); - ReflectionUtils.doWithFields(entityType, visitor); - ReflectionUtils.doWithMethods(entityType, visitor, new GetterMethodFilter()); - return visitor.getProperty(); + private final BeanWrapper wrapper; + private final RepositoryMetadata repositoryMetadata; + private final String createdBy; + private final String createdDate; + private final String lastModifiedBy; + private final String lastModifiedDate; + + public AuditableWrapper(Object entity, RepositoryMetadata repositoryMetadata) { + this.repositoryMetadata = repositoryMetadata; + this.wrapper = new BeanWrapperImpl(entity); + this.createdBy = findProperty(repositoryMetadata.getEntityType(), CreatedBy.class); + this.createdDate = findProperty(repositoryMetadata.getEntityType(), CreatedDate.class); + this.lastModifiedBy = findProperty(repositoryMetadata.getEntityType(), LastModifiedBy.class); + this.lastModifiedDate = + findProperty(repositoryMetadata.getEntityType(), LastModifiedDate.class); + } + + @Override + @Nonnull + public Optional getCreatedBy() { + return Optional.ofNullable(getProperty(Object.class, wrapper, createdBy)); + } + + @Override + public void setCreatedBy(@Nonnull Object createdBy) { + setProperty(wrapper, this.createdBy, createdBy); + } + + @Override + @Nonnull + public Optional getCreatedDate() { + return Optional.ofNullable(getProperty(Instant.class, wrapper, createdDate)); + } + + @Override + public void setCreatedDate(@Nonnull TemporalAccessor creationDate) { + setProperty(wrapper, createdDate, creationDate); + } + + @Override + @Nonnull + public Optional getLastModifiedBy() { + return Optional.ofNullable(getProperty(Object.class, wrapper, lastModifiedBy)); + } + + @Override + public void setLastModifiedBy(@Nonnull Object lastModifiedBy) { + setProperty(wrapper, this.lastModifiedBy, lastModifiedBy); + } + + @Override + @Nonnull + public Optional getLastModifiedDate() { + return Optional.ofNullable(getProperty(Instant.class, wrapper, lastModifiedDate)); + } + + @Override + public void setLastModifiedDate(@Nonnull TemporalAccessor lastModifiedDate) { + setProperty(wrapper, this.lastModifiedDate, lastModifiedDate); + } + + @Override + public Object getId() { + return wrapper.getPropertyValue(repositoryMetadata.getIdentifierProperty()); + } + + @Override + public boolean isNew() { + return getId() == null; + } + + private static String findProperty( + Class entityType, Class annotationType) { + final PropertyVisitor visitor = new PropertyVisitor(annotationType); + ReflectionUtils.doWithFields(entityType, visitor); + ReflectionUtils.doWithMethods(entityType, visitor, new GetterMethodFilter()); + return visitor.getProperty(); + } + + /** + * Returns the property value for a given audit property. + * + * @param type the type of the property + * @param wrapper the bean wrapper + * @param property actual property to read + * @param the object type for the value + * @return the property value + */ + private static E getProperty(Class type, BeanWrapper wrapper, String property) { + if (property == null || !wrapper.isReadableProperty(property)) { + return null; } - - /** - * Returns the property value for a given audit property. - * - * @param type the type of the property - * @param wrapper the bean wrapper - * @param property actual property to read - * @param the object type for the value - * @return the property value - */ - private static E getProperty(Class type, BeanWrapper wrapper, String property) { - if (property == null || !wrapper.isReadableProperty(property)) { - return null; - } - Object propertyValue = wrapper.getPropertyValue(property); - if (propertyValue instanceof Date) { - propertyValue = Instant.ofEpochMilli(((Date) propertyValue).getTime()); - } - return type.cast(propertyValue); + Object propertyValue = wrapper.getPropertyValue(property); + if (propertyValue instanceof Date) { + propertyValue = Instant.ofEpochMilli(((Date) propertyValue).getTime()); } - - /** - * Sets an audit property on the given entity - * - * @param wrapper the bean wrapper for the entity - * @param property the property for which the value is being set - * @param value the original value of the property - */ - private static void setProperty(BeanWrapper wrapper, String property, Object value) { - if (property != null) { - Object targetValue = value; - final PropertyDescriptor descriptor = wrapper.getPropertyDescriptor(property); - if (targetValue instanceof Instant) { - Instant instant = (Instant) targetValue; - if (Date.class.equals(descriptor.getPropertyType())) { - targetValue = new Date(instant.toEpochMilli()); - } else if (java.sql.Date.class.equals(descriptor.getPropertyType())) { - targetValue = new java.sql.Date(instant.toEpochMilli()); - } else if (java.sql.Timestamp.class.equals(descriptor.getPropertyType())) { - targetValue = new java.sql.Timestamp(instant.toEpochMilli()); - } else if (java.sql.Time.class.equals(descriptor.getPropertyType())) { - targetValue = new java.sql.Time(instant.toEpochMilli()); - } - } - if (wrapper.isWritableProperty(property)) { - wrapper.setPropertyValue(property, targetValue); - } + return type.cast(propertyValue); + } + + /** + * Sets an audit property on the given entity + * + * @param wrapper the bean wrapper for the entity + * @param property the property for which the value is being set + * @param value the original value of the property + */ + private static void setProperty(BeanWrapper wrapper, String property, Object value) { + if (property != null) { + Object targetValue = value; + final PropertyDescriptor descriptor = wrapper.getPropertyDescriptor(property); + if (targetValue instanceof Instant) { + Instant instant = (Instant) targetValue; + if (Date.class.equals(descriptor.getPropertyType())) { + targetValue = new Date(instant.toEpochMilli()); + } else if (java.sql.Date.class.equals(descriptor.getPropertyType())) { + targetValue = new java.sql.Date(instant.toEpochMilli()); + } else if (java.sql.Timestamp.class.equals(descriptor.getPropertyType())) { + targetValue = new java.sql.Timestamp(instant.toEpochMilli()); + } else if (java.sql.Time.class.equals(descriptor.getPropertyType())) { + targetValue = new java.sql.Time(instant.toEpochMilli()); } + } + if (wrapper.isWritableProperty(property)) { + wrapper.setPropertyValue(property, targetValue); + } } - - public AuditableWrapper(Object entity, RepositoryMetadata repositoryMetadata) { - this.repositoryMetadata = repositoryMetadata; - this.wrapper = new BeanWrapperImpl(entity); - this.createdBy = findProperty(repositoryMetadata.getEntityType(), CreatedBy.class); - this.createdDate = findProperty(repositoryMetadata.getEntityType(), CreatedDate.class); - this.lastModifiedBy = findProperty(repositoryMetadata.getEntityType(), LastModifiedBy.class); - this.lastModifiedDate = findProperty(repositoryMetadata.getEntityType(), LastModifiedDate.class); - } - - @Override - @Nonnull - public Optional getCreatedBy() { - return Optional.ofNullable(getProperty(Object.class, wrapper, createdBy)); - } - - @Override - public void setCreatedBy(@Nonnull Object createdBy) { - setProperty(wrapper, this.createdBy, createdBy); - } - - @Override - @Nonnull - public Optional getCreatedDate() { - return Optional.ofNullable(getProperty(Instant.class, wrapper, createdDate)); - } - - @Override - public void setCreatedDate(@Nonnull TemporalAccessor creationDate) { - setProperty(wrapper, createdDate, creationDate); - } - - @Override - @Nonnull - public Optional getLastModifiedBy() { - return Optional.ofNullable(getProperty(Object.class, wrapper, lastModifiedBy)); - } - - @Override - public void setLastModifiedBy(@Nonnull Object lastModifiedBy) { - setProperty(wrapper, this.lastModifiedBy, lastModifiedBy); - } - - @Override - @Nonnull - public Optional getLastModifiedDate() { - return Optional.ofNullable(getProperty(Instant.class, wrapper, lastModifiedDate)); - } - - @Override - public void setLastModifiedDate(@Nonnull TemporalAccessor lastModifiedDate) { - setProperty(wrapper, this.lastModifiedDate, lastModifiedDate); - } - - @Override - public Object getId() { - return wrapper.getPropertyValue(repositoryMetadata.getIdentifierProperty()); - } - - @Override - public boolean isNew() { - return getId() == null; - } - + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeDeleteDataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeDeleteDataStoreEvent.java index 44eb9f4e..a36423bf 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeDeleteDataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeDeleteDataStoreEvent.java @@ -12,8 +12,8 @@ @SuppressWarnings("WeakerAccess") public class BeforeDeleteDataStoreEvent extends AbstractEntityDataStoreEvent { - public BeforeDeleteDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { - super(repositoryMetadata, dataStore, entity); - } - + public BeforeDeleteDataStoreEvent( + RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { + super(repositoryMetadata, dataStore, entity); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeInsertDataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeInsertDataStoreEvent.java index 5429d574..e66a90ed 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeInsertDataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeInsertDataStoreEvent.java @@ -12,8 +12,8 @@ @SuppressWarnings("WeakerAccess") public class BeforeInsertDataStoreEvent extends AbstractEntityDataStoreEvent { - public BeforeInsertDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { - super(repositoryMetadata, dataStore, entity); - } - + public BeforeInsertDataStoreEvent( + RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { + super(repositoryMetadata, dataStore, entity); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeUpdateDataStoreEvent.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeUpdateDataStoreEvent.java index c835f562..fb53ac8d 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeUpdateDataStoreEvent.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/BeforeUpdateDataStoreEvent.java @@ -12,8 +12,8 @@ @SuppressWarnings("WeakerAccess") public class BeforeUpdateDataStoreEvent extends AbstractEntityDataStoreEvent { - public BeforeUpdateDataStoreEvent(RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { - super(repositoryMetadata, dataStore, entity); - } - + public BeforeUpdateDataStoreEvent( + RepositoryMetadata repositoryMetadata, DataStore dataStore, Object entity) { + super(repositoryMetadata, dataStore, entity); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContext.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContext.java index ec1d3aa3..9df6be5e 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContext.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContext.java @@ -14,77 +14,81 @@ import java.util.concurrent.CopyOnWriteArrayList; /** - *

This is the default implementation for the {@link DataStoreEventListenerContext} interface. - * This implementation comes with support for parent context lookup, meaning that you can register event listeners with - * another context, set that as the parent for this context, and have appropriate events triggered in that context as - * well.

+ * This is the default implementation for the {@link DataStoreEventListenerContext} interface. This + * implementation comes with support for parent context lookup, meaning that you can register event + * listeners with another context, set that as the parent for this context, and have appropriate + * events triggered in that context as well. * - *

It should be noted that listeners registered in the current context always take precedence over the - * listeners found on a possible parent context.

+ *

It should be noted that listeners registered in the current context always take precedence + * over the listeners found on a possible parent context. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/12/15) */ public class DefaultDataStoreEventListenerContext implements DataStoreEventListenerContext { - private static final Log log = LogFactory.getLog(DefaultDataStoreEventListenerContext.class); - private final ConcurrentMap, List>> listeners; - private final DataStoreEventListenerContext parent; + private static final Log log = LogFactory.getLog(DefaultDataStoreEventListenerContext.class); + private final ConcurrentMap, List>> + listeners; + private final DataStoreEventListenerContext parent; - public DefaultDataStoreEventListenerContext() { - this(null); - } + public DefaultDataStoreEventListenerContext() { + this(null); + } - public DefaultDataStoreEventListenerContext(DataStoreEventListenerContext parent) { - this.parent = parent; - listeners = new ConcurrentHashMap<>(); - } + public DefaultDataStoreEventListenerContext(DataStoreEventListenerContext parent) { + this.parent = parent; + listeners = new ConcurrentHashMap<>(); + } - @Override - public void register(DataStoreEventListener listener) { - final SmartDataStoreEventListener eventListener = new SmartDataStoreEventListener<>(listener); - listeners.putIfAbsent(eventListener.getEventType(), new CopyOnWriteArrayList<>()); - log.info("Registering an event listener for type " + eventListener.getEventType()); - listeners.get(eventListener.getEventType()).add(eventListener); - } + @Override + public void register(DataStoreEventListener listener) { + final SmartDataStoreEventListener eventListener = + new SmartDataStoreEventListener<>(listener); + listeners.putIfAbsent(eventListener.getEventType(), new CopyOnWriteArrayList<>()); + log.info("Registering an event listener for type " + eventListener.getEventType()); + listeners.get(eventListener.getEventType()).add(eventListener); + } - @Override - public void trigger(DataStoreEvent event) { - if (event == null) { - log.error("The data store event that was triggered was a null value"); - throw new InvalidArgumentException("Cannot raise a null event"); - } - log.info("Triggering data store event of type " + event.getClass()); - for (Class eventType : listeners.keySet()) { - if (eventType.isInstance(event)) { - for (DataStoreEventListener listener : listeners.get(eventType)) { - log.debug("Triggering event on listener " + ((SmartDataStoreEventListener) listener).getDelegate()); - //noinspection unchecked - listener.onEvent(event); - } - } - } - if (parent != null) { - log.info("Going to trigger the same event on the parent context"); - parent.trigger(event); + @Override + public void trigger(DataStoreEvent event) { + if (event == null) { + log.error("The data store event that was triggered was a null value"); + throw new InvalidArgumentException("Cannot raise a null event"); + } + log.info("Triggering data store event of type " + event.getClass()); + for (Class eventType : listeners.keySet()) { + if (eventType.isInstance(event)) { + for (DataStoreEventListener listener : listeners.get(eventType)) { + log.debug( + "Triggering event on listener " + + ((SmartDataStoreEventListener) listener).getDelegate()); + //noinspection unchecked + listener.onEvent(event); } + } + } + if (parent != null) { + log.info("Going to trigger the same event on the parent context"); + parent.trigger(event); } + } - @Override - public List> getListeners(Class eventType) { - final List> found = new LinkedList<>(); - for (Class supportedType : listeners.keySet()) { - if (supportedType.isAssignableFrom(eventType)) { - for (DataStoreEventListener listener : listeners.get(supportedType)) { - //noinspection unchecked - found.add(((SmartDataStoreEventListener) listener).getDelegate()); - } - } - } - if (parent != null) { - found.addAll(parent.getListeners(eventType)); + @Override + public List> getListeners( + Class eventType) { + final List> found = new LinkedList<>(); + for (Class supportedType : listeners.keySet()) { + if (supportedType.isAssignableFrom(eventType)) { + for (DataStoreEventListener listener : listeners.get(supportedType)) { + //noinspection unchecked + found.add(((SmartDataStoreEventListener) listener).getDelegate()); } - return found; + } } - + if (parent != null) { + found.addAll(parent.getListeners(eventType)); + } + return found; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistry.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistry.java index 909f19ea..ba5b836a 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistry.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistry.java @@ -10,37 +10,36 @@ import java.util.concurrent.ConcurrentHashMap; /** - * This is the default implementation of the data store registry that supports caching a data store based on the type of - * entity the data store supports. + * This is the default implementation of the data store registry that supports caching a data store + * based on the type of entity the data store supports. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/29/15) */ public class DefaultDataStoreRegistry implements DataStoreRegistry { - private static final Log log = LogFactory.getLog(DefaultDataStoreRegistry.class); - private final Map, DataStore> dataStores = new ConcurrentHashMap<>(); - - @Override - public void register(DataStore dataStore) { - log.info("Registering a data store for type " + dataStore.getEntityType()); - dataStores.put(dataStore.getEntityType(), dataStore); - } - - @Override - public DataStore getDataStore(Class entityType) { - if (!dataStores.containsKey(entityType)) { - log.error("There is no data store registered for entity type " + entityType); - log.debug("Registered data types are " + dataStores.keySet()); - throw new DataStoreNotFoundException(entityType); - } - //noinspection unchecked - return (DataStore) dataStores.get(entityType); + private static final Log log = LogFactory.getLog(DefaultDataStoreRegistry.class); + private final Map, DataStore> dataStores = new ConcurrentHashMap<>(); + + @Override + public void register(DataStore dataStore) { + log.info("Registering a data store for type " + dataStore.getEntityType()); + dataStores.put(dataStore.getEntityType(), dataStore); + } + + @Override + public DataStore getDataStore(Class entityType) { + if (!dataStores.containsKey(entityType)) { + log.error("There is no data store registered for entity type " + entityType); + log.debug("Registered data types are " + dataStores.keySet()); + throw new DataStoreNotFoundException(entityType); } - - @Override - public boolean has(Class entityType) { - return dataStores.containsKey(entityType); - } - + //noinspection unchecked + return (DataStore) dataStores.get(entityType); + } + + @Override + public boolean has(Class entityType) { + return dataStores.containsKey(entityType); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStore.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStore.java index 1bb579f8..25318126 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStore.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStore.java @@ -12,104 +12,107 @@ import java.util.Collection; /** - * This implementation relies on a delegate data store to handling the actual storage/retrieval. It decorates the - * delegate with event triggering capabilities and some additional data integrity checks (null checking). + * This implementation relies on a delegate data store to handling the actual storage/retrieval. It + * decorates the delegate with event triggering capabilities and some additional data integrity + * checks (null checking). * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/6/15) */ public class EventPublishingDataStore implements DataStore, DataStoreEventPublisher { - private static final Log log = LogFactory.getLog(EventPublishingDataStore.class); - private final DataStore delegate; - private final RepositoryMetadata repositoryMetadata; - private final DataStoreEventListenerContext listenerContext; + private static final Log log = LogFactory.getLog(EventPublishingDataStore.class); + private final DataStore delegate; + private final RepositoryMetadata repositoryMetadata; + private final DataStoreEventListenerContext listenerContext; - public EventPublishingDataStore(DataStore delegate, RepositoryMetadata repositoryMetadata, - DataStoreEventListenerContext listenerContext) { - this.delegate = delegate; - this.repositoryMetadata = repositoryMetadata; - this.listenerContext = listenerContext; - } + public EventPublishingDataStore( + DataStore delegate, + RepositoryMetadata repositoryMetadata, + DataStoreEventListenerContext listenerContext) { + this.delegate = delegate; + this.repositoryMetadata = repositoryMetadata; + this.listenerContext = listenerContext; + } - @Override - public boolean hasKey(K key) { - return delegate.hasKey(key); - } + @Override + public boolean hasKey(K key) { + return delegate.hasKey(key); + } - @Override - public boolean save(K key, E entity) { - if (key == null) { - log.error("Cannot save an entity under a null key"); - throw new CorruptDataException(getEntityType(), null, "Cannot save an entity with a null key"); - } - if (entity == null) { - log.error("Cannot save a null value into the data store"); - throw new CorruptDataException(getEntityType(), null, "Cannot save null into the data store"); - } - final boolean entityIsNew = !delegate.hasKey(key); - if (entityIsNew) { - log.info("About to insert a new entity in the data store under key " + key); - publishEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, this, entity)); - } else { - log.info("About to update the entity in the data store under key " + key); - publishEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, this, entity)); - } - delegate.save(key, entity); - if (entityIsNew) { - log.info("Finished inserting the entity in the data store under key " + key); - publishEvent(new AfterInsertDataStoreEvent(repositoryMetadata, this, entity)); - return true; - } else { - log.info("Finished updating the entity under key " + key); - publishEvent(new AfterUpdateDataStoreEvent(repositoryMetadata, this, entity)); - return false; - } + @Override + public boolean save(K key, E entity) { + if (key == null) { + log.error("Cannot save an entity under a null key"); + throw new CorruptDataException( + getEntityType(), null, "Cannot save an entity with a null key"); } - - @Override - public boolean delete(K key) { - if (!delegate.hasKey(key)) { - log.info("Attempted to delete entity with key " + key + " but found nothing"); - return false; - } - final E entity = delegate.retrieve(key); - log.info("About to delete an entity with key " + key); - publishEvent(new BeforeDeleteDataStoreEvent(repositoryMetadata, this, entity)); - delegate.delete(key); - log.info("Finished deleting the entity with key " + key); - publishEvent(new AfterDeleteDataStoreEvent(repositoryMetadata, this, entity)); - return true; + if (entity == null) { + log.error("Cannot save a null value into the data store"); + throw new CorruptDataException(getEntityType(), null, "Cannot save null into the data store"); } - - @Override - public E retrieve(K key) { - return delegate.retrieve(key); + final boolean entityIsNew = !delegate.hasKey(key); + if (entityIsNew) { + log.info("About to insert a new entity in the data store under key " + key); + publishEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, this, entity)); + } else { + log.info("About to update the entity in the data store under key " + key); + publishEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, this, entity)); } - - @Override - public Collection keys() { - return delegate.keys(); + delegate.save(key, entity); + if (entityIsNew) { + log.info("Finished inserting the entity in the data store under key " + key); + publishEvent(new AfterInsertDataStoreEvent(repositoryMetadata, this, entity)); + return true; + } else { + log.info("Finished updating the entity under key " + key); + publishEvent(new AfterUpdateDataStoreEvent(repositoryMetadata, this, entity)); + return false; } + } - @Override - public Collection retrieveAll() { - return delegate.retrieveAll(); + @Override + public boolean delete(K key) { + if (!delegate.hasKey(key)) { + log.info("Attempted to delete entity with key " + key + " but found nothing"); + return false; } + final E entity = delegate.retrieve(key); + log.info("About to delete an entity with key " + key); + publishEvent(new BeforeDeleteDataStoreEvent(repositoryMetadata, this, entity)); + delegate.delete(key); + log.info("Finished deleting the entity with key " + key); + publishEvent(new AfterDeleteDataStoreEvent(repositoryMetadata, this, entity)); + return true; + } - @Override - public Class getEntityType() { - return delegate.getEntityType(); - } + @Override + public E retrieve(K key) { + return delegate.retrieve(key); + } - @Override - public void truncate() { - delegate.truncate(); - } + @Override + public Collection keys() { + return delegate.keys(); + } - @Override - public void publishEvent(DataStoreEvent event) { - listenerContext.trigger(event); - } + @Override + public Collection retrieveAll() { + return delegate.retrieveAll(); + } + + @Override + public Class getEntityType() { + return delegate.getEntityType(); + } + + @Override + public void truncate() { + delegate.truncate(); + } + @Override + public void publishEvent(DataStoreEvent event) { + listenerContext.trigger(event); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStore.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStore.java index bcc2f8c4..64e0dc11 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStore.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStore.java @@ -11,93 +11,92 @@ import java.util.concurrent.ConcurrentMap; /** - * This is the default, most basic implementation provided for a data store that stores entities in an in-memory {@link - * java.util.Map map} by mapping entity keys to entities. + * This is the default, most basic implementation provided for a data store that stores entities in + * an in-memory {@link java.util.Map map} by mapping entity keys to entities. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/17/15) */ public class MemoryDataStore implements DataStore { - private static final Log log = LogFactory.getLog(MemoryDataStore.class); - private final ConcurrentMap store = new ConcurrentHashMap<>(); - private final Class entityType; + private static final Log log = LogFactory.getLog(MemoryDataStore.class); + private final ConcurrentMap store = new ConcurrentHashMap<>(); + private final Class entityType; - public MemoryDataStore(Class entityType) { - this.entityType = entityType; - } + public MemoryDataStore(Class entityType) { + this.entityType = entityType; + } - @Override - public boolean hasKey(K key) { - log.info("Looking for an object with key " + key); - return store.containsKey(key); - } + @Override + public boolean hasKey(K key) { + log.info("Looking for an object with key " + key); + return store.containsKey(key); + } - @Override - public boolean save(K key, E entity) { - if (key == null) { - log.error("Asked to save an entity with a null key"); - throw new DataStoreException(entityType, "Cannot save an entity with a null key"); - } else if (entity == null) { - log.error("Asked to save a null value into the data store"); - throw new DataStoreException(entityType, "Cannot save a null entity"); - } - log.info("Attempting to save entity with key " + key); - boolean saved = store.put(key, entity) == null; - log.debug("Entity was " + (!saved ? "not " : "") + "saved under key " + key); - return saved; + @Override + public boolean save(K key, E entity) { + if (key == null) { + log.error("Asked to save an entity with a null key"); + throw new DataStoreException(entityType, "Cannot save an entity with a null key"); + } else if (entity == null) { + log.error("Asked to save a null value into the data store"); + throw new DataStoreException(entityType, "Cannot save a null entity"); } + log.info("Attempting to save entity with key " + key); + boolean saved = store.put(key, entity) == null; + log.debug("Entity was " + (!saved ? "not " : "") + "saved under key " + key); + return saved; + } - @Override - public boolean delete(K key) { - if (key == null) { - log.error("Asked to delete an entity with a null key for reference"); - throw new DataStoreException(entityType, "Cannot delete an entity with a null key"); - } - if (store.containsKey(key)) { - log.info("Deleting entity under key " + key); - store.remove(key); - return true; - } else { - log.info("No entity was found to delete under key " + key); - } - return false; + @Override + public boolean delete(K key) { + if (key == null) { + log.error("Asked to delete an entity with a null key for reference"); + throw new DataStoreException(entityType, "Cannot delete an entity with a null key"); } - - @Override - public E retrieve(K key) { - if (key == null) { - log.error("Asked to retrieve an entity from a null key"); - throw new DataStoreException(entityType, "Cannot retrieve an entity with a null key"); - } - if (store.containsKey(key)) { - log.info("Retrieving entity from key " + key); - return store.get(key); - } else { - log.info("No entity was found to return under key " + key); - } - return null; + if (store.containsKey(key)) { + log.info("Deleting entity under key " + key); + store.remove(key); + return true; + } else { + log.info("No entity was found to delete under key " + key); } + return false; + } - @Override - public Collection keys() { - return new LinkedList<>(store.keySet()); + @Override + public E retrieve(K key) { + if (key == null) { + log.error("Asked to retrieve an entity from a null key"); + throw new DataStoreException(entityType, "Cannot retrieve an entity with a null key"); } - - @Override - public synchronized Collection retrieveAll() { - log.info("Retrieving all entities from the data store"); - return new LinkedList<>(store.values()); + if (store.containsKey(key)) { + log.info("Retrieving entity from key " + key); + return store.get(key); + } else { + log.info("No entity was found to return under key " + key); } + return null; + } - @Override - public Class getEntityType() { - return entityType; - } + @Override + public Collection keys() { + return new LinkedList<>(store.keySet()); + } - @Override - public void truncate() { - store.clear(); - } + @Override + public synchronized Collection retrieveAll() { + log.info("Retrieving all entities from the data store"); + return new LinkedList<>(store.values()); + } + + @Override + public Class getEntityType() { + return entityType; + } + @Override + public void truncate() { + store.clear(); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitor.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitor.java index 60ea92ae..77b76aea 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitor.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitor.java @@ -10,43 +10,43 @@ import java.lang.reflect.Method; /** - * This property visitor will visit all properties (fields and getter methods) to find out the property that has the - * specified annotation. The property can later be retrieved by calling {@link #getProperty()}. + * This property visitor will visit all properties (fields and getter methods) to find out the + * property that has the specified annotation. The property can later be retrieved by calling {@link + * #getProperty()}. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/12/15) */ class PropertyVisitor implements ReflectionUtils.MethodCallback, ReflectionUtils.FieldCallback { - private final Class annotationType; - private String property; + private final Class annotationType; + private String property; - PropertyVisitor(Class annotationType) { - this.annotationType = annotationType; - } + PropertyVisitor(Class annotationType) { + this.annotationType = annotationType; + } - @Override - public void doWith(@Nonnull Method method) throws IllegalArgumentException { - if (property != null) { - return; - } - if (AnnotationUtils.findAnnotation(method, annotationType) != null) { - property = PropertyUtils.getPropertyName(method); - } + @Override + public void doWith(@Nonnull Method method) throws IllegalArgumentException { + if (property != null) { + return; } - - @Override - public void doWith(@Nonnull Field field) throws IllegalArgumentException { - if (property != null) { - return; - } - if (field.isAnnotationPresent(annotationType)) { - property = field.getName(); - } + if (AnnotationUtils.findAnnotation(method, annotationType) != null) { + property = PropertyUtils.getPropertyName(method); } + } - public String getProperty() { - return property; + @Override + public void doWith(@Nonnull Field field) throws IllegalArgumentException { + if (property != null) { + return; + } + if (field.isAnnotationPresent(annotationType)) { + property = field.getName(); } + } + public String getProperty() { + return property; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListener.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListener.java index b1a57a6d..502e94ad 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListener.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListener.java @@ -5,37 +5,39 @@ import org.springframework.core.GenericTypeResolver; /** - * This implementation of the data store event listener wraps a given delegate listener and reads the supported event - * type from the generic type arguments on the original listener. This lets us interact with the listener without having - * to read its generic type arguments every time. + * This implementation of the data store event listener wraps a given delegate listener and reads + * the supported event type from the generic type arguments on the original listener. This lets us + * interact with the listener without having to read its generic type arguments every time. * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (10/6/15) */ @SuppressWarnings("WeakerAccess") -public class SmartDataStoreEventListener implements DataStoreEventListener { - - private final DataStoreEventListener delegate; - private final Class eventType; - - public SmartDataStoreEventListener(DataStoreEventListener delegate) { - this.delegate = delegate; - //noinspection unchecked - eventType = (Class) GenericTypeResolver.resolveTypeArgument(delegate.getClass(), - DataStoreEventListener.class); - } - - @Override - public void onEvent(E event) { - delegate.onEvent(event); - } - - public Class getEventType() { - return eventType; - } - - public DataStoreEventListener getDelegate() { - return delegate; - } - +public class SmartDataStoreEventListener + implements DataStoreEventListener { + + private final DataStoreEventListener delegate; + private final Class eventType; + + public SmartDataStoreEventListener(DataStoreEventListener delegate) { + this.delegate = delegate; + //noinspection unchecked + eventType = + (Class) + GenericTypeResolver.resolveTypeArgument( + delegate.getClass(), DataStoreEventListener.class); + } + + @Override + public void onEvent(E event) { + delegate.onEvent(event); + } + + public Class getEventType() { + return eventType; + } + + public DataStoreEventListener getDelegate() { + return delegate; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/string/DocumentReader.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/string/DocumentReader.java index f929fed0..45ac0adb 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/string/DocumentReader.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/string/DocumentReader.java @@ -9,87 +9,93 @@ @SuppressWarnings("unused") public interface DocumentReader { - /** - * This will return the parts of document not yet read through by the reader - * - * @return the part of the document not processed by the reader - */ - String rest(); + /** + * This will return the parts of document not yet read through by the reader + * + * @return the part of the document not processed by the reader + */ + String rest(); - /** - * This method will determine whether the indicated pattern can be found at this point in the document or not - * - * @param pattern the lookup pattern - * @return true if the pattern can be found - */ - boolean has(Pattern pattern); + /** + * This method will determine whether the indicated pattern can be found at this point in the + * document or not + * + * @param pattern the lookup pattern + * @return true if the pattern can be found + */ + boolean has(Pattern pattern); - /** - * This method will determine whether the indicated pattern can be found at this point in the document or not - * - * @param pattern the lookup pattern - * @return true if the pattern can be found - */ - boolean has(String pattern); + /** + * This method will determine whether the indicated pattern can be found at this point in the + * document or not + * + * @param pattern the lookup pattern + * @return true if the pattern can be found + */ + boolean has(String pattern); - /** - * Determines whether we have hit the end of the document or not - * - * @return true if we have no more to go - */ - boolean hasMore(); + /** + * Determines whether we have hit the end of the document or not + * + * @return true if we have no more to go + */ + boolean hasMore(); - /** - * Will attempt to read the string matching the given parameter. If the string matched with this pattern does not - * start at the current point in the document, the result will be considered to be negative. - * - * @param pattern the compiled pattern to be matched against - * @return the string read by the method, or null if it cannot be found - * @see Pattern#compile(String) - * @see Pattern#compile(String, int) - */ - String read(Pattern pattern); + /** + * Will attempt to read the string matching the given parameter. If the string matched with this + * pattern does not start at the current point in the document, the result will be considered to + * be negative. + * + * @param pattern the compiled pattern to be matched against + * @return the string read by the method, or null if it cannot be found + * @see Pattern#compile(String) + * @see Pattern#compile(String, int) + */ + String read(Pattern pattern); - /** - * Will attempt to read the string matching the given parameter. If the string matched with this pattern does not - * start at the current point in the document, the result will be considered to be negative. - * - * @param pattern the compiled pattern to be matched against - * @return the string read by the method, or null if it cannot be found - * @see Pattern#compile(String) - * @see Pattern#compile(String, int) - */ - String read(String pattern); + /** + * Will attempt to read the string matching the given parameter. If the string matched with this + * pattern does not start at the current point in the document, the result will be considered to + * be negative. + * + * @param pattern the compiled pattern to be matched against + * @return the string read by the method, or null if it cannot be found + * @see Pattern#compile(String) + * @see Pattern#compile(String, int) + */ + String read(String pattern); - /** - * This will attempt to read string matching the given pattern from the document at the current point indicated by - * the cursor. If failed to do so, the method will be expected to throw an exception or take corrective measures. - * - * @param pattern the regular to query for - * @return the read string - */ - String expect(Pattern pattern); + /** + * This will attempt to read string matching the given pattern from the document at the current + * point indicated by the cursor. If failed to do so, the method will be expected to throw an + * exception or take corrective measures. + * + * @param pattern the regular to query for + * @return the read string + */ + String expect(Pattern pattern); - /** - * This will attempt to read string matching the given pattern from the document at the current point indicated by - * the cursor. If failed to do so, the method will be expected to throw an exception or take corrective measures. - * - * @param pattern the regular to query for - * @return the read string - */ - String expect(String pattern); + /** + * This will attempt to read string matching the given pattern from the document at the current + * point indicated by the cursor. If failed to do so, the method will be expected to throw an + * exception or take corrective measures. + * + * @param pattern the regular to query for + * @return the read string + */ + String expect(String pattern); - /** - * This will cause the state of the reading to be reset. The cursor will be set back to the beginning of the - * document, and the line/column positioning data will be reset to their initial value. - */ - void reset(); - - /** - * Moves back the specified number of characters - * - * @param count character count to backtrack by - */ - void backtrack(int count); + /** + * This will cause the state of the reading to be reset. The cursor will be set back to the + * beginning of the document, and the line/column positioning data will be reset to their initial + * value. + */ + void reset(); + /** + * Moves back the specified number of characters + * + * @param count character count to backtrack by + */ + void backtrack(int count); } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/string/impl/DefaultDocumentReader.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/string/impl/DefaultDocumentReader.java index a30556eb..92efcbff 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/string/impl/DefaultDocumentReader.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/string/impl/DefaultDocumentReader.java @@ -13,137 +13,145 @@ @SuppressWarnings("unused") public class DefaultDocumentReader implements DocumentReader { - private final String document; - private int cursor; - - /** - * Instantiates the reader while taking in the document to be read through - * - * @param document the document - */ - public DefaultDocumentReader(String document) { - this.document = document; - reset(); - } - - /** - * This will return the parts of document not yet read through by the reader - * - * @return the part of the document not processed by the reader - */ - @Override - public String rest() { - return document.substring(cursor); - } - - /** - * This method will determine whether the indicated pattern can be found at this point in the document or not - * - * @param pattern the lookup pattern - * @return true if the pattern can be found - */ - @Override - public boolean has(Pattern pattern) { - final Matcher matcher = pattern.matcher(rest()); - return matcher.find() && matcher.start() == 0; - } - - /** - * This method will determine whether the indicated pattern can be found at this point in the document or not - * - * @param pattern the lookup pattern - * @return true if the pattern can be found - */ - @Override - public boolean has(String pattern) { - if (!pattern.startsWith("^")) { - pattern = "^" + pattern; - } - return has(Pattern.compile(pattern, Pattern.DOTALL | Pattern.MULTILINE)); - } - - /** - * Determines whether we have hit the end of the document or not - * - * @return true if we have no more to go - */ - @Override - public boolean hasMore() { - return !rest().isEmpty(); - } - - /** - * Will attempt to read the string matching the given parameter. If the string matched with this pattern does not - * start at the current point in the document, the result will be considered to be negative. - * - * @param pattern the compiled pattern to be matched against - * @return the string read by the method, or null if it cannot be found - * @see Pattern#compile(String) - * @see Pattern#compile(String, int) - */ - @Override - public String read(Pattern pattern) { - final Matcher matcher = pattern.matcher(rest()); - if (matcher.find() && matcher.start() == 0) { - cursor += matcher.group().length(); - return matcher.group(); - } - return null; - } - - /** - * Will attempt to read the string matching the given parameter. If the string matched with this pattern does not - * start at the current point in the document, the result will be considered to be negative. - * - * @param pattern the compiled pattern to be matched against - * @return the string read by the method, or null if it cannot be found - * @see Pattern#compile(String) - * @see Pattern#compile(String, int) - */ - @Override - public String read(String pattern) { - return read(Pattern.compile(pattern, Pattern.DOTALL | Pattern.MULTILINE)); - } - - /** - * This will attempt to read string matching the given pattern from the document at the current point indicated by - * the cursor. If failed to do so, the method will be expected to throw an exception or take corrective measures. - * - * @param pattern the regular to query for - * @return the read string - */ - @Override - public String expect(Pattern pattern) { - final String token = read(pattern); - if (token == null) { - throw new ParserException( - "Expected pattern '" + pattern.pattern() + "' was not encountered in document: " + document); - } - return token; + private final String document; + private int cursor; + + /** + * Instantiates the reader while taking in the document to be read through + * + * @param document the document + */ + public DefaultDocumentReader(String document) { + this.document = document; + reset(); + } + + /** + * This will return the parts of document not yet read through by the reader + * + * @return the part of the document not processed by the reader + */ + @Override + public String rest() { + return document.substring(cursor); + } + + /** + * This method will determine whether the indicated pattern can be found at this point in the + * document or not + * + * @param pattern the lookup pattern + * @return true if the pattern can be found + */ + @Override + public boolean has(Pattern pattern) { + final Matcher matcher = pattern.matcher(rest()); + return matcher.find() && matcher.start() == 0; + } + + /** + * This method will determine whether the indicated pattern can be found at this point in the + * document or not + * + * @param pattern the lookup pattern + * @return true if the pattern can be found + */ + @Override + public boolean has(String pattern) { + if (!pattern.startsWith("^")) { + pattern = "^" + pattern; } - - @Override - public String expect(String pattern) { - return expect(Pattern.compile(pattern, Pattern.DOTALL | Pattern.MULTILINE)); + return has(Pattern.compile(pattern, Pattern.DOTALL | Pattern.MULTILINE)); + } + + /** + * Determines whether we have hit the end of the document or not + * + * @return true if we have no more to go + */ + @Override + public boolean hasMore() { + return !rest().isEmpty(); + } + + /** + * Will attempt to read the string matching the given parameter. If the string matched with this + * pattern does not start at the current point in the document, the result will be considered to + * be negative. + * + * @param pattern the compiled pattern to be matched against + * @return the string read by the method, or null if it cannot be found + * @see Pattern#compile(String) + * @see Pattern#compile(String, int) + */ + @Override + public String read(Pattern pattern) { + final Matcher matcher = pattern.matcher(rest()); + if (matcher.find() && matcher.start() == 0) { + cursor += matcher.group().length(); + return matcher.group(); } - - /** - * This will cause the state of the reading to be reset. The cursor will be set back to the beginning of the - * document, and the line/column positioning data will be reset to their initial value. - */ - @Override - public void reset() { - cursor = 0; + return null; + } + + /** + * Will attempt to read the string matching the given parameter. If the string matched with this + * pattern does not start at the current point in the document, the result will be considered to + * be negative. + * + * @param pattern the compiled pattern to be matched against + * @return the string read by the method, or null if it cannot be found + * @see Pattern#compile(String) + * @see Pattern#compile(String, int) + */ + @Override + public String read(String pattern) { + return read(Pattern.compile(pattern, Pattern.DOTALL | Pattern.MULTILINE)); + } + + /** + * This will attempt to read string matching the given pattern from the document at the current + * point indicated by the cursor. If failed to do so, the method will be expected to throw an + * exception or take corrective measures. + * + * @param pattern the regular to query for + * @return the read string + */ + @Override + public String expect(Pattern pattern) { + final String token = read(pattern); + if (token == null) { + throw new ParserException( + "Expected pattern '" + + pattern.pattern() + + "' was not encountered in document: " + + document); } - - /** - * Moves back the specified number of characters - * - * @param count character count to backtrack by - */ - @Override - public void backtrack(int count) { - cursor -= count; - } - + return token; + } + + @Override + public String expect(String pattern) { + return expect(Pattern.compile(pattern, Pattern.DOTALL | Pattern.MULTILINE)); + } + + /** + * This will cause the state of the reading to be reset. The cursor will be set back to the + * beginning of the document, and the line/column positioning data will be reset to their initial + * value. + */ + @Override + public void reset() { + cursor = 0; + } + + /** + * Moves back the specified number of characters + * + * @param count character count to backtrack by + */ + @Override + public void backtrack(int count) { + cursor -= count; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtils.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtils.java index 6c6b3309..39d8fce1 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtils.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtils.java @@ -1,7 +1,24 @@ package com.mmnaseri.utils.spring.data.tools; -import java.util.*; -import java.util.concurrent.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.Set; +import java.util.Stack; +import java.util.TreeSet; +import java.util.Vector; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.PriorityBlockingQueue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -9,57 +26,56 @@ */ public final class CollectionInstanceUtils { - private CollectionInstanceUtils() { - throw new UnsupportedOperationException(); - } + private CollectionInstanceUtils() { + throw new UnsupportedOperationException(); + } - /** - * Given any of the known collection types, this method will return an instance of the collection. - * - * @param collectionType the type of the collection - * @return the collection instance - */ - public static Collection getCollection(Class collectionType) { - if (HashSet.class.equals(collectionType)) { - return new HashSet<>(); - } else if (TreeSet.class.equals(collectionType)) { - return new TreeSet<>(); - } else if (CopyOnWriteArraySet.class.equals(collectionType)) { - return new CopyOnWriteArraySet<>(); - } else if (LinkedHashSet.class.equals(collectionType)) { - return new LinkedHashSet<>(); - } else if (ArrayList.class.equals(collectionType)) { - return new ArrayList<>(); - } else if (LinkedList.class.equals(collectionType)) { - return new LinkedList<>(); - } else if (Vector.class.equals(collectionType)) { - return new Vector<>(); - } else if (Stack.class.equals(collectionType)) { - return new Stack<>(); - } else if (PriorityQueue.class.equals(collectionType)) { - return new PriorityQueue<>(); - } else if (PriorityBlockingQueue.class.equals(collectionType)) { - return new PriorityBlockingQueue<>(); - } else if (ArrayDeque.class.equals(collectionType)) { - return new ArrayDeque<>(); - } else if (ConcurrentLinkedQueue.class.equals(collectionType)) { - return new ConcurrentLinkedQueue<>(); - } else if (LinkedBlockingQueue.class.equals(collectionType)) { - return new LinkedBlockingQueue<>(); - } else if (LinkedBlockingDeque.class.equals(collectionType)) { - return new LinkedBlockingDeque<>(); - } else if (List.class.equals(collectionType)) { - return new LinkedList<>(); - } else if (Set.class.equals(collectionType)) { - return new HashSet<>(); - } else if (Queue.class.equals(collectionType)) { - return new PriorityQueue<>(); - } else if (Deque.class.equals(collectionType)) { - return new ArrayDeque<>(); - } else if (Collection.class.equals(collectionType)) { - return new LinkedList<>(); - } - throw new IllegalArgumentException("Unsupported collection type: " + collectionType); + /** + * Given any of the known collection types, this method will return an instance of the collection. + * + * @param collectionType the type of the collection + * @return the collection instance + */ + public static Collection getCollection(Class collectionType) { + if (HashSet.class.equals(collectionType)) { + return new HashSet<>(); + } else if (TreeSet.class.equals(collectionType)) { + return new TreeSet<>(); + } else if (CopyOnWriteArraySet.class.equals(collectionType)) { + return new CopyOnWriteArraySet<>(); + } else if (LinkedHashSet.class.equals(collectionType)) { + return new LinkedHashSet<>(); + } else if (ArrayList.class.equals(collectionType)) { + return new ArrayList<>(); + } else if (LinkedList.class.equals(collectionType)) { + return new LinkedList<>(); + } else if (Vector.class.equals(collectionType)) { + return new Vector<>(); + } else if (Stack.class.equals(collectionType)) { + return new Stack<>(); + } else if (PriorityQueue.class.equals(collectionType)) { + return new PriorityQueue<>(); + } else if (PriorityBlockingQueue.class.equals(collectionType)) { + return new PriorityBlockingQueue<>(); + } else if (ArrayDeque.class.equals(collectionType)) { + return new ArrayDeque<>(); + } else if (ConcurrentLinkedQueue.class.equals(collectionType)) { + return new ConcurrentLinkedQueue<>(); + } else if (LinkedBlockingQueue.class.equals(collectionType)) { + return new LinkedBlockingQueue<>(); + } else if (LinkedBlockingDeque.class.equals(collectionType)) { + return new LinkedBlockingDeque<>(); + } else if (List.class.equals(collectionType)) { + return new LinkedList<>(); + } else if (Set.class.equals(collectionType)) { + return new HashSet<>(); + } else if (Queue.class.equals(collectionType)) { + return new PriorityQueue<>(); + } else if (Deque.class.equals(collectionType)) { + return new ArrayDeque<>(); + } else if (Collection.class.equals(collectionType)) { + return new LinkedList<>(); } - + throw new IllegalArgumentException("Unsupported collection type: " + collectionType); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilter.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilter.java index bde1aa5a..4740c035 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilter.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilter.java @@ -5,18 +5,18 @@ import java.lang.reflect.Method; /** - * This filter will only accept methods that can be getters for properties (excluding the `is...` format usually used - * for {@literal boolean} types). + * This filter will only accept methods that can be getters for properties (excluding the `is...` + * format usually used for {@literal boolean} types). * * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (9/23/15) */ public class GetterMethodFilter implements ReflectionUtils.MethodFilter { - @Override - public boolean matches(Method method) { - return method.getName().matches("get[A-Z].*") && !void.class.equals(method.getReturnType()) - && method.getParameterTypes().length == 0; - } - + @Override + public boolean matches(Method method) { + return method.getName().matches("get[A-Z].*") + && !void.class.equals(method.getReturnType()) + && method.getParameterTypes().length == 0; + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/PropertyUtils.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/PropertyUtils.java index e0245d59..8b451229 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/PropertyUtils.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/PropertyUtils.java @@ -22,253 +22,263 @@ */ public final class PropertyUtils { - /** - * Used for storing all primitive-object mappings - */ - private static final Map, Class> types = new HashMap<>(); + /** Used for storing all primitive-object mappings */ + private static final Map, Class> types = new HashMap<>(); - private PropertyUtils() { - throw new UnsupportedOperationException(); - } + static { + types.put(int.class, Integer.class); + types.put(short.class, Short.class); + types.put(long.class, Long.class); + types.put(double.class, Double.class); + types.put(char.class, Character.class); + types.put(float.class, Float.class); + types.put(boolean.class, Boolean.class); + types.put(byte.class, Byte.class); + } - static { - types.put(int.class, Integer.class); - types.put(short.class, Short.class); - types.put(long.class, Long.class); - types.put(double.class, Double.class); - types.put(char.class, Character.class); - types.put(float.class, Float.class); - types.put(boolean.class, Boolean.class); - types.put(byte.class, Byte.class); - } + private PropertyUtils() { + throw new UnsupportedOperationException(); + } - /** - *

Given a property path will find out the proper way of accessing that property and - * return the value given the current context. The property path can use the "dot notation" to indicate nested - * properties (so that "x.y.z" would mean {@literal context.getX().getY().getZ()}).

- * - *

Properties can be accessed via getter methods or fields, with getter methods taking precedence. If a property - * doesn't exist at any given point, an error will be raised. If any property is set to {@literal null}, the chain - * evaluation will stop and {@literal null} will be returned. This means that if we are requesting access to the - * valid nested property {@literal x.y.z}, and {@literal y} is {@literal null}, instead of failing with an error, - * the reader will return {@literal null}.

- * - * @param context the object to evaluate the property path against - * @param property the property path as outlined above - * @return the value of the property - */ - public static Object getPropertyValue(Object context, String property) { - final String[] chain = property.split("\\."); - final List accessors = new ArrayList<>(); - Class type = context.getClass(); - final StringBuilder path = new StringBuilder(); - for (String current : chain) { - if (path.length() > 0) { - path.append('.'); - } - path.append(current); - final Method getter = ReflectionUtils.findMethod(type, "get" + StringUtils.capitalize(current)); - if (getter != null) { - accessors.add(getter); - type = getter.getReturnType(); - } else { - final Field field = ReflectionUtils.findField(type, current); - if (field != null) { - field.setAccessible(true); - accessors.add(field); - type = field.getType(); - } else { - throw new IllegalStateException( - "Cannot find property `" + path + "` on type `" + context.getClass() + "`"); - } - } - } - Object result = context; - for (Object accessor : accessors) { - try { - if (accessor instanceof Method) { - final Method method = (Method) accessor; - result = method.invoke(result); - } else { - final Field field = (Field) accessor; - result = field.get(result); - } - } catch (Exception e) { - throw new IllegalStateException("Failed to access property `" + property + "`", e); - } - if (result == null) { - return null; - } - } - return result; - } - - /** - * Sets the value of the given property to the provided value. The property path will follow the same rules as - * defined in {@link #getPropertyValue(Object, String)}, with the exception that if any of the parent properties in - * the nested path leading to the very last property (the one being modified) is {@literal null} an exception is - * thrown. - * - * @param context the context against which the property path will be evaluated - * @param property the property path - * @param value the value to set for the property - * @return the actual object that was changed. So, if the property path was {@literal x.y.z} on object {@literal - * context}, the returned value would be equivalent to {@literal context.getX().getY()}, since we are modifying the - * {@literal z} property of the {@literal y} object accessible by the mentioned chain of accessors. - */ - public static Object setPropertyValue(Object context, String property, Object value) { - if (property.contains(".")) { - final String[] split = property.split("\\.", 2); - final Object propertyValue = getPropertyValue(context, split[0]); - if (propertyValue == null) { - throw new IllegalStateException("Root property " + split[0] + " was null when reading " + property); - } - return setPropertyValue(propertyValue, split[1], value); - } - Method setter = null; - final String setterName = "set" + StringUtils.capitalize(property); - if (value != null) { - setter = ReflectionUtils.findMethod(context.getClass(), setterName, value.getClass()); + /** + * Given a property path will find out the proper way of accessing that property and return the + * value given the current context. The property path can use the "dot notation" to indicate + * nested properties (so that "x.y.z" would mean {@literal context.getX().getY().getZ()}). + * + *

Properties can be accessed via getter methods or fields, with getter methods taking + * precedence. If a property doesn't exist at any given point, an error will be raised. If any + * property is set to {@literal null}, the chain evaluation will stop and {@literal null} will be + * returned. This means that if we are requesting access to the valid nested property {@literal + * x.y.z}, and {@literal y} is {@literal null}, instead of failing with an error, the reader will + * return {@literal null}. + * + * @param context the object to evaluate the property path against + * @param property the property path as outlined above + * @return the value of the property + */ + public static Object getPropertyValue(Object context, String property) { + final String[] chain = property.split("\\."); + final List accessors = new ArrayList<>(); + Class type = context.getClass(); + final StringBuilder path = new StringBuilder(); + for (String current : chain) { + if (path.length() > 0) { + path.append('.'); + } + path.append(current); + final Method getter = + ReflectionUtils.findMethod(type, "get" + StringUtils.capitalize(current)); + if (getter != null) { + accessors.add(getter); + type = getter.getReturnType(); + } else { + final Field field = ReflectionUtils.findField(type, current); + if (field != null) { + field.setAccessible(true); + accessors.add(field); + type = field.getType(); } else { - for (Method method : ReflectionUtils.getAllDeclaredMethods(context.getClass())) { - if (method.getName().equals(setterName) && method.getParameterTypes().length == 1 && !method - .getParameterTypes()[0].isPrimitive()) { - setter = method; - break; - } - } + throw new IllegalStateException( + "Cannot find property `" + path + "` on type `" + context.getClass() + "`"); } - if (setter != null) { - try { - setter.invoke(context, value); - return context; - } catch (Exception e) { - throw new IllegalStateException("Failed to set property value through the setter method " + setter); - } + } + } + Object result = context; + for (Object accessor : accessors) { + try { + if (accessor instanceof Method) { + final Method method = (Method) accessor; + result = method.invoke(result); } else { - final Field field = ReflectionUtils.findField(context.getClass(), property); - if (field != null) { - if (Modifier.isFinal(field.getModifiers())) { - field.setAccessible(true); - } - try { - field.set(context, value); - return context; - } catch (Exception e) { - throw new IllegalStateException("Failed to set property value through the field " + field); - } - } + final Field field = (Field) accessor; + result = field.get(result); } - throw new IllegalStateException("Failed to find property " + property + " on " + context.getClass()); + } catch (Exception e) { + throw new IllegalStateException("Failed to access property `" + property + "`", e); + } + if (result == null) { + return null; + } } + return result; + } - /** - *

Given a property expression which contains CamelCase words will try to look up the property path - * leading up to the appropriate nested property. Property names will be matched eagerly, so that expression - * {@literal XxYy} will match property {@literal XxYy} if it exists, rather than {@literal Xx} first.

- * - *

If you wan to force the parser to avoid eager evaluation, you can insert an underscore ({@literal _}) - * character - * in place of the nested property separator. Thus, {@literal Xx_Yy} will force the parser to consider {@literal Xx} - * and only that property will satisfy the parser.

- * - * @param domainType the domain type that will be used to evaluate the property expression - * @param expression the property expression as explained above - * @return a property descriptor equipped with a proper property path (as described in {@link - * #getPropertyValue(Object, String)}) to let us read from and write to the described property. - */ - public static PropertyDescriptor getPropertyDescriptor(Class domainType, String expression) { - String search = expression; - final String followUp; - if (search.contains("_")) { - final String[] split = search.split("_", 2); - search = split[0]; - followUp = split[1]; - } else { - followUp = ""; - } - Class context = domainType; - final DocumentReader reader = new DefaultDocumentReader(search); - final List tokens = new ArrayList<>(); - while (reader.hasMore()) { - tokens.add(reader.expect("[A-Z][a-z]*")); + /** + * Sets the value of the given property to the provided value. The property path will follow the + * same rules as defined in {@link #getPropertyValue(Object, String)}, with the exception that if + * any of the parent properties in the nested path leading to the very last property (the one + * being modified) is {@literal null} an exception is thrown. + * + * @param context the context against which the property path will be evaluated + * @param property the property path + * @param value the value to set for the property + * @return the actual object that was changed. So, if the property path was {@literal x.y.z} on + * object {@literal context}, the returned value would be equivalent to {@literal + * context.getX().getY()}, since we are modifying the {@literal z} property of the {@literal + * y} object accessible by the mentioned chain of accessors. + */ + public static Object setPropertyValue(Object context, String property, Object value) { + if (property.contains(".")) { + final String[] split = property.split("\\.", 2); + final Object propertyValue = getPropertyValue(context, split[0]); + if (propertyValue == null) { + throw new IllegalStateException( + "Root property " + split[0] + " was null when reading " + property); + } + return setPropertyValue(propertyValue, split[1], value); + } + Method setter = null; + final String setterName = "set" + StringUtils.capitalize(property); + if (value != null) { + setter = ReflectionUtils.findMethod(context.getClass(), setterName, value.getClass()); + } else { + for (Method method : ReflectionUtils.getAllDeclaredMethods(context.getClass())) { + if (method.getName().equals(setterName) + && method.getParameterTypes().length == 1 + && !method.getParameterTypes()[0].isPrimitive()) { + setter = method; + break; } - int cursor = 0; - final StringBuilder path = new StringBuilder(); - while (cursor < tokens.size()) { - boolean found = false; - for (int i = tokens.size(); i >= cursor; i--) { - final String propertyName = getPropertyName(tokens, cursor, i); - final Method getter = ReflectionUtils.findMethod(context, "get" + StringUtils.capitalize(propertyName)); - if (getter != null) { - context = getter.getReturnType(); - cursor = i; - found = true; - path.append(".").append(propertyName); - break; - } - final Field field = ReflectionUtils.findField(context, propertyName); - if (field != null) { - context = field.getType(); - cursor = i; - found = true; - path.append(".").append(propertyName); - break; - } - } - if (!found) { - throw new IllegalStateException( - "Could not find property `" + getPropertyName(tokens, cursor, tokens.size()) + "` on `" - + context + "`"); - } + } + } + if (setter != null) { + try { + setter.invoke(context, value); + return context; + } catch (Exception e) { + throw new IllegalStateException( + "Failed to set property value through the setter method " + setter); + } + } else { + final Field field = ReflectionUtils.findField(context.getClass(), property); + if (field != null) { + if (Modifier.isFinal(field.getModifiers())) { + field.setAccessible(true); } - if (!followUp.isEmpty()) { - final PropertyDescriptor descriptor = getPropertyDescriptor(context, followUp); - return new ImmutablePropertyDescriptor(path.substring(1) + "." + descriptor.getPath(), - descriptor.getType()); + try { + field.set(context, value); + return context; + } catch (Exception e) { + throw new IllegalStateException( + "Failed to set property value through the field " + field); } - return new ImmutablePropertyDescriptor(path.substring(1), context); + } } + throw new IllegalStateException( + "Failed to find property " + property + " on " + context.getClass()); + } - /** - * Given a list of tokens (all of which are capitalized) this method composes a possible property name, so that - * {@literal ["Xx", "Yy", "Zz"]} becomes {@literal "xxYyZz"}. - * - * @param tokens the list of all tokens - * @param from the start index - * @param to the end index - * @return composed property name - */ - private static String getPropertyName(List tokens, int from, int to) { - final StringBuilder builder = new StringBuilder(); - for (int i = from; i < to; i++) { - builder.append(tokens.get(i)); + /** + * Given a property expression which contains CamelCase words will try to look up the property + * path leading up to the appropriate nested property. Property names will be matched eagerly, so + * that expression {@literal XxYy} will match property {@literal XxYy} if it exists, rather than + * {@literal Xx} first. + * + *

If you wan to force the parser to avoid eager evaluation, you can insert an underscore + * ({@literal _}) character in place of the nested property separator. Thus, {@literal Xx_Yy} will + * force the parser to consider {@literal Xx} and only that property will satisfy the parser. + * + * @param domainType the domain type that will be used to evaluate the property expression + * @param expression the property expression as explained above + * @return a property descriptor equipped with a proper property path (as described in {@link + * #getPropertyValue(Object, String)}) to let us read from and write to the described + * property. + */ + public static PropertyDescriptor getPropertyDescriptor(Class domainType, String expression) { + String search = expression; + final String followUp; + if (search.contains("_")) { + final String[] split = search.split("_", 2); + search = split[0]; + followUp = split[1]; + } else { + followUp = ""; + } + Class context = domainType; + final DocumentReader reader = new DefaultDocumentReader(search); + final List tokens = new ArrayList<>(); + while (reader.hasMore()) { + tokens.add(reader.expect("[A-Z][a-z]*")); + } + int cursor = 0; + final StringBuilder path = new StringBuilder(); + while (cursor < tokens.size()) { + boolean found = false; + for (int i = tokens.size(); i >= cursor; i--) { + final String propertyName = getPropertyName(tokens, cursor, i); + final Method getter = + ReflectionUtils.findMethod(context, "get" + StringUtils.capitalize(propertyName)); + if (getter != null) { + context = getter.getReturnType(); + cursor = i; + found = true; + path.append(".").append(propertyName); + break; } - return StringUtils.uncapitalize(builder.toString()); + final Field field = ReflectionUtils.findField(context, propertyName); + if (field != null) { + context = field.getType(); + cursor = i; + found = true; + path.append(".").append(propertyName); + break; + } + } + if (!found) { + throw new IllegalStateException( + "Could not find property `" + + getPropertyName(tokens, cursor, tokens.size()) + + "` on `" + + context + + "`"); + } + } + if (!followUp.isEmpty()) { + final PropertyDescriptor descriptor = getPropertyDescriptor(context, followUp); + return new ImmutablePropertyDescriptor( + path.substring(1) + "." + descriptor.getPath(), descriptor.getType()); } + return new ImmutablePropertyDescriptor(path.substring(1), context); + } - /** - * Returns the object type for the provided type. - * - * @param type the type to find out the object type for - * @return the object type for the type if it is a primitive, or the type itself if it is not. - */ - public static Class getTypeOf(Class type) { - if (type.isPrimitive()) { - return types.get(type); - } else { - return type; - } + /** + * Given a list of tokens (all of which are capitalized) this method composes a possible property + * name, so that {@literal ["Xx", "Yy", "Zz"]} becomes {@literal "xxYyZz"}. + * + * @param tokens the list of all tokens + * @param from the start index + * @param to the end index + * @return composed property name + */ + private static String getPropertyName(List tokens, int from, int to) { + final StringBuilder builder = new StringBuilder(); + for (int i = from; i < to; i++) { + builder.append(tokens.get(i)); } + return StringUtils.uncapitalize(builder.toString()); + } - /** - * Given a getter method finds out the property name for the getter - * - * @param getter the getter method - * @return the name of the property for the getter method - */ - public static String getPropertyName(Method getter) { - return StringUtils.uncapitalize(getter.getName().substring(3)); + /** + * Returns the object type for the provided type. + * + * @param type the type to find out the object type for + * @return the object type for the type if it is a primitive, or the type itself if it is not. + */ + public static Class getTypeOf(Class type) { + if (type.isPrimitive()) { + return types.get(type); + } else { + return type; } + } + /** + * Given a getter method finds out the property name for the getter + * + * @param getter the getter method + * @return the name of the property for the getter method + */ + public static String getPropertyName(Method getter) { + return StringUtils.uncapitalize(getter.getName().substring(3)); + } } diff --git a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/StringUtils.java b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/StringUtils.java index 2fe3f0fb..7e4831f5 100644 --- a/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/StringUtils.java +++ b/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/StringUtils.java @@ -11,30 +11,31 @@ @SuppressWarnings("WeakerAccess") public final class StringUtils { - private StringUtils() { - throw new UnsupportedOperationException(); - } + private StringUtils() { + throw new UnsupportedOperationException(); + } - /** - * Returns the same string as the original value, with the first letter turned to lower case - * - * @param expression the expression - * @return the un-capitalized version of the expression - */ - public static String uncapitalize(String expression) { - return Objects.requireNonNull(expression, "String value cannot be null").isEmpty() ? expression - : expression.substring(0, 1).toLowerCase() + expression.substring(1); - } - - /** - * Returns the same string as the original value, with the first letter turned to upper case - * - * @param expression the expression - * @return the un-capitalized version of the expression - */ - public static String capitalize(String expression) { - return Objects.requireNonNull(expression, "String value cannot be null").isEmpty() ? expression - : expression.substring(0, 1).toUpperCase() + expression.substring(1); - } + /** + * Returns the same string as the original value, with the first letter turned to lower case + * + * @param expression the expression + * @return the un-capitalized version of the expression + */ + public static String uncapitalize(String expression) { + return Objects.requireNonNull(expression, "String value cannot be null").isEmpty() + ? expression + : expression.substring(0, 1).toLowerCase() + expression.substring(1); + } + /** + * Returns the same string as the original value, with the first letter turned to upper case + * + * @param expression the expression + * @return the un-capitalized version of the expression + */ + public static String capitalize(String expression) { + return Objects.requireNonNull(expression, "String value cannot be null").isEmpty() + ? expression + : expression.substring(0, 1).toUpperCase() + expression.substring(1); + } } diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGeneratorTest.java index 7f51cb7a..c9134136 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGeneratorTest.java @@ -17,15 +17,14 @@ */ public class AbstractRandomKeyGeneratorTest { - @Test - public void testThatGeneratorProtectsUsFromDuplicates() { - final Set generatedKeys = new HashSet<>(); - final KeyGenerator generator = new DuplicatingKeyGenerator(); - for (int i = 0; i < 1000; i++) { - final Integer key = generator.generate(); - assertThat(generatedKeys, not(hasItem(key))); - generatedKeys.add(key); - } + @Test + public void testThatGeneratorProtectsUsFromDuplicates() { + final Set generatedKeys = new HashSet<>(); + final KeyGenerator generator = new DuplicatingKeyGenerator(); + for (int i = 0; i < 1000; i++) { + final Integer key = generator.generate(); + assertThat(generatedKeys, not(hasItem(key))); + generatedKeys.add(key); } - -} \ No newline at end of file + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/BaseKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/BaseKeyGeneratorTest.java index 76568001..95b003e7 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/BaseKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/BaseKeyGeneratorTest.java @@ -15,17 +15,16 @@ */ public abstract class BaseKeyGeneratorTest { - protected abstract KeyGenerator getKeyGenerator(); + protected abstract KeyGenerator getKeyGenerator(); - @Test(invocationCount = 100) - public void testThatKeysAreUnique() { - final KeyGenerator keyGenerator = getKeyGenerator(); - final Set keys = new HashSet<>(); - for (int i = 0; i < 200; i++) { - final S key = keyGenerator.generate(); - assertThat(keys.contains(key), is(false)); - keys.add(key); - } + @Test(invocationCount = 100) + public void testThatKeysAreUnique() { + final KeyGenerator keyGenerator = getKeyGenerator(); + final Set keys = new HashSet<>(); + for (int i = 0; i < 200; i++) { + final S key = keyGenerator.generate(); + assertThat(keys.contains(key), is(false)); + keys.add(key); } - + } } diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContextTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContextTest.java index e133a093..d5587e9a 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContextTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContextTest.java @@ -5,7 +5,9 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -13,26 +15,25 @@ */ public class DefaultOperatorContextTest { - @Test - public void testRegistering() { - final DefaultOperatorContext context = new DefaultOperatorContext(); - final ImmutableOperator operator = new ImmutableOperator("x", 1, null, "A"); - context.register(operator); - assertThat(context.getBySuffix("A"), is(notNullValue())); - assertThat(context.getBySuffix("A"), Matchers.is(operator)); - } + @Test + public void testRegistering() { + final DefaultOperatorContext context = new DefaultOperatorContext(); + final ImmutableOperator operator = new ImmutableOperator("x", 1, null, "A"); + context.register(operator); + assertThat(context.getBySuffix("A"), is(notNullValue())); + assertThat(context.getBySuffix("A"), Matchers.is(operator)); + } - @Test(expectedExceptions = DuplicateOperatorException.class) - public void testRegisteringDuplicates() { - final DefaultOperatorContext context = new DefaultOperatorContext(); - context.register(new ImmutableOperator("x", 1, null, "X", "A")); - context.register(new ImmutableOperator("y", 1, null, "B", "A")); - } + @Test(expectedExceptions = DuplicateOperatorException.class) + public void testRegisteringDuplicates() { + final DefaultOperatorContext context = new DefaultOperatorContext(); + context.register(new ImmutableOperator("x", 1, null, "X", "A")); + context.register(new ImmutableOperator("y", 1, null, "B", "A")); + } - @Test - public void testLookingForNonExistentOperator() { - final DefaultOperatorContext context = new DefaultOperatorContext(); - assertThat(context.getBySuffix("xyz"), is(nullValue())); - } - -} \ No newline at end of file + @Test + public void testLookingForNonExistentOperator() { + final DefaultOperatorContext context = new DefaultOperatorContext(); + assertThat(context.getBySuffix("xyz"), is(nullValue())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperatorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperatorTest.java index 464f59de..d318fe73 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperatorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperatorTest.java @@ -17,25 +17,27 @@ */ public class ImmutableMatchedOperatorTest { - private Operator original; - private MatchedOperator matchedOperator; - - @BeforeMethod - public void setUp() { - original = new ImmutableOperator("operator", new Random().nextInt(), new IsFalseMatcher(), "a", "b", "c"); - matchedOperator = new ImmutableMatchedOperator(original, "a"); - } - - @Test - public void testDelegation() { - assertThat(matchedOperator.getMatcher(), is(original.getMatcher())); - assertThat(matchedOperator.getName(), is(original.getName())); - assertThat(matchedOperator.getOperands(), is(original.getOperands())); - assertThat(matchedOperator.getTokens(), is(original.getTokens())); - } - - @Test - public void testMatchedToken() { - assertThat(matchedOperator.getMatchedToken(), is("a")); - } -} \ No newline at end of file + private Operator original; + private MatchedOperator matchedOperator; + + @BeforeMethod + public void setUp() { + original = + new ImmutableOperator( + "operator", new Random().nextInt(), new IsFalseMatcher(), "a", "b", "c"); + matchedOperator = new ImmutableMatchedOperator(original, "a"); + } + + @Test + public void testDelegation() { + assertThat(matchedOperator.getMatcher(), is(original.getMatcher())); + assertThat(matchedOperator.getName(), is(original.getName())); + assertThat(matchedOperator.getOperands(), is(original.getOperands())); + assertThat(matchedOperator.getTokens(), is(original.getTokens())); + } + + @Test + public void testMatchedToken() { + assertThat(matchedOperator.getMatchedToken(), is("a")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameterTest.java index b4c7be2a..b41ae1e6 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameterTest.java @@ -13,12 +13,14 @@ */ public class ImmutableParameterTest { - @Test - public void testToString() { - final ImmutableParameter parameter = new ImmutableParameter("x.y.z", Collections.emptySet(), - new int[]{2, 3, 4}, - new ImmutableOperator("op", 0, null)); - assertThat(parameter.toString(), is("(x.y.z,op,[2, 3, 4],[])")); - } - -} \ No newline at end of file + @Test + public void testToString() { + final ImmutableParameter parameter = + new ImmutableParameter( + "x.y.z", + Collections.emptySet(), + new int[] {2, 3, 4}, + new ImmutableOperator("op", 0, null)); + assertThat(parameter.toString(), is("(x.y.z,op,[2, 3, 4],[])")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparatorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparatorTest.java index 9ee5b1f1..6fe84778 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparatorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparatorTest.java @@ -4,7 +4,11 @@ import com.mmnaseri.utils.spring.data.query.NullHandling; import com.mmnaseri.utils.spring.data.query.SortDirection; import com.mmnaseri.utils.spring.data.query.impl.ImmutableOrder; -import com.mmnaseri.utils.spring.data.sample.models.*; +import com.mmnaseri.utils.spring.data.sample.models.Address; +import com.mmnaseri.utils.spring.data.sample.models.ChildZip; +import com.mmnaseri.utils.spring.data.sample.models.OtherChildZip; +import com.mmnaseri.utils.spring.data.sample.models.Person; +import com.mmnaseri.utils.spring.data.sample.models.Zip; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -16,78 +20,100 @@ */ public class PropertyComparatorTest { - @Test(expectedExceptions = InvalidArgumentException.class) - public void testWhenFirstValueDoesNotExist() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT)); - //noinspection ResultOfMethodCallIgnored - comparator.compare(new Address(), new Person()); - } + @Test(expectedExceptions = InvalidArgumentException.class) + public void testWhenFirstValueDoesNotExist() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT)); + //noinspection ResultOfMethodCallIgnored + comparator.compare(new Address(), new Person()); + } - @Test(expectedExceptions = InvalidArgumentException.class) - public void testWhenSecondValueDoesNotExist() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT)); - //noinspection ResultOfMethodCallIgnored - comparator.compare(new Person(), new Address()); - } + @Test(expectedExceptions = InvalidArgumentException.class) + public void testWhenSecondValueDoesNotExist() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT)); + //noinspection ResultOfMethodCallIgnored + comparator.compare(new Person(), new Address()); + } - @Test - public void testNullFirst() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_FIRST)); - assertThat(comparator.compare(new Person().setAddress(new Address().setCity("A")), new Person()), is(1)); - assertThat(comparator.compare(new Person(), new Person().setAddress(new Address().setCity("A"))), is(-1)); - } + @Test + public void testNullFirst() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_FIRST)); + assertThat( + comparator.compare(new Person().setAddress(new Address().setCity("A")), new Person()), + is(1)); + assertThat( + comparator.compare(new Person(), new Person().setAddress(new Address().setCity("A"))), + is(-1)); + } - @Test - public void testNullLast() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_LAST)); - assertThat(comparator.compare(new Person().setAddress(new Address().setCity("A")), new Person()), is(-1)); - assertThat(comparator.compare(new Person(), new Person().setAddress(new Address().setCity("A"))), is(1)); - } + @Test + public void testNullLast() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_LAST)); + assertThat( + comparator.compare(new Person().setAddress(new Address().setCity("A")), new Person()), + is(-1)); + assertThat( + comparator.compare(new Person(), new Person().setAddress(new Address().setCity("A"))), + is(1)); + } - @Test - public void testBothAreNull() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_LAST)); - assertThat(comparator.compare(new Person(), new Person()), is(0)); - } + @Test + public void testBothAreNull() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_LAST)); + assertThat(comparator.compare(new Person(), new Person()), is(0)); + } - @Test(expectedExceptions = InvalidArgumentException.class) - public void testWhenValuesAreNotComparable() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "address", NullHandling.NULLS_LAST)); - //noinspection ResultOfMethodCallIgnored - comparator.compare(new Person().setAddress(new Address()), new Person().setAddress(new Address())); - } + @Test(expectedExceptions = InvalidArgumentException.class) + public void testWhenValuesAreNotComparable() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "address", NullHandling.NULLS_LAST)); + //noinspection ResultOfMethodCallIgnored + comparator.compare( + new Person().setAddress(new Address()), new Person().setAddress(new Address())); + } - @Test - public void testWhenSecondIsSubTypeOfFirst() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST)); - final int comparison = comparator.compare(new Person().setAddressZip(new Zip().setPrefix("a")), - new Person().setAddressZip(new ChildZip().setPrefix("b"))); - assertThat(comparison, is(-1)); - } + @Test + public void testWhenSecondIsSubTypeOfFirst() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST)); + final int comparison = + comparator.compare( + new Person().setAddressZip(new Zip().setPrefix("a")), + new Person().setAddressZip(new ChildZip().setPrefix("b"))); + assertThat(comparison, is(-1)); + } - @Test - public void testWhenFirstIsSubTypeOfSecond() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST)); - final int comparison = comparator.compare(new Person().setAddressZip(new ChildZip().setPrefix("b")), - new Person().setAddressZip(new Zip().setPrefix("a"))); - assertThat(comparison, is(1)); - } + @Test + public void testWhenFirstIsSubTypeOfSecond() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST)); + final int comparison = + comparator.compare( + new Person().setAddressZip(new ChildZip().setPrefix("b")), + new Person().setAddressZip(new Zip().setPrefix("a"))); + assertThat(comparison, is(1)); + } - @Test(expectedExceptions = InvalidArgumentException.class) - public void testWhenValuesAreNotOfTheSameType() { - final PropertyComparator comparator = new PropertyComparator( - new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST)); - //noinspection ResultOfMethodCallIgnored - comparator.compare(new Person().setAddressZip(new ChildZip().setPrefix("b")), - new Person().setAddressZip(new OtherChildZip().setPrefix("a"))); - } - -} \ No newline at end of file + @Test(expectedExceptions = InvalidArgumentException.class) + public void testWhenValuesAreNotOfTheSameType() { + final PropertyComparator comparator = + new PropertyComparator( + new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST)); + //noinspection ResultOfMethodCallIgnored + comparator.compare( + new Person().setAddressZip(new ChildZip().setPrefix("b")), + new Person().setAddressZip(new OtherChildZip().setPrefix("a"))); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomIntegerKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomIntegerKeyGeneratorTest.java index 2d7387ff..cddc9df4 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomIntegerKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomIntegerKeyGeneratorTest.java @@ -9,9 +9,8 @@ */ public class RandomIntegerKeyGeneratorTest extends BaseKeyGeneratorTest { - @Override - protected KeyGenerator getKeyGenerator() { - return new RandomIntegerKeyGenerator(); - } - -} \ No newline at end of file + @Override + protected KeyGenerator getKeyGenerator() { + return new RandomIntegerKeyGenerator(); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomLongKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomLongKeyGeneratorTest.java index 41ea4cdb..730e607e 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomLongKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomLongKeyGeneratorTest.java @@ -9,9 +9,8 @@ */ public class RandomLongKeyGeneratorTest extends BaseKeyGeneratorTest { - @Override - protected KeyGenerator getKeyGenerator() { - return new RandomLongKeyGenerator(); - } - -} \ No newline at end of file + @Override + protected KeyGenerator getKeyGenerator() { + return new RandomLongKeyGenerator(); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperationTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperationTest.java index 2db0fbab..76ee7868 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperationTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperationTest.java @@ -4,7 +4,11 @@ import com.mmnaseri.utils.spring.data.query.NullHandling; import com.mmnaseri.utils.spring.data.query.PageParameterExtractor; import com.mmnaseri.utils.spring.data.query.SortDirection; -import com.mmnaseri.utils.spring.data.query.impl.*; +import com.mmnaseri.utils.spring.data.query.impl.DefaultQueryDescriptor; +import com.mmnaseri.utils.spring.data.query.impl.ImmutableOrder; +import com.mmnaseri.utils.spring.data.query.impl.ImmutableSort; +import com.mmnaseri.utils.spring.data.query.impl.PageablePageParameterExtractor; +import com.mmnaseri.utils.spring.data.query.impl.WrappedSortParameterExtractor; import com.mmnaseri.utils.spring.data.sample.models.Address; import com.mmnaseri.utils.spring.data.sample.models.Person; import com.mmnaseri.utils.spring.data.sample.repositories.RepositoryWithValidMethods; @@ -22,7 +26,12 @@ import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isIn; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -30,141 +39,215 @@ */ public class SelectDataStoreOperationTest { - private DataStore dataStore; + private DataStore dataStore; - @BeforeMethod - public void setUp() { - dataStore = new MemoryDataStore<>(Person.class); - dataStore.save("k1", new Person().setId("k1").setFirstName("Milad").setLastName("Naseri") - .setAddress(new Address().setCity("Tehran")).setAge(10)); - dataStore.save("k2", new Person().setId("k2").setFirstName("Zohreh").setLastName("Sadeghi") - .setAddress(new Address().setCity("Seattle")).setAge(12)); - dataStore.save("k3", new Person().setId("k3").setFirstName("Milad").setLastName("Naseri") - .setAddress(new Address().setCity("Seattle")).setAge(40)); - dataStore.save("k4", new Person().setId("k4").setFirstName("Zohreh").setLastName("Sadeghi") - .setAddress(new Address().setCity("Amol")).setAge(25)); - } + @BeforeMethod + public void setUp() { + dataStore = new MemoryDataStore<>(Person.class); + dataStore.save( + "k1", + new Person() + .setId("k1") + .setFirstName("Milad") + .setLastName("Naseri") + .setAddress(new Address().setCity("Tehran")) + .setAge(10)); + dataStore.save( + "k2", + new Person() + .setId("k2") + .setFirstName("Zohreh") + .setLastName("Sadeghi") + .setAddress(new Address().setCity("Seattle")) + .setAge(12)); + dataStore.save( + "k3", + new Person() + .setId("k3") + .setFirstName("Milad") + .setLastName("Naseri") + .setAddress(new Address().setCity("Seattle")) + .setAge(40)); + dataStore.save( + "k4", + new Person() + .setId("k4") + .setFirstName("Zohreh") + .setLastName("Sadeghi") + .setAddress(new Address().setCity("Amol")) + .setAge(25)); + } - @Test - public void testSimpleSelection() throws Exception { - final List> branches = new ArrayList<>(); - final DefaultOperatorContext operatorContext = new DefaultOperatorContext(); - branches.add(Arrays.asList( - new ImmutableParameter("firstName", Collections.emptySet(), new int[]{0}, - operatorContext.getBySuffix("Is")), - new ImmutableParameter("lastName", Collections.emptySet(), new int[]{1}, - operatorContext.getBySuffix("Is")) - )); - branches.add(Collections.singletonList( - new ImmutableParameter("address.city", Collections.emptySet(), new int[]{2}, - operatorContext.getBySuffix("Is")) - )); - branches.add(Collections.singletonList( - new ImmutableParameter("age", Collections.emptySet(), new int[]{3}, - operatorContext.getBySuffix("GreaterThan")) - )); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, - null); - final DataStoreOperation, String, Person> operation = new SelectDataStoreOperation<>(descriptor); - final List selected = operation.execute(dataStore, null, new ImmutableInvocation( - RepositoryWithValidMethods.class - .getMethod("findByFirstNameAndLastNameOrAddressCityOrAgeGreaterThan", String.class, - String.class, String.class, Integer.class), - new Object[]{"Milad", "Naseri", "Tabriz", 100})); - assertThat(selected, is(notNullValue())); - assertThat(selected, hasSize(2)); - assertThat(selected.get(0).getId(), isIn(Arrays.asList("k1", "k3"))); - assertThat(selected.get(1).getId(), isIn(Arrays.asList("k1", "k3"))); - } + @Test + public void testSimpleSelection() throws Exception { + final List> branches = new ArrayList<>(); + final DefaultOperatorContext operatorContext = new DefaultOperatorContext(); + branches.add( + Arrays.asList( + new ImmutableParameter( + "firstName", + Collections.emptySet(), + new int[] {0}, + operatorContext.getBySuffix("Is")), + new ImmutableParameter( + "lastName", + Collections.emptySet(), + new int[] {1}, + operatorContext.getBySuffix("Is")))); + branches.add( + Collections.singletonList( + new ImmutableParameter( + "address.city", + Collections.emptySet(), + new int[] {2}, + operatorContext.getBySuffix("Is")))); + branches.add( + Collections.singletonList( + new ImmutableParameter( + "age", + Collections.emptySet(), + new int[] {3}, + operatorContext.getBySuffix("GreaterThan")))); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null); + final DataStoreOperation, String, Person> operation = + new SelectDataStoreOperation<>(descriptor); + final List selected = + operation.execute( + dataStore, + null, + new ImmutableInvocation( + RepositoryWithValidMethods.class.getMethod( + "findByFirstNameAndLastNameOrAddressCityOrAgeGreaterThan", + String.class, + String.class, + String.class, + Integer.class), + new Object[] {"Milad", "Naseri", "Tabriz", 100})); + assertThat(selected, is(notNullValue())); + assertThat(selected, hasSize(2)); + assertThat(selected.get(0).getId(), isIn(Arrays.asList("k1", "k3"))); + assertThat(selected.get(1).getId(), isIn(Arrays.asList("k1", "k3"))); + } - @Test - public void testSorting() throws Exception { - final ImmutableOrder first = new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT); - final ImmutableOrder second = new ImmutableOrder(SortDirection.ASCENDING, "lastName", NullHandling.DEFAULT); - final ImmutableSort sort = new ImmutableSort(Arrays.asList(first, second)); - final WrappedSortParameterExtractor sortExtractor = new WrappedSortParameterExtractor(sort); - final List> branches = new ArrayList<>(); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, sortExtractor, - branches, null, null); - final DataStoreOperation, String, Person> operation = new SelectDataStoreOperation<>(descriptor); - final List selected = operation.execute(dataStore, null, new ImmutableInvocation( - RepositoryWithValidMethods.class.getMethod("findAll"), new Object[]{})); - assertThat(selected, hasSize(4)); - assertThat(selected, containsInAnyOrder(dataStore.retrieveAll().toArray())); - assertThat(selected.get(0).getId(), is("k4")); - assertThat(selected.get(1).getId(), is("k3")); - assertThat(selected.get(2).getId(), is("k2")); - assertThat(selected.get(3).getId(), is("k1")); - } + @Test + public void testSorting() throws Exception { + final ImmutableOrder first = + new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT); + final ImmutableOrder second = + new ImmutableOrder(SortDirection.ASCENDING, "lastName", NullHandling.DEFAULT); + final ImmutableSort sort = new ImmutableSort(Arrays.asList(first, second)); + final WrappedSortParameterExtractor sortExtractor = new WrappedSortParameterExtractor(sort); + final List> branches = new ArrayList<>(); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, sortExtractor, branches, null, null); + final DataStoreOperation, String, Person> operation = + new SelectDataStoreOperation<>(descriptor); + final List selected = + operation.execute( + dataStore, + null, + new ImmutableInvocation( + RepositoryWithValidMethods.class.getMethod("findAll"), new Object[] {})); + assertThat(selected, hasSize(4)); + assertThat(selected, containsInAnyOrder(dataStore.retrieveAll().toArray())); + assertThat(selected.get(0).getId(), is("k4")); + assertThat(selected.get(1).getId(), is("k3")); + assertThat(selected.get(2).getId(), is("k2")); + assertThat(selected.get(3).getId(), is("k1")); + } - @Test - public void testPagingWhenPageStartIsBeyondSelection() throws Exception { - final List> branches = new ArrayList<>(); - final PageParameterExtractor pageExtractor = new PageablePageParameterExtractor(0); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, pageExtractor, null, - branches, null, null); - final SelectDataStoreOperation operation = new SelectDataStoreOperation<>(descriptor); - final List selected = operation.execute(dataStore, null, new ImmutableInvocation( + @Test + public void testPagingWhenPageStartIsBeyondSelection() throws Exception { + final List> branches = new ArrayList<>(); + final PageParameterExtractor pageExtractor = new PageablePageParameterExtractor(0); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, pageExtractor, null, branches, null, null); + final SelectDataStoreOperation operation = + new SelectDataStoreOperation<>(descriptor); + final List selected = + operation.execute( + dataStore, + null, + new ImmutableInvocation( RepositoryWithValidMethods.class.getMethod("findAll", Pageable.class), - new Object[]{PageRequest.of(2, 10)})); - assertThat(selected, is(empty())); - } + new Object[] {PageRequest.of(2, 10)})); + assertThat(selected, is(empty())); + } - @Test - public void testPagingWhenLastPageIsNotFull() throws Exception { - final PageParameterExtractor pageExtractor = new PageablePageParameterExtractor(0); - final List> branches = Collections.emptyList(); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, pageExtractor, null, - branches, null, null); - final DataStoreOperation, String, Person> operation = new SelectDataStoreOperation<>(descriptor); - final List selected = operation.execute(dataStore, null, new ImmutableInvocation( + @Test + public void testPagingWhenLastPageIsNotFull() throws Exception { + final PageParameterExtractor pageExtractor = new PageablePageParameterExtractor(0); + final List> branches = Collections.emptyList(); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, pageExtractor, null, branches, null, null); + final DataStoreOperation, String, Person> operation = + new SelectDataStoreOperation<>(descriptor); + final List selected = + operation.execute( + dataStore, + null, + new ImmutableInvocation( RepositoryWithValidMethods.class.getMethod("findAll", Pageable.class), - new Object[]{PageRequest.of(1, 3)})); - assertThat(selected, hasSize(1)); - } - - @Test - public void testLimitingTheResult() throws Exception { - for (int limit = 1; limit < 10; limit++) { - final List> branches = Collections.emptyList(); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, limit, null, null, - branches, null, null); - final DataStoreOperation, String, Person> operation = new SelectDataStoreOperation<>( - descriptor); - final List selected = operation.execute(dataStore, null, new ImmutableInvocation( - RepositoryWithValidMethods.class.getMethod("findAll"), new Object[]{})); - assertThat(selected, hasSize(Math.min(limit, dataStore.retrieveAll().size()))); - } - } + new Object[] {PageRequest.of(1, 3)})); + assertThat(selected, hasSize(1)); + } - @Test - public void testLoadingDistinctValues() throws Exception { - dataStore.save("k5", new Person().setId("k1")); - final List> branches = Collections.emptyList(); - //not distinct - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, - null); - final DataStoreOperation, String, Person> operation = new SelectDataStoreOperation<>(descriptor); - final List selected = operation.execute(dataStore, null, new ImmutableInvocation( - RepositoryWithValidMethods.class.getMethod("findAll"), new Object[]{})); - assertThat(selected, hasSize(5)); - //distinct - final DefaultQueryDescriptor descriptorDistinct = new DefaultQueryDescriptor(true, null, 0, null, null, - branches, null, null); - final DataStoreOperation, String, Person> operationDistinct = new SelectDataStoreOperation<>( - descriptorDistinct); - final List selectedDistinct = operationDistinct.execute(dataStore, null, new ImmutableInvocation( - RepositoryWithValidMethods.class.getMethod("findAll"), new Object[]{})); - assertThat(selectedDistinct, hasSize(4)); + @Test + public void testLimitingTheResult() throws Exception { + for (int limit = 1; limit < 10; limit++) { + final List> branches = Collections.emptyList(); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, limit, null, null, branches, null, null); + final DataStoreOperation, String, Person> operation = + new SelectDataStoreOperation<>(descriptor); + final List selected = + operation.execute( + dataStore, + null, + new ImmutableInvocation( + RepositoryWithValidMethods.class.getMethod("findAll"), new Object[] {})); + assertThat(selected, hasSize(Math.min(limit, dataStore.retrieveAll().size()))); } + } - @Test - public void testToString() { - final List> branches = Collections.emptyList(); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, - null); - final DataStoreOperation, String, Person> operation = new SelectDataStoreOperation<>(descriptor); - assertThat(operation.toString(), is(descriptor.toString())); - } + @Test + public void testLoadingDistinctValues() throws Exception { + dataStore.save("k5", new Person().setId("k1")); + final List> branches = Collections.emptyList(); + // not distinct + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null); + final DataStoreOperation, String, Person> operation = + new SelectDataStoreOperation<>(descriptor); + final List selected = + operation.execute( + dataStore, + null, + new ImmutableInvocation( + RepositoryWithValidMethods.class.getMethod("findAll"), new Object[] {})); + assertThat(selected, hasSize(5)); + // distinct + final DefaultQueryDescriptor descriptorDistinct = + new DefaultQueryDescriptor(true, null, 0, null, null, branches, null, null); + final DataStoreOperation, String, Person> operationDistinct = + new SelectDataStoreOperation<>(descriptorDistinct); + final List selectedDistinct = + operationDistinct.execute( + dataStore, + null, + new ImmutableInvocation( + RepositoryWithValidMethods.class.getMethod("findAll"), new Object[] {})); + assertThat(selectedDistinct, hasSize(4)); + } -} \ No newline at end of file + @Test + public void testToString() { + final List> branches = Collections.emptyList(); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null); + final DataStoreOperation, String, Person> operation = + new SelectDataStoreOperation<>(descriptor); + assertThat(operation.toString(), is(descriptor.toString())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SequentialLongKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SequentialLongKeyGeneratorTest.java index 75569a66..808730f5 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SequentialLongKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SequentialLongKeyGeneratorTest.java @@ -13,20 +13,19 @@ */ public class SequentialLongKeyGeneratorTest extends BaseKeyGeneratorTest { - @Override - protected KeyGenerator getKeyGenerator() { - return new SequentialLongKeyGenerator(); - } + @Override + protected KeyGenerator getKeyGenerator() { + return new SequentialLongKeyGenerator(); + } - @Test - public void testKeysBeingSequential() { - final KeyGenerator keyGenerator = getKeyGenerator(); - Long last = 0L; - for (int i = 0; i < 100; i++) { - final Long key = keyGenerator.generate(); - assertThat(key, is(last + 1)); - last = key; - } + @Test + public void testKeysBeingSequential() { + final KeyGenerator keyGenerator = getKeyGenerator(); + Long last = 0L; + for (int i = 0; i < 100; i++) { + final Long key = keyGenerator.generate(); + assertThat(key, is(last + 1)); + last = key; } - -} \ No newline at end of file + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/UUIDKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/UUIDKeyGeneratorTest.java index 29e7c3f9..c1257e71 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/UUIDKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/UUIDKeyGeneratorTest.java @@ -9,9 +9,8 @@ */ public class UUIDKeyGeneratorTest extends BaseKeyGeneratorTest { - @Override - protected KeyGenerator getKeyGenerator() { - return new UUIDKeyGenerator(); - } - -} \ No newline at end of file + @Override + protected KeyGenerator getKeyGenerator() { + return new UUIDKeyGenerator(); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedFieldIdPropertyResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedFieldIdPropertyResolverTest.java index 014bfade..bc7ac31d 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedFieldIdPropertyResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedFieldIdPropertyResolverTest.java @@ -1,7 +1,12 @@ package com.mmnaseri.utils.spring.data.domain.impl.id; import com.mmnaseri.utils.spring.data.domain.IdPropertyResolver; -import com.mmnaseri.utils.spring.data.sample.models.*; +import com.mmnaseri.utils.spring.data.sample.models.EmbeddableId; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedEmbeddedIdFieldFromJPA; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedIdField; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedIdFieldFromJPA; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithMultipleAnnotatedFields; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithoutAnnotatedFields; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -15,41 +20,41 @@ @SuppressWarnings("unused") public class AnnotatedFieldIdPropertyResolverTest extends BaseRepeatableIdPropertyResolverTest { - @Override - protected IdPropertyResolver getIdPropertyResolver() { - return new AnnotatedFieldIdPropertyResolver(); - } - - @Override - protected Class properEntity() { - return EntityWithAnnotatedIdField.class; - } - - @Override - protected Class entityWithNoProperty() { - return EntityWithoutAnnotatedFields.class; - } - - @Override - protected Class entityWithMultipleProperties() { - return EntityWithMultipleAnnotatedFields.class; - } - - /** - * Regression test for https://github.com/mmnaseri/spring-data-mock/issues/55 - */ - @Test - public void testResolvingIdPropertyWhenIdAnnotationOnFieldIsFromJPA() { - final String property = getIdPropertyResolver().resolve(EntityWithAnnotatedIdFieldFromJPA.class, Long.class); - assertThat(property, is(notNullValue())); - assertThat(property, is("customIdProperty")); - } - - @Test - public void testResolvingEmbeddedIdPropertyWhenIdAnnotationOnFieldIsFromJPA() { - final String property = getIdPropertyResolver().resolve(EntityWithAnnotatedEmbeddedIdFieldFromJPA.class, EmbeddableId.class); - assertThat(property, is(notNullValue())); - assertThat(property, is("customIdProperty")); - } - -} \ No newline at end of file + @Override + protected IdPropertyResolver getIdPropertyResolver() { + return new AnnotatedFieldIdPropertyResolver(); + } + + @Override + protected Class properEntity() { + return EntityWithAnnotatedIdField.class; + } + + @Override + protected Class entityWithNoProperty() { + return EntityWithoutAnnotatedFields.class; + } + + @Override + protected Class entityWithMultipleProperties() { + return EntityWithMultipleAnnotatedFields.class; + } + + /** Regression test for https://github.com/mmnaseri/spring-data-mock/issues/55 */ + @Test + public void testResolvingIdPropertyWhenIdAnnotationOnFieldIsFromJPA() { + final String property = + getIdPropertyResolver().resolve(EntityWithAnnotatedIdFieldFromJPA.class, Long.class); + assertThat(property, is(notNullValue())); + assertThat(property, is("customIdProperty")); + } + + @Test + public void testResolvingEmbeddedIdPropertyWhenIdAnnotationOnFieldIsFromJPA() { + final String property = + getIdPropertyResolver() + .resolve(EntityWithAnnotatedEmbeddedIdFieldFromJPA.class, EmbeddableId.class); + assertThat(property, is(notNullValue())); + assertThat(property, is("customIdProperty")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedGetterIdPropertyResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedGetterIdPropertyResolverTest.java index 936f61ff..38f51efa 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedGetterIdPropertyResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/AnnotatedGetterIdPropertyResolverTest.java @@ -1,7 +1,12 @@ package com.mmnaseri.utils.spring.data.domain.impl.id; import com.mmnaseri.utils.spring.data.domain.IdPropertyResolver; -import com.mmnaseri.utils.spring.data.sample.models.*; +import com.mmnaseri.utils.spring.data.sample.models.EmbeddableId; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedEmbeddedIdGetterFromJPA; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedIdGetter; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedIdGetterFromJPA; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithMultipleAnnotatedIdGetters; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithoutAnnotatedIdGetter; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -15,43 +20,41 @@ @SuppressWarnings("unused") public class AnnotatedGetterIdPropertyResolverTest extends BaseRepeatableIdPropertyResolverTest { - @Override - protected IdPropertyResolver getIdPropertyResolver() { - return new AnnotatedGetterIdPropertyResolver(); - } - - @Override - protected Class properEntity() { - return EntityWithAnnotatedIdGetter.class; - } - - @Override - protected Class entityWithNoProperty() { - return EntityWithoutAnnotatedIdGetter.class; - } - - @Override - protected Class entityWithMultipleProperties() { - return EntityWithMultipleAnnotatedIdGetters.class; - } - - /** - * Regression test for https://github.com/mmnaseri/spring-data-mock/issues/55 - * - */ - @Test - public void testResolvingIdPropertyWhenIdAnnotationOnGetterIsFromJPA() { - final String property = getIdPropertyResolver().resolve(EntityWithAnnotatedIdGetterFromJPA.class, - Integer.class); - assertThat(property, is(notNullValue())); - assertThat(property, is("myCustomId")); - } - - @Test - public void testResolvingIdPropertyWhenEmbeddedIdAnnotationOnGetterIsFromJPA() { - final String property = getIdPropertyResolver().resolve(EntityWithAnnotatedEmbeddedIdGetterFromJPA.class, EmbeddableId.class); - assertThat(property, is(notNullValue())); - assertThat(property, is("myCustomId")); - } - -} \ No newline at end of file + @Override + protected IdPropertyResolver getIdPropertyResolver() { + return new AnnotatedGetterIdPropertyResolver(); + } + + @Override + protected Class properEntity() { + return EntityWithAnnotatedIdGetter.class; + } + + @Override + protected Class entityWithNoProperty() { + return EntityWithoutAnnotatedIdGetter.class; + } + + @Override + protected Class entityWithMultipleProperties() { + return EntityWithMultipleAnnotatedIdGetters.class; + } + + /** Regression test for https://github.com/mmnaseri/spring-data-mock/issues/55 */ + @Test + public void testResolvingIdPropertyWhenIdAnnotationOnGetterIsFromJPA() { + final String property = + getIdPropertyResolver().resolve(EntityWithAnnotatedIdGetterFromJPA.class, Integer.class); + assertThat(property, is(notNullValue())); + assertThat(property, is("myCustomId")); + } + + @Test + public void testResolvingIdPropertyWhenEmbeddedIdAnnotationOnGetterIsFromJPA() { + final String property = + getIdPropertyResolver() + .resolve(EntityWithAnnotatedEmbeddedIdGetterFromJPA.class, EmbeddableId.class); + assertThat(property, is(notNullValue())); + assertThat(property, is("myCustomId")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/BaseIdPropertyResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/BaseIdPropertyResolverTest.java index aa58b593..06edd76b 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/BaseIdPropertyResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/BaseIdPropertyResolverTest.java @@ -5,7 +5,9 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -13,38 +15,38 @@ */ public abstract class BaseIdPropertyResolverTest { - protected abstract IdPropertyResolver getIdPropertyResolver(); - - protected abstract Class properEntity(); - - protected abstract Class entityWithNoProperty(); - - @Test(expectedExceptions = PropertyTypeMismatchException.class) - public void testFindingTheIdFieldWithWrongType() { - final IdPropertyResolver resolver = getIdPropertyResolver(); - resolver.resolve(properEntity(), Long.class); - } - - @Test - public void testFindingTheIdFieldWithSuperType() { - final IdPropertyResolver resolver = getIdPropertyResolver(); - final String resolved = resolver.resolve(properEntity(), Object.class); - assertThat(resolved, is(notNullValue())); - assertThat(resolved, is("id")); - } - - @Test - public void testFindingTheIdFieldWithCorrectType() { - final IdPropertyResolver resolver = getIdPropertyResolver(); - final String resolved = resolver.resolve(properEntity(), String.class); - assertThat(resolved, is(notNullValue())); - assertThat(resolved, is("id")); - } - - @Test - public void testFindingTheIdFieldOnEntityWithoutAnnotations() { - final IdPropertyResolver resolver = getIdPropertyResolver(); - final String resolved = resolver.resolve(entityWithNoProperty(), Object.class); - assertThat(resolved, is(nullValue())); - } + protected abstract IdPropertyResolver getIdPropertyResolver(); + + protected abstract Class properEntity(); + + protected abstract Class entityWithNoProperty(); + + @Test(expectedExceptions = PropertyTypeMismatchException.class) + public void testFindingTheIdFieldWithWrongType() { + final IdPropertyResolver resolver = getIdPropertyResolver(); + resolver.resolve(properEntity(), Long.class); + } + + @Test + public void testFindingTheIdFieldWithSuperType() { + final IdPropertyResolver resolver = getIdPropertyResolver(); + final String resolved = resolver.resolve(properEntity(), Object.class); + assertThat(resolved, is(notNullValue())); + assertThat(resolved, is("id")); + } + + @Test + public void testFindingTheIdFieldWithCorrectType() { + final IdPropertyResolver resolver = getIdPropertyResolver(); + final String resolved = resolver.resolve(properEntity(), String.class); + assertThat(resolved, is(notNullValue())); + assertThat(resolved, is("id")); + } + + @Test + public void testFindingTheIdFieldOnEntityWithoutAnnotations() { + final IdPropertyResolver resolver = getIdPropertyResolver(); + final String resolved = resolver.resolve(entityWithNoProperty(), Object.class); + assertThat(resolved, is(nullValue())); + } } diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/BaseRepeatableIdPropertyResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/BaseRepeatableIdPropertyResolverTest.java index 96e0c959..a5d5028a 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/BaseRepeatableIdPropertyResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/BaseRepeatableIdPropertyResolverTest.java @@ -10,12 +10,11 @@ */ public abstract class BaseRepeatableIdPropertyResolverTest extends BaseIdPropertyResolverTest { - protected abstract Class entityWithMultipleProperties(); - - @Test(expectedExceptions = MultipleIdPropertiesException.class) - public void testFindingTheIdFieldOnEntityWithMultipleAnnotatedFields() { - final IdPropertyResolver resolver = getIdPropertyResolver(); - resolver.resolve(entityWithMultipleProperties(), Object.class); - } + protected abstract Class entityWithMultipleProperties(); + @Test(expectedExceptions = MultipleIdPropertiesException.class) + public void testFindingTheIdFieldOnEntityWithMultipleAnnotatedFields() { + final IdPropertyResolver resolver = getIdPropertyResolver(); + resolver.resolve(entityWithMultipleProperties(), Object.class); + } } diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/EntityIdPropertyResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/EntityIdPropertyResolverTest.java index 67d56548..fba5b433 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/EntityIdPropertyResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/EntityIdPropertyResolverTest.java @@ -2,7 +2,12 @@ import com.mmnaseri.utils.spring.data.error.NoIdPropertyException; import com.mmnaseri.utils.spring.data.error.PrimitiveIdTypeException; -import com.mmnaseri.utils.spring.data.sample.models.*; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotationOnIdFieldAndGetterAndAnIdField; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithIdFieldAndAnAnnotatedIdField; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithIdFieldHiddenBehindDifferentlyNamedAccessors; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithNoImmediatelyResolvableIdProperty; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithPrimitiveIdProperty; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithUnderscorePrecedingIdField; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -16,55 +21,54 @@ */ public class EntityIdPropertyResolverTest { - private EntityIdPropertyResolver resolver; + private EntityIdPropertyResolver resolver; - @BeforeMethod - public void setUp() { - resolver = new EntityIdPropertyResolver(); - } + @BeforeMethod + public void setUp() { + resolver = new EntityIdPropertyResolver(); + } - @Test - public void testThatAnnotatedGetterHasPrecedence() { - final String resolved = resolver.resolve(EntityWithAnnotationOnIdFieldAndGetterAndAnIdField.class, - Object.class); - assertThat(resolved, is(notNullValue())); - assertThat(resolved, is("unannotatedId")); - } + @Test + public void testThatAnnotatedGetterHasPrecedence() { + final String resolved = + resolver.resolve(EntityWithAnnotationOnIdFieldAndGetterAndAnIdField.class, Object.class); + assertThat(resolved, is(notNullValue())); + assertThat(resolved, is("unannotatedId")); + } - @Test - public void testThatAnnotatedPropertyIsSecond() { - final String resolved = resolver.resolve(EntityWithIdFieldAndAnAnnotatedIdField.class, Object.class); - assertThat(resolved, is(notNullValue())); - assertThat(resolved, is("annotatedId")); - } + @Test + public void testThatAnnotatedPropertyIsSecond() { + final String resolved = + resolver.resolve(EntityWithIdFieldAndAnAnnotatedIdField.class, Object.class); + assertThat(resolved, is(notNullValue())); + assertThat(resolved, is("annotatedId")); + } - @Test - public void testThatNamedGetterIsThird() { - final String resolved = resolver.resolve(EntityWithUnderscorePrecedingIdField.class, Object.class); - assertThat(resolved, is(notNullValue())); - assertThat(resolved, is("id")); - } + @Test + public void testThatNamedGetterIsThird() { + final String resolved = + resolver.resolve(EntityWithUnderscorePrecedingIdField.class, Object.class); + assertThat(resolved, is(notNullValue())); + assertThat(resolved, is("id")); + } - @Test - public void testThatNamedFieldIsFourth() { - final String resolved = resolver.resolve(EntityWithIdFieldHiddenBehindDifferentlyNamedAccessors.class, - Object.class); - assertThat(resolved, is(notNullValue())); - assertThat(resolved, is("id")); - } + @Test + public void testThatNamedFieldIsFourth() { + final String resolved = + resolver.resolve( + EntityWithIdFieldHiddenBehindDifferentlyNamedAccessors.class, Object.class); + assertThat(resolved, is(notNullValue())); + assertThat(resolved, is("id")); + } - @Test(expectedExceptions = NoIdPropertyException.class) - public void testThatNoOtherValueIsHonored() { - resolver.resolve(EntityWithNoImmediatelyResolvableIdProperty.class, Object.class); - } + @Test(expectedExceptions = NoIdPropertyException.class) + public void testThatNoOtherValueIsHonored() { + resolver.resolve(EntityWithNoImmediatelyResolvableIdProperty.class, Object.class); + } - /** - * see https://github.com/mmnaseri/spring-data-mock/issues/83 - * - */ - @Test(expectedExceptions = PrimitiveIdTypeException.class) - public void testPrimitiveIdTypeDoesNotWork() { - resolver.resolve(EntityWithPrimitiveIdProperty.class, Long.class); - } - -} \ No newline at end of file + /** see https://github.com/mmnaseri/spring-data-mock/issues/83 */ + @Test(expectedExceptions = PrimitiveIdTypeException.class) + public void testPrimitiveIdTypeDoesNotWork() { + resolver.resolve(EntityWithPrimitiveIdProperty.class, Long.class); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/IdPropertyResolverUtilsTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/IdPropertyResolverUtilsTest.java index 707265ff..e6a6086e 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/IdPropertyResolverUtilsTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/IdPropertyResolverUtilsTest.java @@ -1,7 +1,14 @@ package com.mmnaseri.utils.spring.data.domain.impl.id; import com.mmnaseri.utils.spring.data.error.PropertyTypeMismatchException; -import com.mmnaseri.utils.spring.data.sample.models.*; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedEmbeddedIdField; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedEmbeddedIdFieldFromJPA; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedEmbeddedIdGetter; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedEmbeddedIdGetterFromJPA; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedIdField; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedIdFieldFromJPA; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedIdGetter; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotatedIdGetterFromJPA; import com.mmnaseri.utils.spring.data.tools.AbstractUtilityClassTest; import org.testng.annotations.Test; @@ -18,61 +25,93 @@ */ public class IdPropertyResolverUtilsTest extends AbstractUtilityClassTest { - @Override - protected Class getUtilityClass() { - return IdPropertyResolverUtils.class; - } + @Override + protected Class getUtilityClass() { + return IdPropertyResolverUtils.class; + } - @Test - public void testReadingAnnotationFromField() throws Exception { - assertThat(IdPropertyResolverUtils.isAnnotated(EntityWithAnnotatedIdFieldFromJPA.class.getDeclaredField("customIdProperty")), is(true)); - assertThat(IdPropertyResolverUtils.isAnnotated(EntityWithAnnotatedEmbeddedIdFieldFromJPA.class.getDeclaredField("customIdProperty")), is(true)); - assertThat(IdPropertyResolverUtils.isAnnotated(EntityWithAnnotatedIdField.class.getDeclaredField("id")), is(true)); - assertThat(IdPropertyResolverUtils.isAnnotated(EntityWithAnnotatedEmbeddedIdField.class.getDeclaredField("id")), is(true)); - } + @Test + public void testReadingAnnotationFromField() throws Exception { + assertThat( + IdPropertyResolverUtils.isAnnotated( + EntityWithAnnotatedIdFieldFromJPA.class.getDeclaredField("customIdProperty")), + is(true)); + assertThat( + IdPropertyResolverUtils.isAnnotated( + EntityWithAnnotatedEmbeddedIdFieldFromJPA.class.getDeclaredField("customIdProperty")), + is(true)); + assertThat( + IdPropertyResolverUtils.isAnnotated( + EntityWithAnnotatedIdField.class.getDeclaredField("id")), + is(true)); + assertThat( + IdPropertyResolverUtils.isAnnotated( + EntityWithAnnotatedEmbeddedIdField.class.getDeclaredField("id")), + is(true)); + } - @Test - public void testReadingAnnotationFromMethod() throws Exception { - assertThat(IdPropertyResolverUtils.isAnnotated(EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")), is(true)); - assertThat(IdPropertyResolverUtils.isAnnotated(EntityWithAnnotatedEmbeddedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")), is(true)); - assertThat(IdPropertyResolverUtils.isAnnotated(EntityWithAnnotatedIdGetter.class.getDeclaredMethod("getId")), is(true)); - assertThat(IdPropertyResolverUtils.isAnnotated(EntityWithAnnotatedEmbeddedIdGetter.class.getDeclaredMethod("getId")), is(true)); - } + @Test + public void testReadingAnnotationFromMethod() throws Exception { + assertThat( + IdPropertyResolverUtils.isAnnotated( + EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")), + is(true)); + assertThat( + IdPropertyResolverUtils.isAnnotated( + EntityWithAnnotatedEmbeddedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")), + is(true)); + assertThat( + IdPropertyResolverUtils.isAnnotated( + EntityWithAnnotatedIdGetter.class.getDeclaredMethod("getId")), + is(true)); + assertThat( + IdPropertyResolverUtils.isAnnotated( + EntityWithAnnotatedEmbeddedIdGetter.class.getDeclaredMethod("getId")), + is(true)); + } - @Test(expectedExceptions = PropertyTypeMismatchException.class) - public void testPropertyNameFromMethodWhenIdTypeIsInvalid() throws Exception { - IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod(EntityWithAnnotatedIdGetterFromJPA.class, Long.class, - EntityWithAnnotatedIdGetterFromJPA.class - .getDeclaredMethod("getMyCustomId")); - } + @Test(expectedExceptions = PropertyTypeMismatchException.class) + public void testPropertyNameFromMethodWhenIdTypeIsInvalid() throws Exception { + IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod( + EntityWithAnnotatedIdGetterFromJPA.class, + Long.class, + EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")); + } - @Test - public void testPropertyNameFromMethod() throws Exception { - final String propertyName = IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod( - EntityWithAnnotatedIdGetterFromJPA.class, Integer.class, - EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")); - assertThat(propertyName, is(notNullValue())); - assertThat(propertyName, is("myCustomId")); - } + @Test + public void testPropertyNameFromMethod() throws Exception { + final String propertyName = + IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod( + EntityWithAnnotatedIdGetterFromJPA.class, + Integer.class, + EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")); + assertThat(propertyName, is(notNullValue())); + assertThat(propertyName, is("myCustomId")); + } - @Test - public void testPropertyNameFromMethodWithEmbeddedId() throws Exception { - final String propertyName = IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod(EntityWithAnnotatedEmbeddedIdGetterFromJPA.class, Integer.class, EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")); - assertThat(propertyName, is(notNullValue())); - assertThat(propertyName, is("myCustomId")); - } + @Test + public void testPropertyNameFromMethodWithEmbeddedId() throws Exception { + final String propertyName = + IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod( + EntityWithAnnotatedEmbeddedIdGetterFromJPA.class, + Integer.class, + EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")); + assertThat(propertyName, is(notNullValue())); + assertThat(propertyName, is("myCustomId")); + } - @Test - public void testDeclaringAnnotationsThatAreNotPresent() throws Exception { - final Field idAnnotations = IdPropertyResolverUtils.class.getDeclaredField("ID_ANNOTATIONS"); - idAnnotations.setAccessible(true); - final List list = (List) idAnnotations.get(null); - //noinspection unchecked - list.add("random class name"); - final String propertyName = IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod( - EntityWithAnnotatedIdGetterFromJPA.class, Integer.class, - EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")); - assertThat(propertyName, is(notNullValue())); - } - -} \ No newline at end of file + @Test + public void testDeclaringAnnotationsThatAreNotPresent() throws Exception { + final Field idAnnotations = IdPropertyResolverUtils.class.getDeclaredField("ID_ANNOTATIONS"); + idAnnotations.setAccessible(true); + final List list = (List) idAnnotations.get(null); + //noinspection unchecked + list.add("random class name"); + final String propertyName = + IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod( + EntityWithAnnotatedIdGetterFromJPA.class, + Integer.class, + EntityWithAnnotatedIdGetterFromJPA.class.getDeclaredMethod("getMyCustomId")); + assertThat(propertyName, is(notNullValue())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedFieldIdPropertyResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedFieldIdPropertyResolverTest.java index 8cc92424..019e7a77 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedFieldIdPropertyResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedFieldIdPropertyResolverTest.java @@ -10,19 +10,18 @@ */ public class NamedFieldIdPropertyResolverTest extends BaseIdPropertyResolverTest { - @Override - protected IdPropertyResolver getIdPropertyResolver() { - return new NamedFieldIdPropertyResolver(); - } + @Override + protected IdPropertyResolver getIdPropertyResolver() { + return new NamedFieldIdPropertyResolver(); + } - @Override - protected Class properEntity() { - return EntityWithIdField.class; - } + @Override + protected Class properEntity() { + return EntityWithIdField.class; + } - @Override - protected Class entityWithNoProperty() { - return EmptyEntity.class; - } - -} \ No newline at end of file + @Override + protected Class entityWithNoProperty() { + return EmptyEntity.class; + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedGetterIdPropertyResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedGetterIdPropertyResolverTest.java index 2475879c..9d8c9599 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedGetterIdPropertyResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/id/NamedGetterIdPropertyResolverTest.java @@ -11,19 +11,18 @@ @SuppressWarnings("unused") public class NamedGetterIdPropertyResolverTest extends BaseIdPropertyResolverTest { - @Override - protected IdPropertyResolver getIdPropertyResolver() { - return new NamedGetterIdPropertyResolver(); - } + @Override + protected IdPropertyResolver getIdPropertyResolver() { + return new NamedGetterIdPropertyResolver(); + } - @Override - protected Class properEntity() { - return EntityWithoutAnnotatedIdGetter.class; - } + @Override + protected Class properEntity() { + return EntityWithoutAnnotatedIdGetter.class; + } - @Override - protected Class entityWithNoProperty() { - return EmptyEntity.class; - } - -} \ No newline at end of file + @Override + protected Class entityWithNoProperty() { + return EmptyEntity.class; + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGeneratorTest.java index d6714e52..3964dea0 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGeneratorTest.java @@ -8,28 +8,31 @@ import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; public class BsonObjectIdKeyGeneratorTest { - private BsonObjectIdKeyGenerator generator; + private BsonObjectIdKeyGenerator generator; - @BeforeMethod - public void setUp() { - generator = new BsonObjectIdKeyGenerator(); - } + @BeforeMethod + public void setUp() { + generator = new BsonObjectIdKeyGenerator(); + } - @Test - public void testNotNullValue() { - assertThat(generator.generate(), is(notNullValue())); - } + @Test + public void testNotNullValue() { + assertThat(generator.generate(), is(notNullValue())); + } - @Test - public void testUniqueness() { - final Set set = new HashSet<>(); - for (int i = 0; i < 1000; i++) { - final ObjectId id = generator.generate(); - assertThat(set, not(contains(id))); - } + @Test + public void testUniqueness() { + final Set set = new HashSet<>(); + for (int i = 0; i < 1000; i++) { + final ObjectId id = generator.generate(); + assertThat(set, not(contains(id))); } -} \ No newline at end of file + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGeneratorTest.java index 873446f3..ba704d4e 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGeneratorTest.java @@ -12,31 +12,32 @@ */ public class ConfigurableSequentialIntegerKeyGeneratorTest { - @Test - public void testKeyGenerationWithDefaultSettings() { - final KeyGenerator generator = new ConfigurableSequentialIntegerKeyGenerator(); - assertThat(generator.generate(), is(1)); - assertThat(generator.generate(), is(2)); - assertThat(generator.generate(), is(3)); - } + @Test + public void testKeyGenerationWithDefaultSettings() { + final KeyGenerator generator = new ConfigurableSequentialIntegerKeyGenerator(); + assertThat(generator.generate(), is(1)); + assertThat(generator.generate(), is(2)); + assertThat(generator.generate(), is(3)); + } - @Test - public void testKeyGenerationWithDefaultStepAndCustomInitialValue() { - final int initialValue = 100; - final KeyGenerator generator = new ConfigurableSequentialIntegerKeyGenerator(initialValue); - assertThat(generator.generate(), is(initialValue)); - assertThat(generator.generate(), is(initialValue + 1)); - assertThat(generator.generate(), is(initialValue + 2)); - } + @Test + public void testKeyGenerationWithDefaultStepAndCustomInitialValue() { + final int initialValue = 100; + final KeyGenerator generator = + new ConfigurableSequentialIntegerKeyGenerator(initialValue); + assertThat(generator.generate(), is(initialValue)); + assertThat(generator.generate(), is(initialValue + 1)); + assertThat(generator.generate(), is(initialValue + 2)); + } - @Test - public void testKeyGenerationWithCustomStepAndCustomInitialValue() { - final int initialValue = 100; - final int step = 3; - final KeyGenerator generator = new ConfigurableSequentialIntegerKeyGenerator(initialValue, step); - assertThat(generator.generate(), is(initialValue)); - assertThat(generator.generate(), is(initialValue + step)); - assertThat(generator.generate(), is(initialValue + step * 2)); - } - -} \ No newline at end of file + @Test + public void testKeyGenerationWithCustomStepAndCustomInitialValue() { + final int initialValue = 100; + final int step = 3; + final KeyGenerator generator = + new ConfigurableSequentialIntegerKeyGenerator(initialValue, step); + assertThat(generator.generate(), is(initialValue)); + assertThat(generator.generate(), is(initialValue + step)); + assertThat(generator.generate(), is(initialValue + step * 2)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGeneratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGeneratorTest.java index f314d4b1..91042747 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGeneratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGeneratorTest.java @@ -12,31 +12,31 @@ */ public class ConfigurableSequentialLongKeyGeneratorTest { - @Test - public void testKeyGenerationWithDefaultSettings() { - final KeyGenerator generator = new ConfigurableSequentialLongKeyGenerator(); - assertThat(generator.generate(), is(1L)); - assertThat(generator.generate(), is(2L)); - assertThat(generator.generate(), is(3L)); - } + @Test + public void testKeyGenerationWithDefaultSettings() { + final KeyGenerator generator = new ConfigurableSequentialLongKeyGenerator(); + assertThat(generator.generate(), is(1L)); + assertThat(generator.generate(), is(2L)); + assertThat(generator.generate(), is(3L)); + } - @Test - public void testKeyGenerationWithDefaultStepAndCustomInitialValue() { - final long initialValue = 100L; - final KeyGenerator generator = new ConfigurableSequentialLongKeyGenerator(initialValue); - assertThat(generator.generate(), is(initialValue)); - assertThat(generator.generate(), is(initialValue + 1)); - assertThat(generator.generate(), is(initialValue + 2)); - } + @Test + public void testKeyGenerationWithDefaultStepAndCustomInitialValue() { + final long initialValue = 100L; + final KeyGenerator generator = new ConfigurableSequentialLongKeyGenerator(initialValue); + assertThat(generator.generate(), is(initialValue)); + assertThat(generator.generate(), is(initialValue + 1)); + assertThat(generator.generate(), is(initialValue + 2)); + } - @Test - public void testKeyGenerationWithCustomStepAndCustomInitialValue() { - final long initialValue = 100L; - final long step = 3L; - final KeyGenerator generator = new ConfigurableSequentialLongKeyGenerator(initialValue, step); - assertThat(generator.generate(), is(initialValue)); - assertThat(generator.generate(), is(initialValue + step)); - assertThat(generator.generate(), is(initialValue + step * 2)); - } - -} \ No newline at end of file + @Test + public void testKeyGenerationWithCustomStepAndCustomInitialValue() { + final long initialValue = 100L; + final long step = 3L; + final KeyGenerator generator = + new ConfigurableSequentialLongKeyGenerator(initialValue, step); + assertThat(generator.generate(), is(initialValue)); + assertThat(generator.generate(), is(initialValue + step)); + assertThat(generator.generate(), is(initialValue + step * 2)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryComparableMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryComparableMatcherTest.java index 364f4fe5..c26b3a42 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryComparableMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryComparableMatcherTest.java @@ -11,28 +11,33 @@ */ public class AbstractBinaryComparableMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenValueIsNotComparable() { - final NotMatchingBinaryComparableMatcher matcher = new NotMatchingBinaryComparableMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 1, 2); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenValueIsNotComparable() { + final NotMatchingBinaryComparableMatcher matcher = new NotMatchingBinaryComparableMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 1, 2); + } - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenFirstParameterIsNotComparable() { - final NotMatchingBinaryComparableMatcher matcher = new NotMatchingBinaryComparableMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, new Object(), 2); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenFirstParameterIsNotComparable() { + final NotMatchingBinaryComparableMatcher matcher = new NotMatchingBinaryComparableMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, new Object(), 2); + } - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenSecondParameterIsNotComparable() { - final NotMatchingBinaryComparableMatcher matcher = new NotMatchingBinaryComparableMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, 2, new Object()); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenSecondParameterIsNotComparable() { + final NotMatchingBinaryComparableMatcher matcher = new NotMatchingBinaryComparableMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, 2, new Object()); + } - @Test - public void testWhenAllAreComparable() { - final NotMatchingBinaryComparableMatcher matcher = new NotMatchingBinaryComparableMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, 2, 3); - } - -} \ No newline at end of file + @Test + public void testWhenAllAreComparable() { + final NotMatchingBinaryComparableMatcher matcher = new NotMatchingBinaryComparableMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, 2, 3); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryMatcherTest.java index 50f35084..89cd2c7c 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractBinaryMatcherTest.java @@ -15,50 +15,61 @@ */ public class AbstractBinaryMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenHasLessThanTwoParameters() { - final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, new ImmutableOperator("sample", 2, null)), - new Object()); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenHasLessThanTwoParameters() { + final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); + matcher.matches( + new ImmutableParameter("x.y.z", null, null, new ImmutableOperator("sample", 2, null)), + new Object()); + } - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenHasMoreThanTwoParameters() { - final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, new ImmutableOperator("sample", 2, null)), - new Object(), new Object(), new Object(), new Object()); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenHasMoreThanTwoParameters() { + final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); + matcher.matches( + new ImmutableParameter("x.y.z", null, null, new ImmutableOperator("sample", 2, null)), + new Object(), + new Object(), + new Object(), + new Object()); + } - @Test - public void testWhenHasTwoParameters() { - final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); - //we are creating the varargs array explicitly to call to the proper method signature - //noinspection RedundantArrayCreation - matcher.matches(new ImmutableParameter("x.y.z", null, null, new ImmutableOperator("sample", 2, null)), - new Object(), new Object[]{new Object(), new Object()}); - } + @Test + public void testWhenHasTwoParameters() { + final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); + // we are creating the varargs array explicitly to call to the proper method signature + //noinspection RedundantArrayCreation + matcher.matches( + new ImmutableParameter("x.y.z", null, null, new ImmutableOperator("sample", 2, null)), + new Object(), + new Object[] {new Object(), new Object()}); + } - @Test - public void testIsApplicableTo() { - final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); - assertTrue(matcher.isApplicableTo(String.class, String.class, String.class)); - } + @Test + public void testIsApplicableTo() { + final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); + assertTrue(matcher.isApplicableTo(String.class, String.class, String.class)); + } - @Test - public void shouldNotBeApplicableToOnlyOneArgument() { - final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); - assertFalse(matcher.isApplicableTo(String.class, String.class)); - } + @Test + public void shouldNotBeApplicableToOnlyOneArgument() { + final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); + assertFalse(matcher.isApplicableTo(String.class, String.class)); + } - @Test - public void shouldNotBeApplicableToIncompatibleFirstArgument() { - final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); - assertFalse(matcher.isApplicableTo(String.class, Integer.class, String.class)); - } + @Test + public void shouldNotBeApplicableToIncompatibleFirstArgument() { + final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); + assertFalse(matcher.isApplicableTo(String.class, Integer.class, String.class)); + } - @Test - public void shouldNotBeApplicableToIncompatibleSecondArgument() { - final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); - assertFalse(matcher.isApplicableTo(String.class, String.class, Integer.class)); - } -} \ No newline at end of file + @Test + public void shouldNotBeApplicableToIncompatibleSecondArgument() { + final NotMatchingBinaryMatcher matcher = new NotMatchingBinaryMatcher(); + assertFalse(matcher.isApplicableTo(String.class, String.class, Integer.class)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcherTest.java index 28f1c569..bf8b2828 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcherTest.java @@ -9,7 +9,11 @@ import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -17,43 +21,45 @@ */ public class AbstractCollectionMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, - expectedExceptionsMessageRegExp = "Comparison property cannot be null: xyz") - public void testWhenPivotIsNull() { - new SpyingCollectionMatcher().matches(new ImmutableParameter("xyz", null, null, null), 1, new Object[]{null}); - } - - @Test - public void testPassingInAnArray() { - final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); - matcher.matches(null, null, new Object[]{new Object[]{1, 2, 3, 4}}); - assertThat(matcher.getCollection(), is(notNullValue())); - assertThat(matcher.getCollection(), hasSize(4)); - assertThat(matcher.getCollection(), contains(1, 2, 3, 4)); - } - - @Test - public void testPassingInAnIterator() { - final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); - matcher.matches(null, null, new Object[]{Arrays.asList(1, 2, 3, 4).iterator()}); - assertThat(matcher.getCollection(), is(notNullValue())); - assertThat(matcher.getCollection(), hasSize(4)); - assertThat(matcher.getCollection(), contains(1, 2, 3, 4)); - } - - @Test - public void testPassingInAnIterable() { - final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); - matcher.matches(null, null, new Object[]{new HashSet<>(Arrays.asList(1, 2, 3, 4))}); - assertThat(matcher.getCollection(), is(notNullValue())); - assertThat(matcher.getCollection(), hasSize(4)); - assertThat(matcher.getCollection(), containsInAnyOrder(1, 2, 3, 4)); - } - - @Test(expectedExceptions = InvalidArgumentException.class, - expectedExceptionsMessageRegExp = "Expected an array, an iterator, or an iterable object") - public void testPassingInAnythingElse() { - new SpyingCollectionMatcher().matches(null, null, new Object[]{new Object()}); - } - -} \ No newline at end of file + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Comparison property cannot be null: xyz") + public void testWhenPivotIsNull() { + new SpyingCollectionMatcher() + .matches(new ImmutableParameter("xyz", null, null, null), 1, new Object[] {null}); + } + + @Test + public void testPassingInAnArray() { + final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); + matcher.matches(null, null, new Object[] {new Object[] {1, 2, 3, 4}}); + assertThat(matcher.getCollection(), is(notNullValue())); + assertThat(matcher.getCollection(), hasSize(4)); + assertThat(matcher.getCollection(), contains(1, 2, 3, 4)); + } + + @Test + public void testPassingInAnIterator() { + final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); + matcher.matches(null, null, new Object[] {Arrays.asList(1, 2, 3, 4).iterator()}); + assertThat(matcher.getCollection(), is(notNullValue())); + assertThat(matcher.getCollection(), hasSize(4)); + assertThat(matcher.getCollection(), contains(1, 2, 3, 4)); + } + + @Test + public void testPassingInAnIterable() { + final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); + matcher.matches(null, null, new Object[] {new HashSet<>(Arrays.asList(1, 2, 3, 4))}); + assertThat(matcher.getCollection(), is(notNullValue())); + assertThat(matcher.getCollection(), hasSize(4)); + assertThat(matcher.getCollection(), containsInAnyOrder(1, 2, 3, 4)); + } + + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Expected an array, an iterator, or an iterable object") + public void testPassingInAnythingElse() { + new SpyingCollectionMatcher().matches(null, null, new Object[] {new Object()}); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcherTest.java index f8af10f5..2920c4b0 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcherTest.java @@ -11,22 +11,25 @@ */ public class AbstractSimpleComparableMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenActualIsNotComparable() { - final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 2); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenActualIsNotComparable() { + final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 2); + } - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenPivotIsNotComparable() { - final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, new Object()); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenPivotIsNotComparable() { + final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, new Object()); + } - @Test - public void testWhenBothAreComparable() { - final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, 2); - } - -} \ No newline at end of file + @Test + public void testWhenBothAreComparable() { + final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, 2); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleMatcherTest.java index ffc1ee5e..7da5f096 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleMatcherTest.java @@ -14,45 +14,49 @@ */ public class AbstractSimpleMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenHasNoParameters() { - final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object()); - } - - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenHasMoreThanOneParameters() { - final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 1, 2, 3); - } - - @Test - public void testWhenHasOneParameter() { - final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 1); - } - - @Test - public void testApplicableToSameType() { - final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); - assertTrue(matcher.isApplicableTo(String.class, String.class)); - } - - @Test - public void testApplicableToSubType() { - final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); - assertTrue(matcher.isApplicableTo(Number.class, Integer.class)); - } - - @Test - public void testNonApplicableToDifferentType() { - final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); - assertFalse(matcher.isApplicableTo(String.class, Integer.class)); - } - - @Test - public void shouldNotBeApplicableToDifferentNumberOfArguments() { - final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); - assertFalse(matcher.isApplicableTo(String.class, String.class, String.class)); - } -} \ No newline at end of file + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenHasNoParameters() { + final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object()); + } + + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenHasMoreThanOneParameters() { + final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 1, 2, 3); + } + + @Test + public void testWhenHasOneParameter() { + final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 1); + } + + @Test + public void testApplicableToSameType() { + final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); + assertTrue(matcher.isApplicableTo(String.class, String.class)); + } + + @Test + public void testApplicableToSubType() { + final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); + assertTrue(matcher.isApplicableTo(Number.class, Integer.class)); + } + + @Test + public void testNonApplicableToDifferentType() { + final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); + assertFalse(matcher.isApplicableTo(String.class, Integer.class)); + } + + @Test + public void shouldNotBeApplicableToDifferentNumberOfArguments() { + final NotMatchingSimpleMatcher matcher = new NotMatchingSimpleMatcher(); + assertFalse(matcher.isApplicableTo(String.class, String.class, String.class)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcherTest.java index 4c038bb7..f8ef5c94 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcherTest.java @@ -17,31 +17,36 @@ */ public class AbstractSimpleStringMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testValueNotAString() { - final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, ""); - } - - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testParameterNotAString() { - final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), "", 1); - } - - @Test - public void testWhenBothAreStrings() { - final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), "", ""); - } - - @Test - public void testWhenIgnoringCase() { - final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", Collections.singleton(Modifier.IGNORE_CASE), null, null), - "test", "TEST"); - assertThat(matcher.getActual(), is("test")); - assertThat(matcher.getArgument(), is("test")); - } - -} \ No newline at end of file + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testValueNotAString() { + final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, ""); + } + + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testParameterNotAString() { + final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), "", 1); + } + + @Test + public void testWhenBothAreStrings() { + final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), "", ""); + } + + @Test + public void testWhenIgnoringCase() { + final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher(); + matcher.matches( + new ImmutableParameter("x.y.z", Collections.singleton(Modifier.IGNORE_CASE), null, null), + "test", + "TEST"); + assertThat(matcher.getActual(), is("test")); + assertThat(matcher.getArgument(), is("test")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractUnaryMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractUnaryMatcherTest.java index 43ab1644..9c843357 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractUnaryMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractUnaryMatcherTest.java @@ -14,22 +14,27 @@ */ public class AbstractUnaryMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = ".*x.y.z.*") - public void testWhenHasParameters() { - final NotMatchingUnaryMatcher matcher = new NotMatchingUnaryMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, new ImmutableOperator("sample operator", 0, null)), - new Object(), new Object()); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = ".*x.y.z.*") + public void testWhenHasParameters() { + final NotMatchingUnaryMatcher matcher = new NotMatchingUnaryMatcher(); + matcher.matches( + new ImmutableParameter( + "x.y.z", null, null, new ImmutableOperator("sample operator", 0, null)), + new Object(), + new Object()); + } - @Test - public void testWhenHasNoParameters() { - final NotMatchingUnaryMatcher matcher = new NotMatchingUnaryMatcher(); - matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object()); - } + @Test + public void testWhenHasNoParameters() { + final NotMatchingUnaryMatcher matcher = new NotMatchingUnaryMatcher(); + matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object()); + } - @Test - public void shouldNotApplyToNonEmptyListOfParameters() { - final NotMatchingUnaryMatcher matcher = new NotMatchingUnaryMatcher(); - assertFalse(matcher.isApplicableTo(String.class, String.class)); - } -} \ No newline at end of file + @Test + public void shouldNotApplyToNonEmptyListOfParameters() { + final NotMatchingUnaryMatcher matcher = new NotMatchingUnaryMatcher(); + assertFalse(matcher.isApplicableTo(String.class, String.class)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/ContainingMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/ContainingMatcherTest.java index c3cbcceb..b66f3169 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/ContainingMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/ContainingMatcherTest.java @@ -11,24 +11,23 @@ */ public class ContainingMatcherTest { - @Test - public void testMatchingWhenActualIsNull() { - assertThat(new ContainingMatcher().matches(null, ""), is(false)); - } - - @Test - public void testMatchingWhenParameterIsNull() { - assertThat(new ContainingMatcher().matches("", null), is(false)); - } - - @Test - public void testMatchingWhenParameterDoesNotContainActual() { - assertThat(new ContainingMatcher().matches("xyz", "abc"), is(false)); - } - - @Test - public void testMatchingWhenParameterContainsActual() { - assertThat(new ContainingMatcher().matches("HelloWorld", "owo"), is(true)); - } - -} \ No newline at end of file + @Test + public void testMatchingWhenActualIsNull() { + assertThat(new ContainingMatcher().matches(null, ""), is(false)); + } + + @Test + public void testMatchingWhenParameterIsNull() { + assertThat(new ContainingMatcher().matches("", null), is(false)); + } + + @Test + public void testMatchingWhenParameterDoesNotContainActual() { + assertThat(new ContainingMatcher().matches("xyz", "abc"), is(false)); + } + + @Test + public void testMatchingWhenParameterContainsActual() { + assertThat(new ContainingMatcher().matches("HelloWorld", "owo"), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/EndingWithMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/EndingWithMatcherTest.java index a848f684..0245b313 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/EndingWithMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/EndingWithMatcherTest.java @@ -11,29 +11,28 @@ */ public class EndingWithMatcherTest { - @Test - public void testWhenActualIsNull() { - assertThat(new EndingWithMatcher().matches(null, ""), is(false)); - } - - @Test - public void testWhenParameterIsNull() { - assertThat(new EndingWithMatcher().matches("", null), is(false)); - } - - @Test - public void testWhenBothAreNull() { - assertThat(new EndingWithMatcher().matches(null, null), is(false)); - } - - @Test - public void testWhenActualDoesNotEndWithParameter() { - assertThat(new EndingWithMatcher().matches("xyz", "abc"), is(false)); - } - - @Test - public void testWhenActualEndsWithParameter() { - assertThat(new EndingWithMatcher().matches("HelloWorld", "WORLD"), is(true)); - } - -} \ No newline at end of file + @Test + public void testWhenActualIsNull() { + assertThat(new EndingWithMatcher().matches(null, ""), is(false)); + } + + @Test + public void testWhenParameterIsNull() { + assertThat(new EndingWithMatcher().matches("", null), is(false)); + } + + @Test + public void testWhenBothAreNull() { + assertThat(new EndingWithMatcher().matches(null, null), is(false)); + } + + @Test + public void testWhenActualDoesNotEndWithParameter() { + assertThat(new EndingWithMatcher().matches("xyz", "abc"), is(false)); + } + + @Test + public void testWhenActualEndsWithParameter() { + assertThat(new EndingWithMatcher().matches("HelloWorld", "WORLD"), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsBetweenMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsBetweenMatcherTest.java index a4f595ec..593963e4 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsBetweenMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsBetweenMatcherTest.java @@ -11,35 +11,34 @@ */ public class IsBetweenMatcherTest { - @Test - public void testWhenActualIsNull() { - assertThat(new IsBetweenMatcher().matches(null, 1, 2), is(false)); - } - - @Test - public void testWhenLowerBoundIsNull() { - assertThat(new IsBetweenMatcher().matches(1, null, 2), is(false)); - } - - @Test - public void testWhenUpperBoundIsNull() { - assertThat(new IsBetweenMatcher().matches(1, 2, null), is(false)); - } - - @Test - public void testWhenRangeDoesNotContainValue() { - assertThat(new IsBetweenMatcher().matches(1, 3, 6), is(false)); - } - - @Test - public void testWhenRangeContainsValueInclusive() { - assertThat(new IsBetweenMatcher().matches(3, 3, 6), is(true)); - assertThat(new IsBetweenMatcher().matches(6, 3, 6), is(true)); - } - - @Test - public void testWhenRangeContainsValueMidRange() { - assertThat(new IsBetweenMatcher().matches(4, 3, 6), is(true)); - } - -} \ No newline at end of file + @Test + public void testWhenActualIsNull() { + assertThat(new IsBetweenMatcher().matches(null, 1, 2), is(false)); + } + + @Test + public void testWhenLowerBoundIsNull() { + assertThat(new IsBetweenMatcher().matches(1, null, 2), is(false)); + } + + @Test + public void testWhenUpperBoundIsNull() { + assertThat(new IsBetweenMatcher().matches(1, 2, null), is(false)); + } + + @Test + public void testWhenRangeDoesNotContainValue() { + assertThat(new IsBetweenMatcher().matches(1, 3, 6), is(false)); + } + + @Test + public void testWhenRangeContainsValueInclusive() { + assertThat(new IsBetweenMatcher().matches(3, 3, 6), is(true)); + assertThat(new IsBetweenMatcher().matches(6, 3, 6), is(true)); + } + + @Test + public void testWhenRangeContainsValueMidRange() { + assertThat(new IsBetweenMatcher().matches(4, 3, 6), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsEqualToMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsEqualToMatcherTest.java index 26dd43ec..6f8697b9 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsEqualToMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsEqualToMatcherTest.java @@ -11,30 +11,29 @@ */ public class IsEqualToMatcherTest { - @Test - public void testWhenBothAreNull() { - assertThat(new IsEqualToMatcher().matches(null, null, new Object[]{null}), is(true)); - } - - @Test - public void testWhenTheyAreTheSameInstance() { - final Object obj = new Object(); - assertThat(new IsEqualToMatcher().matches(null, obj, obj), is(true)); - } - - @Test - public void testWhenTheyHaveTheSameValue() { - assertThat(new IsEqualToMatcher().matches(null, 1, 1), is(true)); - } - - @Test - public void testWhenTheyDiffer() { - assertThat(new IsEqualToMatcher().matches(null, new Object(), new Object()), is(false)); - } - - @Test - public void testWhenTheyHaveDifferentValues() { - assertThat(new IsEqualToMatcher().matches(null, 1, 2), is(false)); - } - -} \ No newline at end of file + @Test + public void testWhenBothAreNull() { + assertThat(new IsEqualToMatcher().matches(null, null, new Object[] {null}), is(true)); + } + + @Test + public void testWhenTheyAreTheSameInstance() { + final Object obj = new Object(); + assertThat(new IsEqualToMatcher().matches(null, obj, obj), is(true)); + } + + @Test + public void testWhenTheyHaveTheSameValue() { + assertThat(new IsEqualToMatcher().matches(null, 1, 1), is(true)); + } + + @Test + public void testWhenTheyDiffer() { + assertThat(new IsEqualToMatcher().matches(null, new Object(), new Object()), is(false)); + } + + @Test + public void testWhenTheyHaveDifferentValues() { + assertThat(new IsEqualToMatcher().matches(null, 1, 2), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsFalseMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsFalseMatcherTest.java index c1f9e739..c7529812 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsFalseMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsFalseMatcherTest.java @@ -11,24 +11,23 @@ */ public class IsFalseMatcherTest { - @Test - public void testWhenSubjectIsNull() { - assertThat(new IsFalseMatcher().matches(null), is(false)); - } - - @Test - public void testSubjectIsNonBoolean() { - assertThat(new IsFalseMatcher().matches(""), is(false)); - } - - @Test - public void testIsFalse() { - assertThat(new IsFalseMatcher().matches(false), is(true)); - } - - @Test - public void testIsTrue() { - assertThat(new IsFalseMatcher().matches(true), is(false)); - } - -} \ No newline at end of file + @Test + public void testWhenSubjectIsNull() { + assertThat(new IsFalseMatcher().matches(null), is(false)); + } + + @Test + public void testSubjectIsNonBoolean() { + assertThat(new IsFalseMatcher().matches(""), is(false)); + } + + @Test + public void testIsFalse() { + assertThat(new IsFalseMatcher().matches(false), is(true)); + } + + @Test + public void testIsTrue() { + assertThat(new IsFalseMatcher().matches(true), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanMatcherTest.java index e05228e9..dea5e75f 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanMatcherTest.java @@ -13,35 +13,36 @@ */ public class IsGreaterThanMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, - expectedExceptionsMessageRegExp = "Expected property to be comparable: xyz") - public void testValueIsNotComparable() { - new IsGreaterThanMatcher().matches(new ImmutableParameter("xyz", null, null, null), new Object(), new Object()); - } - - @Test - public void testValuesAreEqual() { - assertThat(new IsGreaterThanMatcher().matches(5, 5), is(false)); - } - - @Test - public void testActualIsLessThanPivot() { - assertThat(new IsGreaterThanMatcher().matches(1, 5), is(false)); - } - - @Test - public void testActualIsGreaterThanPivot() { - assertThat(new IsGreaterThanMatcher().matches(10, 5), is(true)); - } - - @Test - public void testActualIsNull() { - assertThat(new IsGreaterThanMatcher().matches(null, 5), is(false)); - } - - @Test - public void testPivotIsNull() { - assertThat(new IsGreaterThanMatcher().matches(5, null), is(false)); - } - -} \ No newline at end of file + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Expected property to be comparable: xyz") + public void testValueIsNotComparable() { + new IsGreaterThanMatcher() + .matches(new ImmutableParameter("xyz", null, null, null), new Object(), new Object()); + } + + @Test + public void testValuesAreEqual() { + assertThat(new IsGreaterThanMatcher().matches(5, 5), is(false)); + } + + @Test + public void testActualIsLessThanPivot() { + assertThat(new IsGreaterThanMatcher().matches(1, 5), is(false)); + } + + @Test + public void testActualIsGreaterThanPivot() { + assertThat(new IsGreaterThanMatcher().matches(10, 5), is(true)); + } + + @Test + public void testActualIsNull() { + assertThat(new IsGreaterThanMatcher().matches(null, 5), is(false)); + } + + @Test + public void testPivotIsNull() { + assertThat(new IsGreaterThanMatcher().matches(5, null), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanOrEqualToMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanOrEqualToMatcherTest.java index 2ae88bf8..0a277821 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanOrEqualToMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsGreaterThanOrEqualToMatcherTest.java @@ -13,36 +13,36 @@ */ public class IsGreaterThanOrEqualToMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, - expectedExceptionsMessageRegExp = "Expected property to be comparable: xyz") - public void testValueIsNotComparable() { - new IsGreaterThanOrEqualToMatcher().matches(new ImmutableParameter("xyz", null, null, null), new Object(), - new Object()); - } - - @Test - public void testValuesAreEqual() { - assertThat(new IsGreaterThanOrEqualToMatcher().matches(5, 5), is(true)); - } - - @Test - public void testActualIsLessThanPivot() { - assertThat(new IsGreaterThanOrEqualToMatcher().matches(1, 5), is(false)); - } - - @Test - public void testActualIsGreaterThanPivot() { - assertThat(new IsGreaterThanOrEqualToMatcher().matches(10, 5), is(true)); - } - - @Test - public void testActualIsNull() { - assertThat(new IsGreaterThanOrEqualToMatcher().matches(null, 5), is(false)); - } - - @Test - public void testPivotIsNull() { - assertThat(new IsGreaterThanOrEqualToMatcher().matches(5, null), is(false)); - } - -} \ No newline at end of file + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Expected property to be comparable: xyz") + public void testValueIsNotComparable() { + new IsGreaterThanOrEqualToMatcher() + .matches(new ImmutableParameter("xyz", null, null, null), new Object(), new Object()); + } + + @Test + public void testValuesAreEqual() { + assertThat(new IsGreaterThanOrEqualToMatcher().matches(5, 5), is(true)); + } + + @Test + public void testActualIsLessThanPivot() { + assertThat(new IsGreaterThanOrEqualToMatcher().matches(1, 5), is(false)); + } + + @Test + public void testActualIsGreaterThanPivot() { + assertThat(new IsGreaterThanOrEqualToMatcher().matches(10, 5), is(true)); + } + + @Test + public void testActualIsNull() { + assertThat(new IsGreaterThanOrEqualToMatcher().matches(null, 5), is(false)); + } + + @Test + public void testPivotIsNull() { + assertThat(new IsGreaterThanOrEqualToMatcher().matches(5, null), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsInMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsInMatcherTest.java index 5b54e6a3..706d5745 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsInMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsInMatcherTest.java @@ -19,37 +19,33 @@ */ public class IsInMatcherTest { - @Test - public void testWhenItemIsNull() { - assertThat(new IsInMatcher().matches(null, Collections.emptyList()), is(false)); - } - - @Test - public void testWhenItemIsInCollection() { - assertThat(new IsInMatcher().matches(1, Arrays.asList(1, 2, 3, 4)), is(true)); - } - - @Test - public void testWhenItemIsNotInCollection() { - assertThat(new IsInMatcher().matches(1, Arrays.asList(3, 4, 5, 6)), is(false)); - } - - @DataProvider - public Object[][] allowedTypes() { - return new Object[][] { - { Collection.class }, - { Iterable.class }, - { Iterator.class } - }; - } - - @Test(dataProvider = "allowedTypes") - public void testAllowedParameterType(Class parameterType) { - assertTrue(new IsInMatcher().isApplicableTo(String.class, parameterType)); - } - - @Test - public void testInvalidParameterType() { - assertFalse(new IsInMatcher().isApplicableTo(String.class, String.class )); - } -} \ No newline at end of file + @Test + public void testWhenItemIsNull() { + assertThat(new IsInMatcher().matches(null, Collections.emptyList()), is(false)); + } + + @Test + public void testWhenItemIsInCollection() { + assertThat(new IsInMatcher().matches(1, Arrays.asList(1, 2, 3, 4)), is(true)); + } + + @Test + public void testWhenItemIsNotInCollection() { + assertThat(new IsInMatcher().matches(1, Arrays.asList(3, 4, 5, 6)), is(false)); + } + + @DataProvider + public Object[][] allowedTypes() { + return new Object[][] {{Collection.class}, {Iterable.class}, {Iterator.class}}; + } + + @Test(dataProvider = "allowedTypes") + public void testAllowedParameterType(Class parameterType) { + assertTrue(new IsInMatcher().isApplicableTo(String.class, parameterType)); + } + + @Test + public void testInvalidParameterType() { + assertFalse(new IsInMatcher().isApplicableTo(String.class, String.class)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanMatcherTest.java index 702dede2..72d7430c 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanMatcherTest.java @@ -13,35 +13,36 @@ */ public class IsLessThanMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, - expectedExceptionsMessageRegExp = "Expected property to be comparable: xyz") - public void testValueIsNotComparable() { - new IsLessThanMatcher().matches(new ImmutableParameter("xyz", null, null, null), new Object(), new Object()); - } - - @Test - public void testValuesAreEqual() { - assertThat(new IsLessThanMatcher().matches(5, 5), is(false)); - } - - @Test - public void testActualIsLessThanPivot() { - assertThat(new IsLessThanMatcher().matches(1, 5), is(true)); - } - - @Test - public void testActualIsGreaterThanPivot() { - assertThat(new IsLessThanMatcher().matches(10, 5), is(false)); - } - - @Test - public void testActualIsNull() { - assertThat(new IsLessThanMatcher().matches(null, 5), is(false)); - } - - @Test - public void testPivotIsNull() { - assertThat(new IsLessThanMatcher().matches(5, null), is(false)); - } - -} \ No newline at end of file + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Expected property to be comparable: xyz") + public void testValueIsNotComparable() { + new IsLessThanMatcher() + .matches(new ImmutableParameter("xyz", null, null, null), new Object(), new Object()); + } + + @Test + public void testValuesAreEqual() { + assertThat(new IsLessThanMatcher().matches(5, 5), is(false)); + } + + @Test + public void testActualIsLessThanPivot() { + assertThat(new IsLessThanMatcher().matches(1, 5), is(true)); + } + + @Test + public void testActualIsGreaterThanPivot() { + assertThat(new IsLessThanMatcher().matches(10, 5), is(false)); + } + + @Test + public void testActualIsNull() { + assertThat(new IsLessThanMatcher().matches(null, 5), is(false)); + } + + @Test + public void testPivotIsNull() { + assertThat(new IsLessThanMatcher().matches(5, null), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanOrEqualToMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanOrEqualToMatcherTest.java index 27277cac..dae53fb3 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanOrEqualToMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLessThanOrEqualToMatcherTest.java @@ -13,36 +13,36 @@ */ public class IsLessThanOrEqualToMatcherTest { - @Test(expectedExceptions = InvalidArgumentException.class, - expectedExceptionsMessageRegExp = "Expected property to be comparable: xyz") - public void testValueIsNotComparable() { - new IsLessThanOrEqualToMatcher().matches(new ImmutableParameter("xyz", null, null, null), new Object(), - new Object()); - } - - @Test - public void testValuesAreEqual() { - assertThat(new IsLessThanOrEqualToMatcher().matches(5, 5), is(true)); - } - - @Test - public void testActualIsLessThanPivot() { - assertThat(new IsLessThanOrEqualToMatcher().matches(1, 5), is(true)); - } - - @Test - public void testActualIsGreaterThanPivot() { - assertThat(new IsLessThanOrEqualToMatcher().matches(10, 5), is(false)); - } - - @Test - public void testActualIsNull() { - assertThat(new IsLessThanOrEqualToMatcher().matches(null, 5), is(false)); - } - - @Test - public void testPivotIsNull() { - assertThat(new IsLessThanOrEqualToMatcher().matches(5, null), is(false)); - } - -} \ No newline at end of file + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Expected property to be comparable: xyz") + public void testValueIsNotComparable() { + new IsLessThanOrEqualToMatcher() + .matches(new ImmutableParameter("xyz", null, null, null), new Object(), new Object()); + } + + @Test + public void testValuesAreEqual() { + assertThat(new IsLessThanOrEqualToMatcher().matches(5, 5), is(true)); + } + + @Test + public void testActualIsLessThanPivot() { + assertThat(new IsLessThanOrEqualToMatcher().matches(1, 5), is(true)); + } + + @Test + public void testActualIsGreaterThanPivot() { + assertThat(new IsLessThanOrEqualToMatcher().matches(10, 5), is(false)); + } + + @Test + public void testActualIsNull() { + assertThat(new IsLessThanOrEqualToMatcher().matches(null, 5), is(false)); + } + + @Test + public void testPivotIsNull() { + assertThat(new IsLessThanOrEqualToMatcher().matches(5, null), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLikeMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLikeMatcherTest.java index f9c26c9f..8be88fb3 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLikeMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsLikeMatcherTest.java @@ -11,23 +11,23 @@ */ public class IsLikeMatcherTest { - @Test - public void testWhenSubjectIsNull() { - assertThat(new IsLikeMatcher().matches(null, ""), is(false)); - } + @Test + public void testWhenSubjectIsNull() { + assertThat(new IsLikeMatcher().matches(null, ""), is(false)); + } - @Test - public void testWhenReferenceIsNull() { - assertThat(new IsLikeMatcher().matches("", null), is(false)); - } + @Test + public void testWhenReferenceIsNull() { + assertThat(new IsLikeMatcher().matches("", null), is(false)); + } - @Test - public void testWhenTheyAreNotAlike() { - assertThat(new IsLikeMatcher().matches("Hello World", "World"), is(false)); - } + @Test + public void testWhenTheyAreNotAlike() { + assertThat(new IsLikeMatcher().matches("Hello World", "World"), is(false)); + } - @Test - public void testWhenTheyAreAlike() { - assertThat(new IsLikeMatcher().matches("Hello world!", "hello WORLD!"), is(true)); - } -} \ No newline at end of file + @Test + public void testWhenTheyAreAlike() { + assertThat(new IsLikeMatcher().matches("Hello world!", "hello WORLD!"), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcherTest.java index 26c9b5b7..7c1d548f 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcherTest.java @@ -11,40 +11,39 @@ */ public class IsNotBetweenMatcherTest { - @Test - public void testWhenActualIsNull() { - assertThat(new IsNotBetweenMatcher().matches(null, 1, 2), is(true)); - } - - @Test - public void testWhenLowerBoundIsNull() { - assertThat(new IsNotBetweenMatcher().matches(1, null, 2), is(false)); - } - - @Test - public void testWhenUpperBoundIsNull() { - assertThat(new IsNotBetweenMatcher().matches(1, 2, null), is(false)); - } - - @Test - public void testWhenValueIsBelowRange() { - assertThat(new IsNotBetweenMatcher().matches(1, 3, 6), is(true)); - } - - @Test - public void testWhenValueIsAboveRange() { - assertThat(new IsNotBetweenMatcher().matches(9, 3, 6), is(true)); - } - - @Test - public void testWhenRangeContainsValueInclusive() { - assertThat(new IsNotBetweenMatcher().matches(3, 3, 6), is(false)); - assertThat(new IsNotBetweenMatcher().matches(6, 3, 6), is(false)); - } - - @Test - public void testWhenRangeContainsValueMidRange() { - assertThat(new IsNotBetweenMatcher().matches(4, 3, 6), is(false)); - } - -} \ No newline at end of file + @Test + public void testWhenActualIsNull() { + assertThat(new IsNotBetweenMatcher().matches(null, 1, 2), is(true)); + } + + @Test + public void testWhenLowerBoundIsNull() { + assertThat(new IsNotBetweenMatcher().matches(1, null, 2), is(false)); + } + + @Test + public void testWhenUpperBoundIsNull() { + assertThat(new IsNotBetweenMatcher().matches(1, 2, null), is(false)); + } + + @Test + public void testWhenValueIsBelowRange() { + assertThat(new IsNotBetweenMatcher().matches(1, 3, 6), is(true)); + } + + @Test + public void testWhenValueIsAboveRange() { + assertThat(new IsNotBetweenMatcher().matches(9, 3, 6), is(true)); + } + + @Test + public void testWhenRangeContainsValueInclusive() { + assertThat(new IsNotBetweenMatcher().matches(3, 3, 6), is(false)); + assertThat(new IsNotBetweenMatcher().matches(6, 3, 6), is(false)); + } + + @Test + public void testWhenRangeContainsValueMidRange() { + assertThat(new IsNotBetweenMatcher().matches(4, 3, 6), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcherTest.java index 212cb036..925f5f53 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcherTest.java @@ -14,19 +14,18 @@ */ public class IsNotInMatcherTest { - @Test - public void testWhenItemIsNull() { - assertThat(new IsNotInMatcher().matches(null, Collections.emptyList()), is(true)); - } - - @Test - public void testWhenItemIsInCollection() { - assertThat(new IsNotInMatcher().matches(1, Arrays.asList(1, 2, 3, 4)), is(false)); - } - - @Test - public void testWhenItemIsNotInCollection() { - assertThat(new IsNotInMatcher().matches(1, Arrays.asList(3, 4, 5, 6)), is(true)); - } - -} \ No newline at end of file + @Test + public void testWhenItemIsNull() { + assertThat(new IsNotInMatcher().matches(null, Collections.emptyList()), is(true)); + } + + @Test + public void testWhenItemIsInCollection() { + assertThat(new IsNotInMatcher().matches(1, Arrays.asList(1, 2, 3, 4)), is(false)); + } + + @Test + public void testWhenItemIsNotInCollection() { + assertThat(new IsNotInMatcher().matches(1, Arrays.asList(3, 4, 5, 6)), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcherTest.java index e2b115bd..8c7fa6a7 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcherTest.java @@ -11,29 +11,28 @@ */ public class IsNotLikeMatcherTest { - @Test - public void testWhenBothSubjectAndReferenceAreNull() { - assertThat(new IsNotLikeMatcher().matches(null, null), is(false)); - } - - @Test - - public void testWhenSubjectIsNullAndReferenceIsNotNull() { - assertThat(new IsNotLikeMatcher().matches(null, ""), is(true)); - } - - @Test - public void testWhenReferenceIsNullAndSubjectIsNotNull() { - assertThat(new IsNotLikeMatcher().matches("", null), is(true)); - } - - @Test - public void testWhenTheyAreNotAlike() { - assertThat(new IsNotLikeMatcher().matches("Hello World", "World"), is(true)); - } - - @Test - public void testWhenTheyAreAlike() { - assertThat(new IsNotLikeMatcher().matches("Hello world!", "hello WORLD!"), is(false)); - } -} \ No newline at end of file + @Test + public void testWhenBothSubjectAndReferenceAreNull() { + assertThat(new IsNotLikeMatcher().matches(null, null), is(false)); + } + + @Test + public void testWhenSubjectIsNullAndReferenceIsNotNull() { + assertThat(new IsNotLikeMatcher().matches(null, ""), is(true)); + } + + @Test + public void testWhenReferenceIsNullAndSubjectIsNotNull() { + assertThat(new IsNotLikeMatcher().matches("", null), is(true)); + } + + @Test + public void testWhenTheyAreNotAlike() { + assertThat(new IsNotLikeMatcher().matches("Hello World", "World"), is(true)); + } + + @Test + public void testWhenTheyAreAlike() { + assertThat(new IsNotLikeMatcher().matches("Hello world!", "hello WORLD!"), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotNullMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotNullMatcherTest.java index 3470a7fd..01d4704a 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotNullMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotNullMatcherTest.java @@ -11,14 +11,13 @@ */ public class IsNotNullMatcherTest { - @Test - public void testSubjectIsNull() { - assertThat(new IsNotNullMatcher().matches(null), is(false)); - } + @Test + public void testSubjectIsNull() { + assertThat(new IsNotNullMatcher().matches(null), is(false)); + } - @Test - public void testSubjectIsNotNull() { - assertThat(new IsNotNullMatcher().matches(new Object()), is(true)); - } - -} \ No newline at end of file + @Test + public void testSubjectIsNotNull() { + assertThat(new IsNotNullMatcher().matches(new Object()), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNullMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNullMatcherTest.java index 10e7b4b8..809fd702 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNullMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNullMatcherTest.java @@ -11,14 +11,13 @@ */ public class IsNullMatcherTest { - @Test - public void testSubjectIsNull() { - assertThat(new IsNullMatcher().matches(null), is(true)); - } + @Test + public void testSubjectIsNull() { + assertThat(new IsNullMatcher().matches(null), is(true)); + } - @Test - public void testSubjectIsNotNull() { - assertThat(new IsNullMatcher().matches(new Object()), is(false)); - } - -} \ No newline at end of file + @Test + public void testSubjectIsNotNull() { + assertThat(new IsNullMatcher().matches(new Object()), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsTrueMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsTrueMatcherTest.java index dc7fc5d8..83acb40e 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsTrueMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsTrueMatcherTest.java @@ -11,24 +11,23 @@ */ public class IsTrueMatcherTest { - @Test - public void testWhenSubjectIsNull() { - assertThat(new IsTrueMatcher().matches(null), is(false)); - } - - @Test - public void testSubjectIsNonBoolean() { - assertThat(new IsTrueMatcher().matches(""), is(false)); - } - - @Test - public void testIsFalse() { - assertThat(new IsTrueMatcher().matches(false), is(false)); - } - - @Test - public void testIsTrue() { - assertThat(new IsTrueMatcher().matches(true), is(true)); - } - -} \ No newline at end of file + @Test + public void testWhenSubjectIsNull() { + assertThat(new IsTrueMatcher().matches(null), is(false)); + } + + @Test + public void testSubjectIsNonBoolean() { + assertThat(new IsTrueMatcher().matches(""), is(false)); + } + + @Test + public void testIsFalse() { + assertThat(new IsTrueMatcher().matches(false), is(false)); + } + + @Test + public void testIsTrue() { + assertThat(new IsTrueMatcher().matches(true), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcherTest.java index e0108884..d42d46bf 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcherTest.java @@ -11,29 +11,28 @@ */ public class RegexMatcherTest { - @Test - public void testWhenActualIsNull() { - assertThat(new RegexMatcher().matches(null, ""), is(false)); - } - - @Test - public void testWhenPatternIsNull() { - assertThat(new RegexMatcher().matches("", null), is(false)); - } - - @Test - public void testWhenItemMatchesPatternPartially() { - assertThat(new RegexMatcher().matches("hello", "lo"), is(false)); - } - - @Test - public void testWhenItemDoesNotMatchPatternInAnyWay() { - assertThat(new RegexMatcher().matches("hello", "\\d+"), is(false)); - } - - @Test - public void testWhenItemMatchesPattern() { - assertThat(new RegexMatcher().matches("12345", "\\d+"), is(true)); - } - -} \ No newline at end of file + @Test + public void testWhenActualIsNull() { + assertThat(new RegexMatcher().matches(null, ""), is(false)); + } + + @Test + public void testWhenPatternIsNull() { + assertThat(new RegexMatcher().matches("", null), is(false)); + } + + @Test + public void testWhenItemMatchesPatternPartially() { + assertThat(new RegexMatcher().matches("hello", "lo"), is(false)); + } + + @Test + public void testWhenItemDoesNotMatchPatternInAnyWay() { + assertThat(new RegexMatcher().matches("hello", "\\d+"), is(false)); + } + + @Test + public void testWhenItemMatchesPattern() { + assertThat(new RegexMatcher().matches("12345", "\\d+"), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/StartingWithMatcherTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/StartingWithMatcherTest.java index b8aebad1..f41a4123 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/StartingWithMatcherTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/StartingWithMatcherTest.java @@ -11,29 +11,28 @@ */ public class StartingWithMatcherTest { - @Test - public void testWhenActualIsNull() { - assertThat(new StartingWithMatcher().matches(null, ""), is(false)); - } - - @Test - public void testWhenParameterIsNull() { - assertThat(new StartingWithMatcher().matches("", null), is(false)); - } - - @Test - public void testWhenBothAreNull() { - assertThat(new StartingWithMatcher().matches(null, null), is(false)); - } - - @Test - public void testWhenActualDoesNotStartWithParameter() { - assertThat(new StartingWithMatcher().matches("xyz", "abc"), is(false)); - } - - @Test - public void testWhenActualStartsWithParameter() { - assertThat(new StartingWithMatcher().matches("HelloWorld", "HELLO"), is(true)); - } - -} \ No newline at end of file + @Test + public void testWhenActualIsNull() { + assertThat(new StartingWithMatcher().matches(null, ""), is(false)); + } + + @Test + public void testWhenParameterIsNull() { + assertThat(new StartingWithMatcher().matches("", null), is(false)); + } + + @Test + public void testWhenBothAreNull() { + assertThat(new StartingWithMatcher().matches(null, null), is(false)); + } + + @Test + public void testWhenActualDoesNotStartWithParameter() { + assertThat(new StartingWithMatcher().matches("xyz", "abc"), is(false)); + } + + @Test + public void testWhenActualStartsWithParameter() { + assertThat(new StartingWithMatcher().matches("HelloWorld", "HELLO"), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilderTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilderTest.java index 2849cb1e..173e4886 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilderTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilderTest.java @@ -20,8 +20,17 @@ import com.mmnaseri.utils.spring.data.sample.mocks.SpyingDataFunction; import com.mmnaseri.utils.spring.data.sample.mocks.SpyingHandler; import com.mmnaseri.utils.spring.data.sample.models.Person; -import com.mmnaseri.utils.spring.data.sample.repositories.*; -import com.mmnaseri.utils.spring.data.store.*; +import com.mmnaseri.utils.spring.data.sample.repositories.ConfiguredMapping; +import com.mmnaseri.utils.spring.data.sample.repositories.ConfiguredSimplePersonRepository; +import com.mmnaseri.utils.spring.data.sample.repositories.ExtendedSimplePersonRepository; +import com.mmnaseri.utils.spring.data.sample.repositories.JpaPersonRepository; +import com.mmnaseri.utils.spring.data.sample.repositories.NumberMapping; +import com.mmnaseri.utils.spring.data.sample.repositories.SimplePersonRepository; +import com.mmnaseri.utils.spring.data.sample.repositories.StringMapping; +import com.mmnaseri.utils.spring.data.store.DataStore; +import com.mmnaseri.utils.spring.data.store.DataStoreEvent; +import com.mmnaseri.utils.spring.data.store.DataStoreEventListener; +import com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext; import com.mmnaseri.utils.spring.data.store.impl.AuditDataEventListener; import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreEventListenerContext; import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreRegistry; @@ -35,7 +44,12 @@ import static com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilder.given; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -43,340 +57,407 @@ */ public class RepositoryFactoryBuilderTest { - @Test - public void testDefaultConfiguration() { - final RepositoryFactoryConfiguration configuration = RepositoryFactoryBuilder.defaultConfiguration(); - assertThat(configuration, is(notNullValue())); - assertThat(configuration.getDataStoreRegistry(), is(notNullValue())); - assertThat(configuration.getTypeMappingContext(), is(notNullValue())); - assertThat(configuration.getResultAdapterContext(), is(notNullValue())); - assertThat(configuration.getRepositoryMetadataResolver(), is(notNullValue())); - assertThat(configuration.getOperationInvocationHandler(), is(notNullValue())); - assertThat(configuration.getFunctionRegistry(), is(notNullValue())); - assertThat(configuration.getEventListenerContext(), is(notNullValue())); - assertThat(configuration.getDescriptionExtractor(), is(notNullValue())); - } - - @Test - public void testDefaultFactory() { - final RepositoryFactory factory = RepositoryFactoryBuilder.defaultFactory(); - assertThat(factory, is(notNullValue())); - } - - @Test - public void testConfiguringAProvidedConfiguration() { - final DefaultRepositoryFactoryConfiguration configuration = new DefaultRepositoryFactoryConfiguration(); - final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry(); - configuration.setFunctionRegistry(functionRegistry); - configuration.setDefaultKeyGenerator(new NoOpKeyGenerator<>()); - final UUIDKeyGenerator keyGenerator = new UUIDKeyGenerator(); - final RepositoryFactoryConfiguration modifiedConfiguration = given(configuration).withDefaultKeyGenerator( - keyGenerator).withListener(new AllCatchingEventListener()).configure(); - assertThat(modifiedConfiguration, is(notNullValue())); - assertThat(modifiedConfiguration.getDefaultKeyGenerator(), is((Object) keyGenerator)); - assertThat(modifiedConfiguration.getEventListenerContext(), is(notNullValue())); - assertThat(modifiedConfiguration.getEventListenerContext().getListeners(DataStoreEvent.class), hasSize(1)); - } - - @Test - public void testUsingCustomMetadataResolver() { - final DefaultRepositoryMetadataResolver resolver = new DefaultRepositoryMetadataResolver(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().resolveMetadataUsing(resolver).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getRepositoryMetadataResolver(), is(notNullValue())); - assertThat(factory.getConfiguration().getRepositoryMetadataResolver(), - Matchers.is(resolver)); - } - - @Test - public void testUsingCustomQueryDescriptor() { - final MethodQueryDescriptionExtractor queryDescriptionExtractor = new MethodQueryDescriptionExtractor( - new DefaultOperatorContext()); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().extractQueriesUsing( - queryDescriptionExtractor).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor(), is(queryDescriptionExtractor)); - } - - @Test - public void testSpecifyingDefaultKeyGenerator() { - final UUIDKeyGenerator generator = new UUIDKeyGenerator(); - final RepositoryFactoryConfiguration configuration = RepositoryFactoryBuilder.builder().withDefaultKeyGenerator( - generator).configure(); - assertThat(configuration.getDefaultKeyGenerator(), is(notNullValue())); - assertThat(configuration.getDefaultKeyGenerator(), is((Object) generator)); - } - - @Test - public void testUsingCustomOperatorContext() { - final DefaultOperatorContext operatorContext = new DefaultOperatorContext(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withOperators(operatorContext).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor().getOperatorContext(), is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor().getOperatorContext(), - Matchers.is(operatorContext)); - } - - @Test - public void testUsingDefaultOperatorContextWithAdditionalOperators() { - final ImmutableOperator x = new ImmutableOperator("x", 0, null, "X"); - final ImmutableOperator y = new ImmutableOperator("y", 0, null, "Y"); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().registerOperator(x).and(y).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor().getOperatorContext(), is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("X"), - is(notNullValue())); - assertThat(factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("X"), - Matchers.is(x)); - assertThat(factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("Y"), - is(notNullValue(Operator.class))); - assertThat(factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("Y"), - Matchers.is(y)); - } - - @Test - public void testUsingCustomFunctionRegistry() { - final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withDataFunctions(functionRegistry) - .build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue())); - assertThat(factory.getConfiguration().getFunctionRegistry(), - Matchers.is(functionRegistry)); - } - - @Test - public void testUsingDefaultFunctionRegistryWithExtraFunctions() { - final SpyingDataFunction x = new SpyingDataFunction<>(null); - final SpyingDataFunction y = new SpyingDataFunction<>(null); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().registerFunction("x", x).and("y", y) - .build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue())); - assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue())); - assertThat(factory.getConfiguration().getFunctionRegistry().getFunction("x"), is(notNullValue())); - assertThat(factory.getConfiguration().getFunctionRegistry().getFunction("x"), Matchers.is(x)); - assertThat(factory.getConfiguration().getFunctionRegistry().getFunction("y"), is(notNullValue())); - assertThat(factory.getConfiguration().getFunctionRegistry().getFunction("y"), Matchers.is(y)); - } - - @Test - public void testUsingCustomDataStoreRegistry() { - final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withDataStores(registry).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getDataStoreRegistry(), is(notNullValue())); - assertThat(factory.getConfiguration().getDataStoreRegistry(), Matchers.is(registry)); - } - - @Test - public void testUsingDefaultDataStoreRegistryAndCustomDataStores() { - final MemoryDataStore x = new MemoryDataStore<>(Integer.class); - final MemoryDataStore y = new MemoryDataStore<>(String.class); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().registerDataStore(x).and(y).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getDataStoreRegistry(), is(notNullValue())); - assertThat(factory.getConfiguration().getDataStoreRegistry().getDataStore(Integer.class), is(notNullValue())); - assertThat(factory.getConfiguration().getDataStoreRegistry().getDataStore(Integer.class), - Matchers.is(x)); - assertThat(factory.getConfiguration().getDataStoreRegistry().getDataStore(String.class), is(notNullValue())); - assertThat(factory.getConfiguration().getDataStoreRegistry().getDataStore(String.class), - Matchers.is(y)); - } - - @Test - public void testUsingCustomResultAdapterContext() { - final DefaultResultAdapterContext context = new DefaultResultAdapterContext(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withAdapters(context).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getResultAdapterContext(), is(notNullValue())); - assertThat(factory.getConfiguration().getResultAdapterContext(), Matchers.is(context)); - } - - @Test - public void testUsingDefaultContextWithCustomAdapters() { - final VoidResultAdapter x = new VoidResultAdapter(); - final VoidResultAdapter y = new VoidResultAdapter(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().adaptResultsUsing(x).and(y).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getResultAdapterContext(), is(notNullValue())); - assertThat(factory.getConfiguration().getResultAdapterContext().getAdapters(), hasItem(x)); - assertThat(factory.getConfiguration().getResultAdapterContext().getAdapters(), hasItem(y)); - } - - @Test - public void testUsingCustomTypeMappingContext() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withMappings(context).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getTypeMappingContext(), is(notNullValue())); - assertThat(factory.getConfiguration().getTypeMappingContext(), Matchers.is(context)); - } - - @Test - public void testUsingDefaultTypeMappingContextAndCustomTypeMappings() { - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().honoringImplementation(Object.class, - Integer.class).and( - Object.class, String.class).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getTypeMappingContext(), is(notNullValue())); - assertThat(factory.getConfiguration().getTypeMappingContext().getImplementations(Object.class), - hasItem(Integer.class)); - assertThat(factory.getConfiguration().getTypeMappingContext().getImplementations(Object.class), - hasItem(String.class)); - } - - @Test - public void testUsingCustomOperationHandler() { - final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withOperationHandlers(handler).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(notNullValue())); - assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(handler)); - } - - @Test - public void testUsingDefaultOperationHandlerWithCustomOperations() { - final SpyingHandler x = new SpyingHandler(); - final SpyingHandler y = new SpyingHandler(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withOperationHandler(x).and(y).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(notNullValue())); - assertThat(factory.getConfiguration().getOperationInvocationHandler().getHandlers(), hasItem(x)); - assertThat(factory.getConfiguration().getOperationInvocationHandler().getHandlers(), hasItem(y)); - } - - @Test - public void testUsingCustomEventListenerContext() { - final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withListeners(context).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getEventListenerContext(), is(notNullValue())); - assertThat(factory.getConfiguration().getEventListenerContext(), - Matchers.is(context)); - } - - @Test - public void testUsingDefaultEventListenerContextWithCustomListeners() { - final AllCatchingEventListener x = new AllCatchingEventListener(); - final AllCatchingEventListener y = new AllCatchingEventListener(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().withListener(x).and(y).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - assertThat(factory.getConfiguration().getEventListenerContext(), is(notNullValue())); - assertThat(factory.getConfiguration().getEventListenerContext().getListeners(DataStoreEvent.class), hasItem(x)); - assertThat(factory.getConfiguration().getEventListenerContext().getListeners(DataStoreEvent.class), hasItem(y)); - } - - @Test - public void testEnablingAuditing() { - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().enableAuditing().build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - final DataStoreEventListenerContext listenerContext = factory.getConfiguration().getEventListenerContext(); - assertThat(listenerContext, is(notNullValue())); - final List> listeners = listenerContext.getListeners( - DataStoreEvent.class); - assertThat(listeners, hasSize(1)); - assertThat(listeners.get(0), is(instanceOf(AuditDataEventListener.class))); - } - - @Test - public void testEnablingAuditingWithCustomAuditorAware() { - final AuditorAware auditorAware = new RepositoryFactoryBuilder.DefaultAuditorAware(); - final RepositoryFactory factory = RepositoryFactoryBuilder.builder().enableAuditing(auditorAware).build(); - assertThat(factory, is(notNullValue())); - assertThat(factory.getConfiguration(), is(notNullValue())); - final DataStoreEventListenerContext listenerContext = factory.getConfiguration().getEventListenerContext(); - assertThat(listenerContext, is(notNullValue())); - final List> listeners = listenerContext.getListeners( - DataStoreEvent.class); - assertThat(listeners, hasSize(1)); - assertThat(listeners.get(0), is(instanceOf(AuditDataEventListener.class))); - final AuditDataEventListener auditDataEventListener = (AuditDataEventListener) listeners.get(0); - final AuditorAware usedAuditorAware = auditDataEventListener.getAuditorAware(); - assertThat(usedAuditorAware, is(notNullValue())); - assertThat(usedAuditorAware, is(auditorAware)); - } - - @Test - public void testDefaultAuditorAware() { - final AuditorAware auditorAware = new RepositoryFactoryBuilder.DefaultAuditorAware(); - assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true)); - assertThat(auditorAware.getCurrentAuditor().get(), is(RepositoryFactoryBuilder.DEFAULT_USER)); - } - - @Test - public void testOutOfTheBoxMocking() { - final SimplePersonRepository repository = RepositoryFactoryBuilder.builder().mock(SimplePersonRepository.class); - assertThat(repository, is(notNullValue())); - } - - @Test - public void testMockingUsingCustomImplementation() { - final ExtendedSimplePersonRepository repository = RepositoryFactoryBuilder.builder().usingImplementation( - StringMapping.class).and(NumberMapping.class).mock(ExtendedSimplePersonRepository.class); - assertThat(repository, is(notNullValue())); - assertThat(repository.getString(), is("Hello!")); - assertThat(repository.getNumber(), Matchers.is(123)); - } - - @Test - public void testMockingWithoutGeneratingKeys() { - final ConfiguredSimplePersonRepository repository = - RepositoryFactoryBuilder.builder().withoutGeneratingKeys().usingImplementation(ConfiguredMapping.class) - .mock(ConfiguredSimplePersonRepository.class); - assertThat(repository.getRepositoryConfiguration(), is(notNullValue())); - assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue())); - assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(instanceOf(NoOpKeyGenerator.class))); - } - - @Test - public void testMockingWithCustomKeyGeneration() { - final NoOpKeyGenerator keyGenerator = new NoOpKeyGenerator<>(); - final ConfiguredSimplePersonRepository repository = RepositoryFactoryBuilder.builder().generateKeysUsing( - keyGenerator).usingImplementation(ConfiguredMapping.class).mock(ConfiguredSimplePersonRepository.class); - assertThat(repository.getRepositoryConfiguration(), is(notNullValue())); - assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue())); - assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), - Matchers.is(keyGenerator)); - } - - @Test - public void testMockingWithCustomKeyGenerationByType() { - //noinspection unchecked - final ConfiguredSimplePersonRepository repository = RepositoryFactoryBuilder.builder().generateKeysUsing( - NoOpKeyGenerator.class).usingImplementation(ConfiguredMapping.class).mock( - ConfiguredSimplePersonRepository.class); - assertThat(repository.getRepositoryConfiguration(), is(notNullValue())); - assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue())); - assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(instanceOf(NoOpKeyGenerator.class))); - } - - @Test - public void testSaveIterable() { - final JpaPersonRepository repository = RepositoryFactoryBuilder.builder().mock(JpaPersonRepository.class); - final Iterable iterable = Arrays.asList(new Person().setId("1"), new Person().setId("2"), new Person().setId("3")); - repository.saveAll(iterable); - assertThat(repository.findAll(), hasSize(3)); - assertThat(repository.findAll(), containsInAnyOrder(((List) iterable).toArray())); - } -} \ No newline at end of file + @Test + public void testDefaultConfiguration() { + final RepositoryFactoryConfiguration configuration = + RepositoryFactoryBuilder.defaultConfiguration(); + assertThat(configuration, is(notNullValue())); + assertThat(configuration.getDataStoreRegistry(), is(notNullValue())); + assertThat(configuration.getTypeMappingContext(), is(notNullValue())); + assertThat(configuration.getResultAdapterContext(), is(notNullValue())); + assertThat(configuration.getRepositoryMetadataResolver(), is(notNullValue())); + assertThat(configuration.getOperationInvocationHandler(), is(notNullValue())); + assertThat(configuration.getFunctionRegistry(), is(notNullValue())); + assertThat(configuration.getEventListenerContext(), is(notNullValue())); + assertThat(configuration.getDescriptionExtractor(), is(notNullValue())); + } + + @Test + public void testDefaultFactory() { + final RepositoryFactory factory = RepositoryFactoryBuilder.defaultFactory(); + assertThat(factory, is(notNullValue())); + } + + @Test + public void testConfiguringAProvidedConfiguration() { + final DefaultRepositoryFactoryConfiguration configuration = + new DefaultRepositoryFactoryConfiguration(); + final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry(); + configuration.setFunctionRegistry(functionRegistry); + configuration.setDefaultKeyGenerator(new NoOpKeyGenerator<>()); + final UUIDKeyGenerator keyGenerator = new UUIDKeyGenerator(); + final RepositoryFactoryConfiguration modifiedConfiguration = + given(configuration) + .withDefaultKeyGenerator(keyGenerator) + .withListener(new AllCatchingEventListener()) + .configure(); + assertThat(modifiedConfiguration, is(notNullValue())); + assertThat(modifiedConfiguration.getDefaultKeyGenerator(), is((Object) keyGenerator)); + assertThat(modifiedConfiguration.getEventListenerContext(), is(notNullValue())); + assertThat( + modifiedConfiguration.getEventListenerContext().getListeners(DataStoreEvent.class), + hasSize(1)); + } + + @Test + public void testUsingCustomMetadataResolver() { + final DefaultRepositoryMetadataResolver resolver = new DefaultRepositoryMetadataResolver(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().resolveMetadataUsing(resolver).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getRepositoryMetadataResolver(), is(notNullValue())); + assertThat(factory.getConfiguration().getRepositoryMetadataResolver(), Matchers.is(resolver)); + } + + @Test + public void testUsingCustomQueryDescriptor() { + final MethodQueryDescriptionExtractor queryDescriptionExtractor = + new MethodQueryDescriptionExtractor(new DefaultOperatorContext()); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().extractQueriesUsing(queryDescriptionExtractor).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue())); + assertThat(factory.getConfiguration().getDescriptionExtractor(), is(queryDescriptionExtractor)); + } + + @Test + public void testSpecifyingDefaultKeyGenerator() { + final UUIDKeyGenerator generator = new UUIDKeyGenerator(); + final RepositoryFactoryConfiguration configuration = + RepositoryFactoryBuilder.builder().withDefaultKeyGenerator(generator).configure(); + assertThat(configuration.getDefaultKeyGenerator(), is(notNullValue())); + assertThat(configuration.getDefaultKeyGenerator(), is((Object) generator)); + } + + @Test + public void testUsingCustomOperatorContext() { + final DefaultOperatorContext operatorContext = new DefaultOperatorContext(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withOperators(operatorContext).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue())); + assertThat( + factory.getConfiguration().getDescriptionExtractor().getOperatorContext(), + is(notNullValue())); + assertThat( + factory.getConfiguration().getDescriptionExtractor().getOperatorContext(), + Matchers.is(operatorContext)); + } + + @Test + public void testUsingDefaultOperatorContextWithAdditionalOperators() { + final ImmutableOperator x = new ImmutableOperator("x", 0, null, "X"); + final ImmutableOperator y = new ImmutableOperator("y", 0, null, "Y"); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().registerOperator(x).and(y).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue())); + assertThat( + factory.getConfiguration().getDescriptionExtractor().getOperatorContext(), + is(notNullValue())); + assertThat( + factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("X"), + is(notNullValue())); + assertThat( + factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("X"), + Matchers.is(x)); + assertThat( + factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("Y"), + is(notNullValue(Operator.class))); + assertThat( + factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("Y"), + Matchers.is(y)); + } + + @Test + public void testUsingCustomFunctionRegistry() { + final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withDataFunctions(functionRegistry).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue())); + assertThat(factory.getConfiguration().getFunctionRegistry(), Matchers.is(functionRegistry)); + } + + @Test + public void testUsingDefaultFunctionRegistryWithExtraFunctions() { + final SpyingDataFunction x = new SpyingDataFunction<>(null); + final SpyingDataFunction y = new SpyingDataFunction<>(null); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().registerFunction("x", x).and("y", y).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue())); + assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue())); + assertThat( + factory.getConfiguration().getFunctionRegistry().getFunction("x"), is(notNullValue())); + assertThat( + factory.getConfiguration().getFunctionRegistry().getFunction("x"), + Matchers.is(x)); + assertThat( + factory.getConfiguration().getFunctionRegistry().getFunction("y"), is(notNullValue())); + assertThat( + factory.getConfiguration().getFunctionRegistry().getFunction("y"), + Matchers.is(y)); + } + + @Test + public void testUsingCustomDataStoreRegistry() { + final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withDataStores(registry).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getDataStoreRegistry(), is(notNullValue())); + assertThat(factory.getConfiguration().getDataStoreRegistry(), Matchers.is(registry)); + } + + @Test + public void testUsingDefaultDataStoreRegistryAndCustomDataStores() { + final MemoryDataStore x = new MemoryDataStore<>(Integer.class); + final MemoryDataStore y = new MemoryDataStore<>(String.class); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().registerDataStore(x).and(y).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getDataStoreRegistry(), is(notNullValue())); + assertThat( + factory.getConfiguration().getDataStoreRegistry().getDataStore(Integer.class), + is(notNullValue())); + assertThat( + factory.getConfiguration().getDataStoreRegistry().getDataStore(Integer.class), + Matchers.is(x)); + assertThat( + factory.getConfiguration().getDataStoreRegistry().getDataStore(String.class), + is(notNullValue())); + assertThat( + factory.getConfiguration().getDataStoreRegistry().getDataStore(String.class), + Matchers.is(y)); + } + + @Test + public void testUsingCustomResultAdapterContext() { + final DefaultResultAdapterContext context = new DefaultResultAdapterContext(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withAdapters(context).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getResultAdapterContext(), is(notNullValue())); + assertThat(factory.getConfiguration().getResultAdapterContext(), Matchers.is(context)); + } + + @Test + public void testUsingDefaultContextWithCustomAdapters() { + final VoidResultAdapter x = new VoidResultAdapter(); + final VoidResultAdapter y = new VoidResultAdapter(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().adaptResultsUsing(x).and(y).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getResultAdapterContext(), is(notNullValue())); + assertThat(factory.getConfiguration().getResultAdapterContext().getAdapters(), hasItem(x)); + assertThat(factory.getConfiguration().getResultAdapterContext().getAdapters(), hasItem(y)); + } + + @Test + public void testUsingCustomTypeMappingContext() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withMappings(context).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getTypeMappingContext(), is(notNullValue())); + assertThat(factory.getConfiguration().getTypeMappingContext(), Matchers.is(context)); + } + + @Test + public void testUsingDefaultTypeMappingContextAndCustomTypeMappings() { + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder() + .honoringImplementation(Object.class, Integer.class) + .and(Object.class, String.class) + .build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getTypeMappingContext(), is(notNullValue())); + assertThat( + factory.getConfiguration().getTypeMappingContext().getImplementations(Object.class), + hasItem(Integer.class)); + assertThat( + factory.getConfiguration().getTypeMappingContext().getImplementations(Object.class), + hasItem(String.class)); + } + + @Test + public void testUsingCustomOperationHandler() { + final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withOperationHandlers(handler).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(notNullValue())); + assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(handler)); + } + + @Test + public void testUsingDefaultOperationHandlerWithCustomOperations() { + final SpyingHandler x = new SpyingHandler(); + final SpyingHandler y = new SpyingHandler(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withOperationHandler(x).and(y).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(notNullValue())); + assertThat( + factory.getConfiguration().getOperationInvocationHandler().getHandlers(), hasItem(x)); + assertThat( + factory.getConfiguration().getOperationInvocationHandler().getHandlers(), hasItem(y)); + } + + @Test + public void testUsingCustomEventListenerContext() { + final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withListeners(context).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getEventListenerContext(), is(notNullValue())); + assertThat(factory.getConfiguration().getEventListenerContext(), Matchers.is(context)); + } + + @Test + public void testUsingDefaultEventListenerContextWithCustomListeners() { + final AllCatchingEventListener x = new AllCatchingEventListener(); + final AllCatchingEventListener y = new AllCatchingEventListener(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().withListener(x).and(y).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + assertThat(factory.getConfiguration().getEventListenerContext(), is(notNullValue())); + assertThat( + factory.getConfiguration().getEventListenerContext().getListeners(DataStoreEvent.class), + hasItem(x)); + assertThat( + factory.getConfiguration().getEventListenerContext().getListeners(DataStoreEvent.class), + hasItem(y)); + } + + @Test + public void testEnablingAuditing() { + final RepositoryFactory factory = RepositoryFactoryBuilder.builder().enableAuditing().build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + final DataStoreEventListenerContext listenerContext = + factory.getConfiguration().getEventListenerContext(); + assertThat(listenerContext, is(notNullValue())); + final List> listeners = + listenerContext.getListeners(DataStoreEvent.class); + assertThat(listeners, hasSize(1)); + assertThat(listeners.get(0), is(instanceOf(AuditDataEventListener.class))); + } + + @Test + public void testEnablingAuditingWithCustomAuditorAware() { + final AuditorAware auditorAware = new RepositoryFactoryBuilder.DefaultAuditorAware(); + final RepositoryFactory factory = + RepositoryFactoryBuilder.builder().enableAuditing(auditorAware).build(); + assertThat(factory, is(notNullValue())); + assertThat(factory.getConfiguration(), is(notNullValue())); + final DataStoreEventListenerContext listenerContext = + factory.getConfiguration().getEventListenerContext(); + assertThat(listenerContext, is(notNullValue())); + final List> listeners = + listenerContext.getListeners(DataStoreEvent.class); + assertThat(listeners, hasSize(1)); + assertThat(listeners.get(0), is(instanceOf(AuditDataEventListener.class))); + final AuditDataEventListener auditDataEventListener = (AuditDataEventListener) listeners.get(0); + final AuditorAware usedAuditorAware = auditDataEventListener.getAuditorAware(); + assertThat(usedAuditorAware, is(notNullValue())); + assertThat(usedAuditorAware, is(auditorAware)); + } + + @Test + public void testDefaultAuditorAware() { + final AuditorAware auditorAware = new RepositoryFactoryBuilder.DefaultAuditorAware(); + assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true)); + assertThat(auditorAware.getCurrentAuditor().get(), is(RepositoryFactoryBuilder.DEFAULT_USER)); + } + + @Test + public void testOutOfTheBoxMocking() { + final SimplePersonRepository repository = + RepositoryFactoryBuilder.builder().mock(SimplePersonRepository.class); + assertThat(repository, is(notNullValue())); + } + + @Test + public void testMockingUsingCustomImplementation() { + final ExtendedSimplePersonRepository repository = + RepositoryFactoryBuilder.builder() + .usingImplementation(StringMapping.class) + .and(NumberMapping.class) + .mock(ExtendedSimplePersonRepository.class); + assertThat(repository, is(notNullValue())); + assertThat(repository.getString(), is("Hello!")); + assertThat(repository.getNumber(), Matchers.is(123)); + } + + @Test + public void testMockingWithoutGeneratingKeys() { + final ConfiguredSimplePersonRepository repository = + RepositoryFactoryBuilder.builder() + .withoutGeneratingKeys() + .usingImplementation(ConfiguredMapping.class) + .mock(ConfiguredSimplePersonRepository.class); + assertThat(repository.getRepositoryConfiguration(), is(notNullValue())); + assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue())); + assertThat( + repository.getRepositoryConfiguration().getKeyGenerator(), + is(instanceOf(NoOpKeyGenerator.class))); + } + + @Test + public void testMockingWithCustomKeyGeneration() { + final NoOpKeyGenerator keyGenerator = new NoOpKeyGenerator<>(); + final ConfiguredSimplePersonRepository repository = + RepositoryFactoryBuilder.builder() + .generateKeysUsing(keyGenerator) + .usingImplementation(ConfiguredMapping.class) + .mock(ConfiguredSimplePersonRepository.class); + assertThat(repository.getRepositoryConfiguration(), is(notNullValue())); + assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue())); + assertThat( + repository.getRepositoryConfiguration().getKeyGenerator(), Matchers.is(keyGenerator)); + } + + @Test + public void testMockingWithCustomKeyGenerationByType() { + //noinspection unchecked + final ConfiguredSimplePersonRepository repository = + RepositoryFactoryBuilder.builder() + .generateKeysUsing(NoOpKeyGenerator.class) + .usingImplementation(ConfiguredMapping.class) + .mock(ConfiguredSimplePersonRepository.class); + assertThat(repository.getRepositoryConfiguration(), is(notNullValue())); + assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue())); + assertThat( + repository.getRepositoryConfiguration().getKeyGenerator(), + is(instanceOf(NoOpKeyGenerator.class))); + } + + @Test + public void testSaveIterable() { + final JpaPersonRepository repository = + RepositoryFactoryBuilder.builder().mock(JpaPersonRepository.class); + final Iterable iterable = + Arrays.asList(new Person().setId("1"), new Person().setId("2"), new Person().setId("3")); + repository.saveAll(iterable); + assertThat(repository.findAll(), hasSize(3)); + assertThat(repository.findAll(), containsInAnyOrder(((List) iterable).toArray())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilderTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilderTest.java index e2cce18a..031ae195 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilderTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilderTest.java @@ -29,7 +29,13 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -38,224 +44,254 @@ @SuppressWarnings("unused") public class RepositoryMockBuilderTest { - @Test - public void testOutOfTheBoxMocking() { - final SimpleCrudPersonRepository repository = new RepositoryMockBuilder().useConfiguration( - RepositoryFactoryBuilder.defaultConfiguration()).mock(SimpleCrudPersonRepository.class); - assertThat(repository, is(notNullValue())); - final Person person = repository.save(new Person()); - assertThat(repository.findAll(), is(notNullValue())); - assertThat(repository.findAll(), hasSize(1)); - assertThat(repository.findAll(), hasItem(person)); - repository.delete(person); - assertThat(repository.findAll(), is(empty())); + @Test + public void testOutOfTheBoxMocking() { + final SimpleCrudPersonRepository repository = + new RepositoryMockBuilder() + .useConfiguration(RepositoryFactoryBuilder.defaultConfiguration()) + .mock(SimpleCrudPersonRepository.class); + assertThat(repository, is(notNullValue())); + final Person person = repository.save(new Person()); + assertThat(repository.findAll(), is(notNullValue())); + assertThat(repository.findAll(), hasSize(1)); + assertThat(repository.findAll(), hasItem(person)); + repository.delete(person); + assertThat(repository.findAll(), is(empty())); + } + + @Test + public void testMockingWithoutKeyGeneration() { + final SimpleCrudPersonRepository repository = + new RepositoryMockBuilder().withoutGeneratingKeys().mock(SimpleCrudPersonRepository.class); + assertThat(repository, is(notNullValue())); + boolean exceptionThrown = false; + try { + repository.save(new Person()); + } catch (Exception e) { + assertThat(e, is(instanceOf(DataOperationExecutionException.class))); + assertThat(e.getCause(), is(notNullValue())); + assertThat(e.getCause(), is(instanceOf(CorruptDataException.class))); + exceptionThrown = true; } - - @Test - public void testMockingWithoutKeyGeneration() { - final SimpleCrudPersonRepository repository = new RepositoryMockBuilder().withoutGeneratingKeys().mock( - SimpleCrudPersonRepository.class); - assertThat(repository, is(notNullValue())); - boolean exceptionThrown = false; - try { - repository.save(new Person()); - } catch (Exception e) { - assertThat(e, is(instanceOf(DataOperationExecutionException.class))); - assertThat(e.getCause(), is(notNullValue())); - assertThat(e.getCause(), is(instanceOf(CorruptDataException.class))); - exceptionThrown = true; - } - assertThat(exceptionThrown, is(true)); - final Person person = repository.save(new Person().setId("1")); - assertThat(repository.findAll(), is(notNullValue())); - assertThat(repository.findAll(), hasSize(1)); - assertThat(repository.findAll(), hasItem(person)); - repository.delete(person); - assertThat(repository.findAll(), is(empty())); - } - - @Test - public void testMockingWithFallbackKeyGenerator() { - final DefaultRepositoryFactoryConfiguration configuration = new DefaultRepositoryFactoryConfiguration( - RepositoryFactoryBuilder.defaultConfiguration()); - configuration.setDefaultKeyGenerator(new UUIDKeyGenerator()); - final SimpleCrudPersonRepository repository = new RepositoryMockBuilder().useConfiguration(configuration).mock( - SimpleCrudPersonRepository.class); - assertThat(repository, is(notNullValue())); - final Person saved = repository.save(new Person()); - assertThat(saved, is(notNullValue())); - assertThat(saved.getId(), is(notNullValue())); - } - - @Test - public void testCustomKeyGeneration() { - final SimpleCrudPersonRepository repository = new RepositoryMockBuilder().generateKeysUsing( - CustomStringKeyGenerator.class).mock(SimpleCrudPersonRepository.class); - assertThat(repository, is(notNullValue())); - final Person person = repository.save(new Person()); - assertThat(repository.findAll(), is(notNullValue())); - assertThat(repository.findAll(), hasSize(1)); - assertThat(repository.findAll(), hasItem(person)); - repository.delete(person); - assertThat(repository.findAll(), is(empty())); + assertThat(exceptionThrown, is(true)); + final Person person = repository.save(new Person().setId("1")); + assertThat(repository.findAll(), is(notNullValue())); + assertThat(repository.findAll(), hasSize(1)); + assertThat(repository.findAll(), hasItem(person)); + repository.delete(person); + assertThat(repository.findAll(), is(empty())); + } + + @Test + public void testMockingWithFallbackKeyGenerator() { + final DefaultRepositoryFactoryConfiguration configuration = + new DefaultRepositoryFactoryConfiguration(RepositoryFactoryBuilder.defaultConfiguration()); + configuration.setDefaultKeyGenerator(new UUIDKeyGenerator()); + final SimpleCrudPersonRepository repository = + new RepositoryMockBuilder() + .useConfiguration(configuration) + .mock(SimpleCrudPersonRepository.class); + assertThat(repository, is(notNullValue())); + final Person saved = repository.save(new Person()); + assertThat(saved, is(notNullValue())); + assertThat(saved.getId(), is(notNullValue())); + } + + @Test + public void testCustomKeyGeneration() { + final SimpleCrudPersonRepository repository = + new RepositoryMockBuilder() + .generateKeysUsing(CustomStringKeyGenerator.class) + .mock(SimpleCrudPersonRepository.class); + assertThat(repository, is(notNullValue())); + final Person person = repository.save(new Person()); + assertThat(repository.findAll(), is(notNullValue())); + assertThat(repository.findAll(), hasSize(1)); + assertThat(repository.findAll(), hasItem(person)); + repository.delete(person); + assertThat(repository.findAll(), is(empty())); + } + + @Test(expectedExceptions = MockBuilderException.class) + public void testUsingInvalidKeyGenerator() { + new RepositoryMockBuilder().generateKeysUsing(InaccessibleKeyGenerator.class); + } + + @Test + public void testUsingCustomImplementations() { + final MappedSimpleCrudPersonRepository repository = + new RepositoryMockBuilder() + .usingImplementation(ValueHashMapper.class) + .and(ValueStringMapper.class) + .mock(MappedSimpleCrudPersonRepository.class); + assertThat(repository, is(notNullValue())); + final Person person = repository.save(new Person()); + assertThat(repository.findAll(), is(notNullValue())); + assertThat(repository.findAll(), hasSize(1)); + assertThat(repository.findAll(), hasItem(person)); + repository.delete(person); + assertThat(repository.findAll(), is(empty())); + assertThat(repository.getHash(), is(repository.hashCode())); + assertThat(repository.getString(), is(repository.toString())); + } + + /** + * This is a slightly more sophisticated test that adds additional methods to the interface being + * mocked. + * + *

This sort of thing might come in handy if we are unsure of how to proceed with the tests, or + * if there is something we need bound to the repository specifically for the tests, however, it + * should be noted that adding functionality to your repositories for the purpose of testing is + * not really the greatest idea. + */ + @Test + public void testUsingCustomFactory() { + final DefaultRepositoryFactoryConfiguration configuration = + new DefaultRepositoryFactoryConfiguration(); + configuration.setDataStoreRegistry(new DefaultDataStoreRegistry()); + configuration.setDescriptionExtractor( + new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); + configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext()); + configuration.setFunctionRegistry(new DefaultDataFunctionRegistry()); + configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); + configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); + configuration.setResultAdapterContext(new DefaultResultAdapterContext()); + configuration.setTypeMappingContext(new DefaultTypeMappingContext()); + final SimpleCrudPersonRepository repository = + new RepositoryMockBuilder() + .useFactory(new InformationExposingRepositoryFactory(configuration)) + .mock(SimpleCrudPersonRepository.class); + assertThat(repository, is(instanceOf(InformationExposingRepository.class))); + final InformationExposingRepository informationExposingRepository = + (InformationExposingRepository) repository; + assertThat(informationExposingRepository.getFactoryConfiguration(), is(notNullValue())); + assertThat(informationExposingRepository.getFactoryConfiguration(), Matchers.is(configuration)); + assertThat(informationExposingRepository.getConfiguration(), is(notNullValue())); + assertThat( + informationExposingRepository.getConfiguration().getBoundImplementations(), + is(notNullValue())); + assertThat( + informationExposingRepository.getConfiguration().getBoundImplementations(), is(empty())); + assertThat( + informationExposingRepository.getConfiguration().getKeyGenerator(), is(notNullValue())); + assertThat( + informationExposingRepository.getConfiguration().getRepositoryMetadata(), + is(notNullValue())); + assertThat( + informationExposingRepository.getConfiguration().getRepositoryMetadata().getEntityType(), + is(Matchers.equalTo(Person.class))); + assertThat( + informationExposingRepository + .getConfiguration() + .getRepositoryMetadata() + .getIdentifierType(), + is(Matchers.equalTo(String.class))); + assertThat( + informationExposingRepository + .getConfiguration() + .getRepositoryMetadata() + .getRepositoryInterface(), + is(Matchers.equalTo(SimpleCrudPersonRepository.class))); + assertThat( + informationExposingRepository + .getConfiguration() + .getRepositoryMetadata() + .getIdentifierProperty(), + is("id")); + } + + @Test + public void testUsingCustomConfiguration() { + final DefaultTypeMappingContext mappingContext = new DefaultTypeMappingContext(); + mappingContext.register( + ConfiguredSimpleCrudPersonRepository.class, ConfigurationAwareMapper.class); + final DefaultRepositoryFactoryConfiguration configuration = + new DefaultRepositoryFactoryConfiguration(); + configuration.setDataStoreRegistry(new DefaultDataStoreRegistry()); + configuration.setDescriptionExtractor( + new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); + configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext()); + configuration.setFunctionRegistry(new DefaultDataFunctionRegistry()); + configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); + configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); + configuration.setResultAdapterContext(new DefaultResultAdapterContext()); + configuration.setTypeMappingContext(mappingContext); + final ConfiguredSimpleCrudPersonRepository repository = + new RepositoryMockBuilder() + .useConfiguration(configuration) + .mock(ConfiguredSimpleCrudPersonRepository.class); + assertThat(repository.getConfiguration(), is(notNullValue())); + assertThat(repository.getConfiguration(), Matchers.is(configuration)); + } + + @Test + public void testNoOpKeyGeneration() { + final NoOpKeyGenerator generator = new NoOpKeyGenerator<>(); + assertThat(generator.generate(), is(nullValue())); + } + + public interface MappedSimpleCrudPersonRepository extends SimpleCrudPersonRepository { + + int getHash(); + + String getString(); + } + + public interface ConfiguredSimpleCrudPersonRepository extends SimpleCrudPersonRepository { + + RepositoryFactoryConfiguration getConfiguration(); + } + + public static class ValueHashMapper implements RepositoryAware { + + private MappedSimpleCrudPersonRepository repository; + + @Override + public void setRepository(MappedSimpleCrudPersonRepository repository) { + this.repository = repository; } - @Test(expectedExceptions = MockBuilderException.class) - public void testUsingInvalidKeyGenerator() { - new RepositoryMockBuilder().generateKeysUsing(InaccessibleKeyGenerator.class); + public int getHash() { + return repository.hashCode(); } + } - @Test - public void testUsingCustomImplementations() { - final MappedSimpleCrudPersonRepository repository = new RepositoryMockBuilder().usingImplementation( - ValueHashMapper.class).and(ValueStringMapper.class).mock(MappedSimpleCrudPersonRepository.class); - assertThat(repository, is(notNullValue())); - final Person person = repository.save(new Person()); - assertThat(repository.findAll(), is(notNullValue())); - assertThat(repository.findAll(), hasSize(1)); - assertThat(repository.findAll(), hasItem(person)); - repository.delete(person); - assertThat(repository.findAll(), is(empty())); - assertThat(repository.getHash(), is(repository.hashCode())); - assertThat(repository.getString(), is(repository.toString())); - } + public static class ValueStringMapper + implements RepositoryAware { - /** - * This is a slightly more sophisticated test that adds additional methods to the interface being mocked. - *

- * This sort of thing might come in handy if we are unsure of how to proceed with the tests, or if there is - * something we need bound to the repository specifically for the tests, however, it should be noted that adding - * functionality to your repositories for the purpose of testing is not really the greatest idea. - * - */ - @Test - public void testUsingCustomFactory() { - final DefaultRepositoryFactoryConfiguration configuration = new DefaultRepositoryFactoryConfiguration(); - configuration.setDataStoreRegistry(new DefaultDataStoreRegistry()); - configuration.setDescriptionExtractor(new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); - configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext()); - configuration.setFunctionRegistry(new DefaultDataFunctionRegistry()); - configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); - configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); - configuration.setResultAdapterContext(new DefaultResultAdapterContext()); - configuration.setTypeMappingContext(new DefaultTypeMappingContext()); - final SimpleCrudPersonRepository repository = new RepositoryMockBuilder().useFactory( - new InformationExposingRepositoryFactory(configuration)).mock(SimpleCrudPersonRepository.class); - assertThat(repository, is(instanceOf(InformationExposingRepository.class))); - final InformationExposingRepository informationExposingRepository = (InformationExposingRepository) repository; - assertThat(informationExposingRepository.getFactoryConfiguration(), is(notNullValue())); - assertThat(informationExposingRepository.getFactoryConfiguration(), - Matchers.is(configuration)); - assertThat(informationExposingRepository.getConfiguration(), is(notNullValue())); - assertThat(informationExposingRepository.getConfiguration().getBoundImplementations(), is(notNullValue())); - assertThat(informationExposingRepository.getConfiguration().getBoundImplementations(), is(empty())); - assertThat(informationExposingRepository.getConfiguration().getKeyGenerator(), is(notNullValue())); - assertThat(informationExposingRepository.getConfiguration().getRepositoryMetadata(), is(notNullValue())); - assertThat(informationExposingRepository.getConfiguration().getRepositoryMetadata().getEntityType(), - is(Matchers.equalTo(Person.class))); - assertThat(informationExposingRepository.getConfiguration().getRepositoryMetadata().getIdentifierType(), - is(Matchers.equalTo(String.class))); - assertThat(informationExposingRepository.getConfiguration().getRepositoryMetadata().getRepositoryInterface(), - is(Matchers.equalTo(SimpleCrudPersonRepository.class))); - assertThat(informationExposingRepository.getConfiguration().getRepositoryMetadata().getIdentifierProperty(), - is("id")); - } + private MappedSimpleCrudPersonRepository repository; - @Test - public void testUsingCustomConfiguration() { - final DefaultTypeMappingContext mappingContext = new DefaultTypeMappingContext(); - mappingContext.register(ConfiguredSimpleCrudPersonRepository.class, ConfigurationAwareMapper.class); - final DefaultRepositoryFactoryConfiguration configuration = new DefaultRepositoryFactoryConfiguration(); - configuration.setDataStoreRegistry(new DefaultDataStoreRegistry()); - configuration.setDescriptionExtractor(new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); - configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext()); - configuration.setFunctionRegistry(new DefaultDataFunctionRegistry()); - configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); - configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); - configuration.setResultAdapterContext(new DefaultResultAdapterContext()); - configuration.setTypeMappingContext(mappingContext); - final ConfiguredSimpleCrudPersonRepository repository = new RepositoryMockBuilder().useConfiguration( - configuration).mock(ConfiguredSimpleCrudPersonRepository.class); - assertThat(repository.getConfiguration(), is(notNullValue())); - assertThat(repository.getConfiguration(), Matchers.is(configuration)); + @Override + public void setRepository(MappedSimpleCrudPersonRepository repository) { + this.repository = repository; } - @Test - public void testNoOpKeyGeneration() { - final NoOpKeyGenerator generator = new NoOpKeyGenerator<>(); - assertThat(generator.generate(), is(nullValue())); + public String getString() { + return repository.toString(); } + } - public interface MappedSimpleCrudPersonRepository extends SimpleCrudPersonRepository { - - int getHash(); + public static class ConfigurationAwareMapper implements RepositoryFactoryConfigurationAware { - String getString(); + private RepositoryFactoryConfiguration configuration; + @Override + public void setRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) { + this.configuration = configuration; } - public interface ConfiguredSimpleCrudPersonRepository extends SimpleCrudPersonRepository { - - RepositoryFactoryConfiguration getConfiguration(); - + public RepositoryFactoryConfiguration getConfiguration() { + return configuration; } + } - public static class ValueHashMapper implements RepositoryAware { - - private MappedSimpleCrudPersonRepository repository; - - @Override - public void setRepository(MappedSimpleCrudPersonRepository repository) { - this.repository = repository; - } + public static class InaccessibleKeyGenerator implements KeyGenerator { - public int getHash() { - return repository.hashCode(); - } + private InaccessibleKeyGenerator() {} + @Override + public Object generate() { + return null; } - - public static class ValueStringMapper implements RepositoryAware { - - private MappedSimpleCrudPersonRepository repository; - - @Override - public void setRepository(MappedSimpleCrudPersonRepository repository) { - this.repository = repository; - } - - public String getString() { - return repository.toString(); - } - - } - - public static class ConfigurationAwareMapper implements RepositoryFactoryConfigurationAware { - - - private RepositoryFactoryConfiguration configuration; - - @Override - public void setRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) { - this.configuration = configuration; - } - - public RepositoryFactoryConfiguration getConfiguration() { - return configuration; - } - - } - - public static class InaccessibleKeyGenerator implements KeyGenerator { - - private InaccessibleKeyGenerator() { - } - - @Override - public Object generate() { - return null; - } - - } - -} \ No newline at end of file + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandlerTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandlerTest.java index 1123976f..832948d2 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandlerTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandlerTest.java @@ -18,113 +18,130 @@ import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; public class DataOperationInvocationHandlerTest { - private DataOperationInvocationHandler handler; - private List> mappings; + private DataOperationInvocationHandler handler; + private List> mappings; - @BeforeMethod - public void setUp() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, Person.class, - SimplePersonRepository.class, - "id"); - final RepositoryConfiguration repositoryConfiguration = new ImmutableRepositoryConfiguration(repositoryMetadata, - new UUIDKeyGenerator(), - Collections.emptyList()); - final MemoryDataStore dataStore = new MemoryDataStore<>(Person.class); - final DefaultResultAdapterContext adapterContext = new DefaultResultAdapterContext(); - final NonDataOperationInvocationHandler invocationHandler = new NonDataOperationInvocationHandler(); - mappings = new ArrayList<>(); - handler = new DataOperationInvocationHandler<>(repositoryConfiguration, mappings, dataStore, adapterContext, - invocationHandler); - } + @BeforeMethod + public void setUp() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, Person.class, SimplePersonRepository.class, "id"); + final RepositoryConfiguration repositoryConfiguration = + new ImmutableRepositoryConfiguration( + repositoryMetadata, new UUIDKeyGenerator(), Collections.emptyList()); + final MemoryDataStore dataStore = new MemoryDataStore<>(Person.class); + final DefaultResultAdapterContext adapterContext = new DefaultResultAdapterContext(); + final NonDataOperationInvocationHandler invocationHandler = + new NonDataOperationInvocationHandler(); + mappings = new ArrayList<>(); + handler = + new DataOperationInvocationHandler<>( + repositoryConfiguration, mappings, dataStore, adapterContext, invocationHandler); + } - /** - * Regression test to reproduce #12 - * - * @throws Throwable in case the method can't be found. - */ - @Test - public void testCallingHashCode() throws Throwable { - final Object proxy = new Object(); - final Object result = handler.invoke(proxy, Object.class.getMethod("hashCode"), new Object[]{}); - assertThat(result, is(notNullValue())); - assertThat(result, is(proxy.hashCode())); - } + /** + * Regression test to reproduce #12 + * + * @throws Throwable in case the method can't be found. + */ + @Test + public void testCallingHashCode() throws Throwable { + final Object proxy = new Object(); + final Object result = + handler.invoke(proxy, Object.class.getMethod("hashCode"), new Object[] {}); + assertThat(result, is(notNullValue())); + assertThat(result, is(proxy.hashCode())); + } - /** - * Regression test to reproduce #12 - */ - @Test - public void testCallingEqualsWhenTheyAreIdentical() throws Throwable { - final Object proxy = new Object(); - final Object result = handler.invoke(proxy, Object.class.getMethod("equals", Object.class), - new Object[]{proxy}); - assertThat(result, is(notNullValue())); - assertThat(result, is(instanceOf(Boolean.class))); - //noinspection ConstantConditions - assertThat(result, is(true)); - } + /** Regression test to reproduce #12 */ + @Test + public void testCallingEqualsWhenTheyAreIdentical() throws Throwable { + final Object proxy = new Object(); + final Object result = + handler.invoke(proxy, Object.class.getMethod("equals", Object.class), new Object[] {proxy}); + assertThat(result, is(notNullValue())); + assertThat(result, is(instanceOf(Boolean.class))); + //noinspection ConstantConditions + assertThat(result, is(true)); + } - /** - * Regression test to reproduce #12 - */ - @Test - public void testCallingEqualsWhenTheyAreNotIdentical() throws Throwable { - final Object proxy = new Object(); - final Object result = handler.invoke(proxy, Object.class.getMethod("equals", Object.class), - new Object[]{new Object()}); - assertThat(result, is(notNullValue())); - assertThat(result, is(false)); - } + /** Regression test to reproduce #12 */ + @Test + public void testCallingEqualsWhenTheyAreNotIdentical() throws Throwable { + final Object proxy = new Object(); + final Object result = + handler.invoke( + proxy, Object.class.getMethod("equals", Object.class), new Object[] {new Object()}); + assertThat(result, is(notNullValue())); + assertThat(result, is(false)); + } - /** - * Regression test to reproduce #12 - */ - @Test - public void testCallingToString() throws Throwable { - final Object proxy = new Object(); - final Object result = handler.invoke(proxy, Object.class.getMethod("toString"), new Object[]{}); - assertThat(result, is(notNullValue())); - assertThat(result, is(proxy.toString())); - } + /** Regression test to reproduce #12 */ + @Test + public void testCallingToString() throws Throwable { + final Object proxy = new Object(); + final Object result = + handler.invoke(proxy, Object.class.getMethod("toString"), new Object[] {}); + assertThat(result, is(notNullValue())); + assertThat(result, is(proxy.toString())); + } - @Test - public void testMissingMethodTwice() throws Throwable { - assertThat(handler.invoke(new Object(), Object.class.getMethod("toString"), new Object[]{}), - is(notNullValue())); - assertThat(handler.invoke(new Object(), Object.class.getMethod("toString"), new Object[]{}), - is(notNullValue())); - } + @Test + public void testMissingMethodTwice() throws Throwable { + assertThat( + handler.invoke(new Object(), Object.class.getMethod("toString"), new Object[] {}), + is(notNullValue())); + assertThat( + handler.invoke(new Object(), Object.class.getMethod("toString"), new Object[] {}), + is(notNullValue())); + } - @Test - public void testInvokingBoundMapping() throws Throwable { - final Object originalValue = new Object(); - final SpyingOperation spy = new SpyingOperation(originalValue); - mappings.add(new ImmutableInvocationMapping<>(ReturnTypeSampleRepository.class.getMethod("findOther"), spy)); - final Object[] args = {1, 2, 3}; - final Object result = handler.invoke(new Object(), ReturnTypeSampleRepository.class.getMethod("findOther"), - args); - assertThat(spy.getInvocation(), is(notNullValue())); - assertThat(spy.getInvocation().getMethod(), is(ReturnTypeSampleRepository.class.getMethod("findOther"))); - assertThat(spy.getInvocation().getArguments(), is(args)); - assertThat(result, is(originalValue)); - } - - @Test - public void testInvokingBoundMappingTwice() throws Throwable { - final Object originalValue = new Object(); - final SpyingOperation spy = new SpyingOperation(originalValue); - final SpyingOperation otherSpy = new SpyingOperation(originalValue); - mappings.add(new ImmutableInvocationMapping<>(Object.class.getMethod("hashCode"), otherSpy)); - mappings.add(new ImmutableInvocationMapping<>(ReturnTypeSampleRepository.class.getMethod("findOther"), spy)); - assertThat(handler.invoke(new Object(), ReturnTypeSampleRepository.class.getMethod("findOther"), - new Object[]{1, 2, 3}), is(originalValue)); - assertThat(handler.invoke(new Object(), ReturnTypeSampleRepository.class.getMethod("findOther"), - new Object[]{4, 5, 6}), is(originalValue)); - assertThat(otherSpy.getInvocation(), is(nullValue())); - } + @Test + public void testInvokingBoundMapping() throws Throwable { + final Object originalValue = new Object(); + final SpyingOperation spy = new SpyingOperation(originalValue); + mappings.add( + new ImmutableInvocationMapping<>( + ReturnTypeSampleRepository.class.getMethod("findOther"), spy)); + final Object[] args = {1, 2, 3}; + final Object result = + handler.invoke(new Object(), ReturnTypeSampleRepository.class.getMethod("findOther"), args); + assertThat(spy.getInvocation(), is(notNullValue())); + assertThat( + spy.getInvocation().getMethod(), + is(ReturnTypeSampleRepository.class.getMethod("findOther"))); + assertThat(spy.getInvocation().getArguments(), is(args)); + assertThat(result, is(originalValue)); + } + @Test + public void testInvokingBoundMappingTwice() throws Throwable { + final Object originalValue = new Object(); + final SpyingOperation spy = new SpyingOperation(originalValue); + final SpyingOperation otherSpy = new SpyingOperation(originalValue); + mappings.add(new ImmutableInvocationMapping<>(Object.class.getMethod("hashCode"), otherSpy)); + mappings.add( + new ImmutableInvocationMapping<>( + ReturnTypeSampleRepository.class.getMethod("findOther"), spy)); + assertThat( + handler.invoke( + new Object(), + ReturnTypeSampleRepository.class.getMethod("findOther"), + new Object[] {1, 2, 3}), + is(originalValue)); + assertThat( + handler.invoke( + new Object(), + ReturnTypeSampleRepository.class.getMethod("findOther"), + new Object[] {4, 5, 6}), + is(originalValue)); + assertThat(otherSpy.getInvocation(), is(nullValue())); + } } diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryTest.java index 2e74821c..6d2dd989 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryTest.java @@ -17,7 +17,10 @@ import java.util.Collection; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -25,90 +28,99 @@ */ public class DefaultRepositoryFactoryTest { - @Test - public void testRepositoryInstance() { - final DefaultRepositoryFactoryConfiguration configuration = new DefaultRepositoryFactoryConfiguration(); - final DefaultDataStoreRegistry dataStoreRegistry = new DefaultDataStoreRegistry(); - configuration.setDataStoreRegistry(dataStoreRegistry); - configuration.setDescriptionExtractor(new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); - configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext()); - configuration.setFunctionRegistry(new DefaultDataFunctionRegistry()); - configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); - configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); - configuration.setResultAdapterContext(new DefaultResultAdapterContext()); - configuration.setTypeMappingContext(new DefaultTypeMappingContext()); - configuration.setDefaultKeyGenerator(null); - final DefaultRepositoryFactory factory = new DefaultRepositoryFactory(configuration); - assertThat(factory.getConfiguration(), Matchers.is(configuration)); - assertThat(dataStoreRegistry.has(Person.class), is(false)); - factory.getInstance(null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class); - assertThat(dataStoreRegistry.has(Person.class), is(true)); - final ClearableSimpleCrudPersonRepository repository = factory.getInstance(null, - ClearableSimpleCrudPersonRepository.class, - RepositoryClearerMapping.class); - final DataStore dataStore = dataStoreRegistry.getDataStore(Person.class); - dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi")); - dataStore.save("k2", new Person().setId("k2").setLastName("Naseri")); - dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi")); - dataStore.save("k4", new Person().setId("k4").setLastName("Naseri")); - assertThat(repository.findAll(), containsInAnyOrder(dataStore.retrieveAll().toArray())); - assertThat(repository.findByLastName("Naseri"), - containsInAnyOrder(dataStore.retrieve("k2"), dataStore.retrieve("k4"))); - assertThat(repository.findByLastName("Sadeghi"), - containsInAnyOrder(dataStore.retrieve("k1"), dataStore.retrieve("k3"))); - assertThat(repository.findByLastName("Ghomboli"), is(empty())); - final Collection all = dataStore.retrieveAll(); - assertThat(repository.deleteAll(), containsInAnyOrder(all.toArray())); - dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi")); - dataStore.save("k2", new Person().setId("k2").setLastName("Naseri")); - dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi")); - dataStore.save("k4", new Person().setId("k4").setLastName("Naseri")); - assertThat(dataStore.retrieveAll(), hasSize(4)); - repository.clearRepo(); - assertThat(dataStore.retrieveAll(), is(empty())); - } + @Test + public void testRepositoryInstance() { + final DefaultRepositoryFactoryConfiguration configuration = + new DefaultRepositoryFactoryConfiguration(); + final DefaultDataStoreRegistry dataStoreRegistry = new DefaultDataStoreRegistry(); + configuration.setDataStoreRegistry(dataStoreRegistry); + configuration.setDescriptionExtractor( + new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); + configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext()); + configuration.setFunctionRegistry(new DefaultDataFunctionRegistry()); + configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); + configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); + configuration.setResultAdapterContext(new DefaultResultAdapterContext()); + configuration.setTypeMappingContext(new DefaultTypeMappingContext()); + configuration.setDefaultKeyGenerator(null); + final DefaultRepositoryFactory factory = new DefaultRepositoryFactory(configuration); + assertThat(factory.getConfiguration(), Matchers.is(configuration)); + assertThat(dataStoreRegistry.has(Person.class), is(false)); + factory.getInstance( + null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class); + assertThat(dataStoreRegistry.has(Person.class), is(true)); + final ClearableSimpleCrudPersonRepository repository = + factory.getInstance( + null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class); + final DataStore dataStore = dataStoreRegistry.getDataStore(Person.class); + dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi")); + dataStore.save("k2", new Person().setId("k2").setLastName("Naseri")); + dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi")); + dataStore.save("k4", new Person().setId("k4").setLastName("Naseri")); + assertThat(repository.findAll(), containsInAnyOrder(dataStore.retrieveAll().toArray())); + assertThat( + repository.findByLastName("Naseri"), + containsInAnyOrder(dataStore.retrieve("k2"), dataStore.retrieve("k4"))); + assertThat( + repository.findByLastName("Sadeghi"), + containsInAnyOrder(dataStore.retrieve("k1"), dataStore.retrieve("k3"))); + assertThat(repository.findByLastName("Ghomboli"), is(empty())); + final Collection all = dataStore.retrieveAll(); + assertThat(repository.deleteAll(), containsInAnyOrder(all.toArray())); + dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi")); + dataStore.save("k2", new Person().setId("k2").setLastName("Naseri")); + dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi")); + dataStore.save("k4", new Person().setId("k4").setLastName("Naseri")); + assertThat(dataStore.retrieveAll(), hasSize(4)); + repository.clearRepo(); + assertThat(dataStore.retrieveAll(), is(empty())); + } - @Test - public void testRepositoryInstanceWithKeyGenerationFallback() { - final DefaultRepositoryFactoryConfiguration configuration = new DefaultRepositoryFactoryConfiguration(); - final DefaultDataStoreRegistry dataStoreRegistry = new DefaultDataStoreRegistry(); - configuration.setDataStoreRegistry(dataStoreRegistry); - configuration.setDescriptionExtractor(new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); - configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext()); - configuration.setFunctionRegistry(new DefaultDataFunctionRegistry()); - configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); - configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); - configuration.setResultAdapterContext(new DefaultResultAdapterContext()); - configuration.setTypeMappingContext(new DefaultTypeMappingContext()); - configuration.setDefaultKeyGenerator(new NoOpKeyGenerator<>()); - final DefaultRepositoryFactory factory = new DefaultRepositoryFactory(configuration); - assertThat(factory.getConfiguration(), Matchers.is(configuration)); - assertThat(dataStoreRegistry.has(Person.class), is(false)); - factory.getInstance(null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class); - assertThat(dataStoreRegistry.has(Person.class), is(true)); - final ClearableSimpleCrudPersonRepository repository = factory.getInstance(null, - ClearableSimpleCrudPersonRepository.class, - RepositoryClearerMapping.class); - final DataStore dataStore = dataStoreRegistry.getDataStore(Person.class); - dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi")); - dataStore.save("k2", new Person().setId("k2").setLastName("Naseri")); - dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi")); - dataStore.save("k4", new Person().setId("k4").setLastName("Naseri")); - assertThat(repository.findAll(), containsInAnyOrder(dataStore.retrieveAll().toArray())); - assertThat(repository.findByLastName("Naseri"), - containsInAnyOrder(dataStore.retrieve("k2"), dataStore.retrieve("k4"))); - assertThat(repository.findByLastName("Sadeghi"), - containsInAnyOrder(dataStore.retrieve("k1"), dataStore.retrieve("k3"))); - assertThat(repository.findByLastName("Ghomboli"), is(empty())); - final Collection all = dataStore.retrieveAll(); - assertThat(repository.deleteAll(), containsInAnyOrder(all.toArray())); - dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi")); - dataStore.save("k2", new Person().setId("k2").setLastName("Naseri")); - dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi")); - dataStore.save("k4", new Person().setId("k4").setLastName("Naseri")); - assertThat(dataStore.retrieveAll(), hasSize(4)); - repository.clearRepo(); - assertThat(dataStore.retrieveAll(), is(empty())); - } - -} \ No newline at end of file + @Test + public void testRepositoryInstanceWithKeyGenerationFallback() { + final DefaultRepositoryFactoryConfiguration configuration = + new DefaultRepositoryFactoryConfiguration(); + final DefaultDataStoreRegistry dataStoreRegistry = new DefaultDataStoreRegistry(); + configuration.setDataStoreRegistry(dataStoreRegistry); + configuration.setDescriptionExtractor( + new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); + configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext()); + configuration.setFunctionRegistry(new DefaultDataFunctionRegistry()); + configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); + configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); + configuration.setResultAdapterContext(new DefaultResultAdapterContext()); + configuration.setTypeMappingContext(new DefaultTypeMappingContext()); + configuration.setDefaultKeyGenerator(new NoOpKeyGenerator<>()); + final DefaultRepositoryFactory factory = new DefaultRepositoryFactory(configuration); + assertThat(factory.getConfiguration(), Matchers.is(configuration)); + assertThat(dataStoreRegistry.has(Person.class), is(false)); + factory.getInstance( + null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class); + assertThat(dataStoreRegistry.has(Person.class), is(true)); + final ClearableSimpleCrudPersonRepository repository = + factory.getInstance( + null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class); + final DataStore dataStore = dataStoreRegistry.getDataStore(Person.class); + dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi")); + dataStore.save("k2", new Person().setId("k2").setLastName("Naseri")); + dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi")); + dataStore.save("k4", new Person().setId("k4").setLastName("Naseri")); + assertThat(repository.findAll(), containsInAnyOrder(dataStore.retrieveAll().toArray())); + assertThat( + repository.findByLastName("Naseri"), + containsInAnyOrder(dataStore.retrieve("k2"), dataStore.retrieve("k4"))); + assertThat( + repository.findByLastName("Sadeghi"), + containsInAnyOrder(dataStore.retrieve("k1"), dataStore.retrieve("k3"))); + assertThat(repository.findByLastName("Ghomboli"), is(empty())); + final Collection all = dataStore.retrieveAll(); + assertThat(repository.deleteAll(), containsInAnyOrder(all.toArray())); + dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi")); + dataStore.save("k2", new Person().setId("k2").setLastName("Naseri")); + dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi")); + dataStore.save("k4", new Person().setId("k4").setLastName("Naseri")); + assertThat(dataStore.retrieveAll(), hasSize(4)); + repository.clearRepo(); + assertThat(dataStore.retrieveAll(), is(empty())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContextTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContextTest.java index 481c0f98..dfd0a726 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContextTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContextTest.java @@ -12,7 +12,10 @@ import java.util.concurrent.atomic.AtomicLong; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -20,31 +23,34 @@ */ public class DefaultResultAdapterContextTest { - @Test(expectedExceptions = ResultAdapterFailureException.class) - public void testInvalidConversion() throws Exception { - final DefaultResultAdapterContext context = new DefaultResultAdapterContext(); - context.adapt(new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPerson"), new Object[]{}), - new Address()); - } + @Test(expectedExceptions = ResultAdapterFailureException.class) + public void testInvalidConversion() throws Exception { + final DefaultResultAdapterContext context = new DefaultResultAdapterContext(); + context.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findPerson"), new Object[] {}), + new Address()); + } - @Test - public void testRegisteringOrderedAdapters() throws Exception { - final DefaultResultAdapterContext context = new DefaultResultAdapterContext(); - final AtomicLong counter = new AtomicLong(); - final Person person = new Person(); - final SpyingResultAdapter first = new SpyingResultAdapter(-10000, counter, false, null); - final SpyingResultAdapter second = new SpyingResultAdapter(10000, counter, true, person); - context.register(first); - context.register(second); - final Object result = context.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPerson"), new Object[]{}), - new Address()); - assertThat(first.getCheck(), is(notNullValue())); - assertThat(second.getCheck(), is(notNullValue())); - assertThat(first.getCheck(), is(lessThan(second.getCheck()))); - assertThat(first.getRequest(), is(nullValue())); - assertThat(second.getCheck(), is(lessThan(second.getRequest()))); - assertThat(result, Matchers.is(person)); - } - -} \ No newline at end of file + @Test + public void testRegisteringOrderedAdapters() throws Exception { + final DefaultResultAdapterContext context = new DefaultResultAdapterContext(); + final AtomicLong counter = new AtomicLong(); + final Person person = new Person(); + final SpyingResultAdapter first = new SpyingResultAdapter(-10000, counter, false, null); + final SpyingResultAdapter second = new SpyingResultAdapter(10000, counter, true, person); + context.register(first); + context.register(second); + final Object result = + context.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findPerson"), new Object[] {}), + new Address()); + assertThat(first.getCheck(), is(notNullValue())); + assertThat(second.getCheck(), is(notNullValue())); + assertThat(first.getCheck(), is(lessThan(second.getCheck()))); + assertThat(first.getRequest(), is(nullValue())); + assertThat(second.getCheck(), is(lessThan(second.getRequest()))); + assertThat(result, Matchers.is(person)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContextTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContextTest.java index e18a6e08..1f6bc8cd 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContextTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContextTest.java @@ -2,8 +2,17 @@ import com.mmnaseri.utils.spring.data.error.RepositoryDefinitionException; import com.mmnaseri.utils.spring.data.proxy.TypeMapping; -import com.mmnaseri.utils.spring.data.repository.*; -import com.mmnaseri.utils.spring.data.sample.usecases.proxy.*; +import com.mmnaseri.utils.spring.data.repository.DefaultCrudRepository; +import com.mmnaseri.utils.spring.data.repository.DefaultGemfireRepository; +import com.mmnaseri.utils.spring.data.repository.DefaultJpaRepository; +import com.mmnaseri.utils.spring.data.repository.DefaultPagingAndSortingRepository; +import com.mmnaseri.utils.spring.data.repository.DefaultQueryByExampleExecutor; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ErrorThrowingImplementation; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.HighPriorityMapping; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ImplementationWithPrivateConstructor; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ImplementationWithoutADefaultConstructor; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.LowerPriorityMapping; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ProperImplementation; import org.hamcrest.Matchers; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -11,7 +20,12 @@ import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -19,134 +33,134 @@ */ public class DefaultTypeMappingContextTest { - private Class[] defaultImplementations; - - @BeforeMethod - public void setUp() { - defaultImplementations = new Class[]{ - DefaultGemfireRepository.class, - DefaultJpaRepository.class, - DefaultPagingAndSortingRepository.class, - DefaultCrudRepository.class, - DefaultQueryByExampleExecutor.class + private Class[] defaultImplementations; + + @BeforeMethod + public void setUp() { + defaultImplementations = + new Class[] { + DefaultGemfireRepository.class, + DefaultJpaRepository.class, + DefaultPagingAndSortingRepository.class, + DefaultCrudRepository.class, + DefaultQueryByExampleExecutor.class }; - } - - @Test - public void testDefaultMappings() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - assertThat(context.getImplementations(Object.class), - Matchers.>containsInAnyOrder(defaultImplementations)); - } - - @Test - public void testRegisteringMappings() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length)); - context.register(Double.class, Float.class); - assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1)); - assertThat(context.getImplementations(Double.class), hasItem(Float.class)); - } - - @Test - public void testRegisteringMappingForSupertype() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length)); - context.register(Number.class, Float.class); - assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1)); - assertThat(context.getImplementations(Double.class), hasItem(Float.class)); - } - - @Test - public void testRegisteringOrderedMappings() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length)); - context.register(Number.class, HighPriorityMapping.class); - context.register(Number.class, LowerPriorityMapping.class); - assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length + 2)); - assertThat(context.getImplementations(Double.class), hasItem(LowerPriorityMapping.class)); - assertThat(context.getImplementations(Double.class), hasItem(HighPriorityMapping.class)); - assertThat(context.getImplementations(Double.class).indexOf(LowerPriorityMapping.class), - is(lessThan(context.getImplementations(Double.class).indexOf(HighPriorityMapping.class)))); - } - - @Test - public void testRegisteringWithParent() { - final DefaultTypeMappingContext parent = new DefaultTypeMappingContext(); - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(parent); - assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length)); - parent.register(Number.class, Float.class); - assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1)); - assertThat(context.getImplementations(Double.class), hasItem(Float.class)); - } - - @Test(expectedExceptions = RepositoryDefinitionException.class) - public void testRegisteringAbstractImplementation() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - context.register(Object.class, AbstractImplementation.class); - } - - @Test(expectedExceptions = RepositoryDefinitionException.class) - public void testRegisteringInterfaceImplementation() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - context.register(Object.class, InterfaceImplementation.class); - } - - @Test(expectedExceptions = RepositoryDefinitionException.class) - public void testGettingMappingsWhenConstructorIsPrivate() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - context.register(Number.class, ImplementationWithPrivateConstructor.class); - context.getMappings(Double.class); - } - - @Test(expectedExceptions = RepositoryDefinitionException.class) - public void testGettingMappingsWhenClassIsPrivate() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - context.register(Number.class, PrivateImplementationClass.class); - context.getMappings(Double.class); - } - - @Test(expectedExceptions = RepositoryDefinitionException.class) - public void testGettingMappingsWhenClassHasNoDefaultConstructor() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - context.register(Number.class, ImplementationWithoutADefaultConstructor.class); - context.getMappings(Double.class); - } - - @Test(expectedExceptions = RepositoryDefinitionException.class) - public void testGettingMappingsWhenClassThrowsErrors() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - context.register(Number.class, ErrorThrowingImplementation.class); - context.getMappings(Double.class); - } - - @Test - public void testRegisteringAProperImplementation() { - final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); - context.register(Number.class, ProperImplementation.class); - final List> mappings = context.getMappings(Double.class); - assertThat(mappings, hasSize(defaultImplementations.length + 1)); - ProperImplementation implementation = null; - for (TypeMapping mapping : mappings) { - assertThat(mapping.getInstance(), is(instanceOf(mapping.getType()))); - if (mapping.getType().equals(ProperImplementation.class)) { - implementation = (ProperImplementation) mapping.getInstance(); - } - } - assertThat(implementation, is(notNullValue())); - assertThat(implementation.pi(), is(Math.PI)); - } - - private static abstract class AbstractImplementation { - - } - - private interface InterfaceImplementation { - - } - - private static class PrivateImplementationClass { - - } - -} \ No newline at end of file + } + + @Test + public void testDefaultMappings() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + assertThat( + context.getImplementations(Object.class), + Matchers.>containsInAnyOrder(defaultImplementations)); + } + + @Test + public void testRegisteringMappings() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length)); + context.register(Double.class, Float.class); + assertThat( + context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1)); + assertThat(context.getImplementations(Double.class), hasItem(Float.class)); + } + + @Test + public void testRegisteringMappingForSupertype() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length)); + context.register(Number.class, Float.class); + assertThat( + context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1)); + assertThat(context.getImplementations(Double.class), hasItem(Float.class)); + } + + @Test + public void testRegisteringOrderedMappings() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length)); + context.register(Number.class, HighPriorityMapping.class); + context.register(Number.class, LowerPriorityMapping.class); + assertThat( + context.getImplementations(Double.class), hasSize(defaultImplementations.length + 2)); + assertThat(context.getImplementations(Double.class), hasItem(LowerPriorityMapping.class)); + assertThat(context.getImplementations(Double.class), hasItem(HighPriorityMapping.class)); + assertThat( + context.getImplementations(Double.class).indexOf(LowerPriorityMapping.class), + is(lessThan(context.getImplementations(Double.class).indexOf(HighPriorityMapping.class)))); + } + + @Test + public void testRegisteringWithParent() { + final DefaultTypeMappingContext parent = new DefaultTypeMappingContext(); + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(parent); + assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length)); + parent.register(Number.class, Float.class); + assertThat( + context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1)); + assertThat(context.getImplementations(Double.class), hasItem(Float.class)); + } + + @Test(expectedExceptions = RepositoryDefinitionException.class) + public void testRegisteringAbstractImplementation() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + context.register(Object.class, AbstractImplementation.class); + } + + @Test(expectedExceptions = RepositoryDefinitionException.class) + public void testRegisteringInterfaceImplementation() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + context.register(Object.class, InterfaceImplementation.class); + } + + @Test(expectedExceptions = RepositoryDefinitionException.class) + public void testGettingMappingsWhenConstructorIsPrivate() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + context.register(Number.class, ImplementationWithPrivateConstructor.class); + context.getMappings(Double.class); + } + + @Test(expectedExceptions = RepositoryDefinitionException.class) + public void testGettingMappingsWhenClassIsPrivate() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + context.register(Number.class, PrivateImplementationClass.class); + context.getMappings(Double.class); + } + + @Test(expectedExceptions = RepositoryDefinitionException.class) + public void testGettingMappingsWhenClassHasNoDefaultConstructor() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + context.register(Number.class, ImplementationWithoutADefaultConstructor.class); + context.getMappings(Double.class); + } + + @Test(expectedExceptions = RepositoryDefinitionException.class) + public void testGettingMappingsWhenClassThrowsErrors() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + context.register(Number.class, ErrorThrowingImplementation.class); + context.getMappings(Double.class); + } + + @Test + public void testRegisteringAProperImplementation() { + final DefaultTypeMappingContext context = new DefaultTypeMappingContext(); + context.register(Number.class, ProperImplementation.class); + final List> mappings = context.getMappings(Double.class); + assertThat(mappings, hasSize(defaultImplementations.length + 1)); + ProperImplementation implementation = null; + for (TypeMapping mapping : mappings) { + assertThat(mapping.getInstance(), is(instanceOf(mapping.getType()))); + if (mapping.getType().equals(ProperImplementation.class)) { + implementation = (ProperImplementation) mapping.getInstance(); + } + } + assertThat(implementation, is(notNullValue())); + assertThat(implementation.pi(), is(Math.PI)); + } + + private interface InterfaceImplementation {} + + private abstract static class AbstractImplementation {} + + private static class PrivateImplementationClass {} +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMappingTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMappingTest.java index 6feef768..31bfb241 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMappingTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMappingTest.java @@ -15,14 +15,12 @@ */ public class ImmutableInvocationMappingTest { - @Test - public void testToString() throws Exception { - final String string = "string representation"; - final Method method = ReturnTypeSampleRepository.class.getMethod("doSomething"); - final ImmutableInvocationMapping mapping = new ImmutableInvocationMapping<>(method, - new StringifiableDataStoreOperation<>( - string)); - assertThat(mapping.toString(), is(method.toString() + " -> " + string)); - } - -} \ No newline at end of file + @Test + public void testToString() throws Exception { + final String string = "string representation"; + final Method method = ReturnTypeSampleRepository.class.getMethod("doSomething"); + final ImmutableInvocationMapping mapping = + new ImmutableInvocationMapping<>(method, new StringifiableDataStoreOperation<>(string)); + assertThat(mapping.toString(), is(method.toString() + " -> " + string)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfigurationTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfigurationTest.java index c641ba72..637a6ec6 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfigurationTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfigurationTest.java @@ -17,26 +17,28 @@ */ public class ImmutableRepositoryFactoryConfigurationTest { - @Test - public void testCopyConstructor() { - final DefaultRepositoryFactoryConfiguration original = new DefaultRepositoryFactoryConfiguration(); - original.setDescriptionExtractor(new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); - original.setEventListenerContext(new DefaultDataStoreEventListenerContext()); - original.setFunctionRegistry(new DefaultDataFunctionRegistry()); - original.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); - original.setResultAdapterContext(new DefaultResultAdapterContext()); - original.setTypeMappingContext(new DefaultTypeMappingContext()); - original.setDataStoreRegistry(new DefaultDataStoreRegistry()); - original.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); - final ImmutableRepositoryFactoryConfiguration copy = new ImmutableRepositoryFactoryConfiguration(original); - assertThat(copy.getTypeMappingContext(), is(original.getTypeMappingContext())); - assertThat(copy.getResultAdapterContext(), is(original.getResultAdapterContext())); - assertThat(copy.getRepositoryMetadataResolver(), is(original.getRepositoryMetadataResolver())); - assertThat(copy.getOperationInvocationHandler(), is(original.getOperationInvocationHandler())); - assertThat(copy.getFunctionRegistry(), is(original.getFunctionRegistry())); - assertThat(copy.getEventListenerContext(), is(original.getEventListenerContext())); - assertThat(copy.getDescriptionExtractor(), is(original.getDescriptionExtractor())); - assertThat(copy.getDataStoreRegistry(), is(original.getDataStoreRegistry())); - } - -} \ No newline at end of file + @Test + public void testCopyConstructor() { + final DefaultRepositoryFactoryConfiguration original = + new DefaultRepositoryFactoryConfiguration(); + original.setDescriptionExtractor( + new MethodQueryDescriptionExtractor(new DefaultOperatorContext())); + original.setEventListenerContext(new DefaultDataStoreEventListenerContext()); + original.setFunctionRegistry(new DefaultDataFunctionRegistry()); + original.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver()); + original.setResultAdapterContext(new DefaultResultAdapterContext()); + original.setTypeMappingContext(new DefaultTypeMappingContext()); + original.setDataStoreRegistry(new DefaultDataStoreRegistry()); + original.setOperationInvocationHandler(new NonDataOperationInvocationHandler()); + final ImmutableRepositoryFactoryConfiguration copy = + new ImmutableRepositoryFactoryConfiguration(original); + assertThat(copy.getTypeMappingContext(), is(original.getTypeMappingContext())); + assertThat(copy.getResultAdapterContext(), is(original.getResultAdapterContext())); + assertThat(copy.getRepositoryMetadataResolver(), is(original.getRepositoryMetadataResolver())); + assertThat(copy.getOperationInvocationHandler(), is(original.getOperationInvocationHandler())); + assertThat(copy.getFunctionRegistry(), is(original.getFunctionRegistry())); + assertThat(copy.getEventListenerContext(), is(original.getEventListenerContext())); + assertThat(copy.getDescriptionExtractor(), is(original.getDescriptionExtractor())); + assertThat(copy.getDataStoreRegistry(), is(original.getDataStoreRegistry())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandlerTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandlerTest.java index f3da4e7c..96a6f385 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandlerTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandlerTest.java @@ -14,34 +14,38 @@ */ public class NonDataOperationInvocationHandlerTest { - @Test - public void testHandlingKnownMethods() throws Throwable { - final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler(); - final Object proxy = new Object(); - assertThat(handler.invoke(proxy, Object.class.getMethod("hashCode"), new Object[]{}), - Matchers.is(proxy.hashCode())); - assertThat(handler.invoke(proxy, Object.class.getMethod("toString"), new Object[]{}), - Matchers.is(proxy.toString())); - assertThat(handler.invoke(proxy, Object.class.getMethod("equals", Object.class), new Object[]{proxy}), - Matchers.is(true)); - assertThat(handler.invoke(proxy, Object.class.getMethod("equals", Object.class), new Object[]{new Object()}), - Matchers.is(false)); - } + @Test + public void testHandlingKnownMethods() throws Throwable { + final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler(); + final Object proxy = new Object(); + assertThat( + handler.invoke(proxy, Object.class.getMethod("hashCode"), new Object[] {}), + Matchers.is(proxy.hashCode())); + assertThat( + handler.invoke(proxy, Object.class.getMethod("toString"), new Object[] {}), + Matchers.is(proxy.toString())); + assertThat( + handler.invoke(proxy, Object.class.getMethod("equals", Object.class), new Object[] {proxy}), + Matchers.is(true)); + assertThat( + handler.invoke( + proxy, Object.class.getMethod("equals", Object.class), new Object[] {new Object()}), + Matchers.is(false)); + } - @Test(expectedExceptions = UnknownDataOperationException.class) - public void testUnknownMethod() throws Throwable { - final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler(); - handler.invoke(new Object(), Object.class.getMethod("wait"), new Object[]{}); - } + @Test(expectedExceptions = UnknownDataOperationException.class) + public void testUnknownMethod() throws Throwable { + final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler(); + handler.invoke(new Object(), Object.class.getMethod("wait"), new Object[] {}); + } - @Test - public void testRegisteringMethod() throws Throwable { - final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler(); - final SpyingHandler spy = new SpyingHandler(); - handler.register(spy); - assertThat(spy.isCalled(), is(false)); - handler.invoke(new Object(), Object.class.getMethod("wait"), new Object[0]); - assertThat(spy.isCalled(), is(true)); - } - -} \ No newline at end of file + @Test + public void testRegisteringMethod() throws Throwable { + final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler(); + final SpyingHandler spy = new SpyingHandler(); + handler.register(spy); + assertThat(spy.isCalled(), is(false)); + handler.invoke(new Object(), Object.class.getMethod("wait"), new Object[0]); + assertThat(spy.isCalled(), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapterTest.java index 1aacf460..919ee26b 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapterTest.java @@ -11,7 +11,11 @@ import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -19,42 +23,58 @@ */ public class CollectionIterableResultAdapterTest { - @Test - public void testAdapting() throws Exception { - final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter(); - final Collection value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSet"), null), - Arrays.asList(1, 2, 3, 4, 5, 4, 3, 2, 1)); - assertThat(value, is(notNullValue())); - assertThat(value, hasSize(5)); - assertThat(value, is(instanceOf(Set.class))); - assertThat(value, containsInAnyOrder(1, 2, 3, 4, 5)); - } + @Test + public void testAdapting() throws Exception { + final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter(); + final Collection value = + adapter.adapt( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSet"), null), + Arrays.asList(1, 2, 3, 4, 5, 4, 3, 2, 1)); + assertThat(value, is(notNullValue())); + assertThat(value, hasSize(5)); + assertThat(value, is(instanceOf(Set.class))); + assertThat(value, containsInAnyOrder(1, 2, 3, 4, 5)); + } - @Test(expectedExceptions = ResultAdapterFailureException.class) - public void testAdaptingCustomCollectionImplementation() throws Exception { - final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter(); - adapter.adapt(new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null), - null); - } + @Test(expectedExceptions = ResultAdapterFailureException.class) + public void testAdaptingCustomCollectionImplementation() throws Exception { + final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter(); + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null), + null); + } - @Test - public void testAccepts() throws Exception { - final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter(); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null), - null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null), - new ArrayList<>()), is(true)); - assertThat(adapter.accepts(new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSet"), null), - new ArrayList<>()), is(true)); - assertThat( - adapter.accepts(new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null), - new ArrayList<>()), is(false)); - } - -} \ No newline at end of file + @Test + public void testAccepts() throws Exception { + final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter(); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null), + null), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null), + new ArrayList<>()), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSet"), null), + new ArrayList<>()), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null), + new ArrayList<>()), + is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIteratorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIteratorTest.java index 399f30b2..c94715d9 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIteratorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIteratorTest.java @@ -11,19 +11,18 @@ */ public class EmptyIteratorTest { - @Test - public void testHasNext() { - assertThat(EmptyIterator.INSTANCE.hasNext(), is(false)); - } + @Test + public void testHasNext() { + assertThat(EmptyIterator.INSTANCE.hasNext(), is(false)); + } - @Test(expectedExceptions = IndexOutOfBoundsException.class) - public void testNext() { - EmptyIterator.INSTANCE.next(); - } + @Test(expectedExceptions = IndexOutOfBoundsException.class) + public void testNext() { + EmptyIterator.INSTANCE.next(); + } - @Test(expectedExceptions = IndexOutOfBoundsException.class) - public void testRemove() { - EmptyIterator.INSTANCE.remove(); - } - -} \ No newline at end of file + @Test(expectedExceptions = IndexOutOfBoundsException.class) + public void testRemove() { + EmptyIterator.INSTANCE.remove(); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapterTest.java index 984269d9..1705a931 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapterTest.java @@ -10,7 +10,11 @@ import java.util.concurrent.Future; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -18,32 +22,41 @@ */ public class FutureIterableResultAdapterTest { - @Test - public void testAdapting() throws Exception { - final FutureIterableResultAdapter adapter = new FutureIterableResultAdapter(); - final Future value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), null), - Arrays.asList(1, 2, 3, 4)); - assertThat(value, is(notNullValue())); - assertThat(value.get(), is(instanceOf((Class) Collection.class))); - final Collection collection = (Collection) value.get(); - assertThat(collection, hasSize(4)); - assertThat(collection, containsInAnyOrder(1, 2, 3, 4)); - } + @Test + public void testAdapting() throws Exception { + final FutureIterableResultAdapter adapter = new FutureIterableResultAdapter(); + final Future value = + adapter.adapt( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), null), + Arrays.asList(1, 2, 3, 4)); + assertThat(value, is(notNullValue())); + assertThat(value.get(), is(instanceOf((Class) Collection.class))); + final Collection collection = (Collection) value.get(); + assertThat(collection, hasSize(4)); + assertThat(collection, containsInAnyOrder(1, 2, 3, 4)); + } - @Test - public void testAccepting() throws Exception { - final FutureIterableResultAdapter adapter = new FutureIterableResultAdapter(); - assertThat(adapter.accepts(null, null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[]{}), - new ArrayList<>()), is(true)); - } - -} \ No newline at end of file + @Test + public void testAccepting() throws Exception { + final FutureIterableResultAdapter adapter = new FutureIterableResultAdapter(); + assertThat(adapter.accepts(null, null), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}), + new ArrayList<>()), + is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapterTest.java index 2c40d658..c44efd2e 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapterTest.java @@ -12,7 +12,10 @@ import java.util.Arrays; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -20,39 +23,51 @@ */ public class GeoPageIterableResultAdapterTest { - @Test - public void testAdapting() throws Exception { - final GeoPageIterableResultAdapter adapter = new GeoPageIterableResultAdapter(); - final GeoResult[] geoResults = {new GeoResult<>(1, new Distance(0)), new GeoResult<>(2, new Distance(1)), - new GeoResult<>(3, new Distance(1)), new GeoResult<>(4, new Distance(2))}; - final GeoPage value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findGeoPage"), null), - Arrays.asList(geoResults)); - assertThat(value, is(notNullValue())); - assertThat(value.getAverageDistance(), is(new Distance(1))); - assertThat(value.getNumber(), is(0)); - assertThat(value.getNumberOfElements(), is(4)); - assertThat(value.getSize(), is(4)); - assertThat(value.getTotalElements(), is(4L)); - assertThat(value.getTotalPages(), is(1)); - assertThat(value.getSort(), is(Sort.unsorted())); - assertThat(value.getContent(), hasSize(4)); - assertThat(value.getContent(), containsInAnyOrder(geoResults)); - } + @Test + public void testAdapting() throws Exception { + final GeoPageIterableResultAdapter adapter = new GeoPageIterableResultAdapter(); + final GeoResult[] geoResults = { + new GeoResult<>(1, new Distance(0)), new GeoResult<>(2, new Distance(1)), + new GeoResult<>(3, new Distance(1)), new GeoResult<>(4, new Distance(2)) + }; + final GeoPage value = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findGeoPage"), null), + Arrays.asList(geoResults)); + assertThat(value, is(notNullValue())); + assertThat(value.getAverageDistance(), is(new Distance(1))); + assertThat(value.getNumber(), is(0)); + assertThat(value.getNumberOfElements(), is(4)); + assertThat(value.getSize(), is(4)); + assertThat(value.getTotalElements(), is(4L)); + assertThat(value.getTotalPages(), is(1)); + assertThat(value.getSort(), is(Sort.unsorted())); + assertThat(value.getContent(), hasSize(4)); + assertThat(value.getContent(), containsInAnyOrder(geoResults)); + } - @Test - public void testAccepting() throws Exception { - final GeoPageIterableResultAdapter adapter = new GeoPageIterableResultAdapter(); - assertThat(adapter.accepts(null, null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[]{}), - new ArrayList<>()), is(true)); - } - -} \ No newline at end of file + @Test + public void testAccepting() throws Exception { + final GeoPageIterableResultAdapter adapter = new GeoPageIterableResultAdapter(); + assertThat(adapter.accepts(null, null), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[] {}), + new ArrayList<>()), + is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapterTest.java index 04929056..69ba63b1 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapterTest.java @@ -9,7 +9,9 @@ import java.util.Iterator; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isIn; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -17,35 +19,45 @@ */ public class IteratorIterableResultAdapterTest { - @Test - public void testAdapting() throws Exception { - final IteratorIterableResultAdapter adapter = new IteratorIterableResultAdapter(); - final Iterator value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterator"), null), - Arrays.asList(1, 2, 3, 4)); - assertThat(value, is(notNullValue())); - int count = 0; - while (value.hasNext()) { - final Object item = value.next(); - assertThat(item, isIn(new Object[]{1, 2, 3, 4})); - count++; - } - assertThat(count, is(4)); + @Test + public void testAdapting() throws Exception { + final IteratorIterableResultAdapter adapter = new IteratorIterableResultAdapter(); + final Iterator value = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterator"), null), + Arrays.asList(1, 2, 3, 4)); + assertThat(value, is(notNullValue())); + int count = 0; + while (value.hasNext()) { + final Object item = value.next(); + assertThat(item, isIn(new Object[] {1, 2, 3, 4})); + count++; } + assertThat(count, is(4)); + } - @Test - public void testAccepting() throws Exception { - final IteratorIterableResultAdapter adapter = new IteratorIterableResultAdapter(); - assertThat(adapter.accepts(null, null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[]{}), - new ArrayList<>()), is(true)); - } - -} \ No newline at end of file + @Test + public void testAccepting() throws Exception { + final IteratorIterableResultAdapter adapter = new IteratorIterableResultAdapter(); + assertThat(adapter.accepts(null, null), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}), + new ArrayList<>()), + is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapterTest.java index 7204b15d..f2ded2a7 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapterTest.java @@ -20,32 +20,47 @@ */ public class ListenableFutureIterableResultAdapterTest { - @Test - public void testAccepting() throws Exception { - final ListenableFutureIterableResultAdapter adapter = new ListenableFutureIterableResultAdapter(); - assertThat(adapter.accepts(null, null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), - new Object[]{}), new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), - new Object[]{}), new ArrayList<>()), is(true)); - } + @Test + public void testAccepting() throws Exception { + final ListenableFutureIterableResultAdapter adapter = + new ListenableFutureIterableResultAdapter(); + assertThat(adapter.accepts(null, null), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), + new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), + new Object[] {}), + new ArrayList<>()), + is(true)); + } - @Test - public void testAdapting() throws Exception { - final ListenableFutureIterableResultAdapter adapter = new ListenableFutureIterableResultAdapter(); - final List originalValue = Arrays.asList(1, 2, 3); - final ListenableFuture adapted = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), - new Object[]{}), originalValue); - assertThat(adapted, is(notNullValue())); - final Object result = adapted.get(); - assertThat(result, is(notNullValue())); - assertThat(result, Matchers.is(originalValue)); - } - -} \ No newline at end of file + @Test + public void testAdapting() throws Exception { + final ListenableFutureIterableResultAdapter adapter = + new ListenableFutureIterableResultAdapter(); + final List originalValue = Arrays.asList(1, 2, 3); + final ListenableFuture adapted = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), + new Object[] {}), + originalValue); + assertThat(adapted, is(notNullValue())); + final Object result = adapted.get(); + assertThat(result, is(notNullValue())); + assertThat(result, Matchers.is(originalValue)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapterTest.java index 760e40da..607b3fe9 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapterTest.java @@ -15,40 +15,58 @@ */ public class NullSimpleResultAdapterTest { - @Test - public void testAcceptance() throws Exception { - final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter(); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), null), - is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findList"), new Object[]{}), null), - is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[]{}), - null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[]{}), - null), is(false)); - } + @Test + public void testAcceptance() throws Exception { + final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter(); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findList"), new Object[] {}), + null), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}), + null), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}), + null), + is(false)); + } - @Test - public void testAdaptingNull() throws Exception { - final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter(); - final Object value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), null); - assertThat(value, is(nullValue())); - } - - @Test(expectedExceptions = ResultAdapterFailureException.class) - public void testAdaptingPrimitiveToNull() throws Exception { - final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter(); + @Test + public void testAdaptingNull() throws Exception { + final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter(); + final Object value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPrimitive"), new Object[]{}), - null); - } + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + null); + assertThat(value, is(nullValue())); + } -} \ No newline at end of file + @Test(expectedExceptions = ResultAdapterFailureException.class) + public void testAdaptingPrimitiveToNull() throws Exception { + final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter(); + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findPrimitive"), new Object[] {}), + null); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapterTest.java index e4c3bf62..f5d6fadb 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapterTest.java @@ -5,10 +5,17 @@ import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository; import org.testng.annotations.Test; -import java.util.*; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -16,62 +23,84 @@ */ public class NullToCollectionResultAdapterTest { - @Test - public void testAcceptance() throws Exception { - final ResultAdapter adapter = new NullToCollectionResultAdapter(); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findList"), new Object[]{}), null), - is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findQueue"), new Object[]{}), null), - is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSet"), new Object[]{}), null), - is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLinkedList"), new Object[]{}), - null), is(true)); - } + @Test + public void testAcceptance() throws Exception { + final ResultAdapter adapter = new NullToCollectionResultAdapter(); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findList"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findQueue"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findSet"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findLinkedList"), new Object[] {}), + null), + is(true)); + } - @Test - public void testAdaptingList() throws Exception { - final ResultAdapter adapter = new NullToCollectionResultAdapter(); - final Collection collection = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findList"), new Object[]{}), null); - assertThat(collection, is(notNullValue())); - assertThat(collection, hasSize(0)); - assertThat(collection, is(instanceOf(List.class))); - } + @Test + public void testAdaptingList() throws Exception { + final ResultAdapter adapter = new NullToCollectionResultAdapter(); + final Collection collection = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findList"), new Object[] {}), + null); + assertThat(collection, is(notNullValue())); + assertThat(collection, hasSize(0)); + assertThat(collection, is(instanceOf(List.class))); + } - @Test - public void testAdaptingSet() throws Exception { - final ResultAdapter adapter = new NullToCollectionResultAdapter(); - final Collection collection = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSet"), new Object[]{}), null); - assertThat(collection, is(notNullValue())); - assertThat(collection, hasSize(0)); - assertThat(collection, is(instanceOf(Set.class))); - } + @Test + public void testAdaptingSet() throws Exception { + final ResultAdapter adapter = new NullToCollectionResultAdapter(); + final Collection collection = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findSet"), new Object[] {}), + null); + assertThat(collection, is(notNullValue())); + assertThat(collection, hasSize(0)); + assertThat(collection, is(instanceOf(Set.class))); + } - @Test - public void testAdaptingQueue() throws Exception { - final ResultAdapter adapter = new NullToCollectionResultAdapter(); - final Collection collection = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findQueue"), new Object[]{}), null); - assertThat(collection, is(notNullValue())); - assertThat(collection, hasSize(0)); - assertThat(collection, is(instanceOf(Queue.class))); - } + @Test + public void testAdaptingQueue() throws Exception { + final ResultAdapter adapter = new NullToCollectionResultAdapter(); + final Collection collection = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findQueue"), new Object[] {}), + null); + assertThat(collection, is(notNullValue())); + assertThat(collection, hasSize(0)); + assertThat(collection, is(instanceOf(Queue.class))); + } - @Test - public void testAdaptingConcreteCollection() throws Exception { - final ResultAdapter adapter = new NullToCollectionResultAdapter(); - final Collection collection = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLinkedList"), new Object[]{}), - null); - assertThat(collection, is(notNullValue())); - assertThat(collection, hasSize(0)); - assertThat(collection, is(instanceOf(LinkedList.class))); - } - -} \ No newline at end of file + @Test + public void testAdaptingConcreteCollection() throws Exception { + final ResultAdapter adapter = new NullToCollectionResultAdapter(); + final Collection collection = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findLinkedList"), new Object[] {}), + null); + assertThat(collection, is(notNullValue())); + assertThat(collection, hasSize(0)); + assertThat(collection, is(instanceOf(LinkedList.class))); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapterTest.java index 9eef260c..0f96e138 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapterTest.java @@ -8,7 +8,9 @@ import java.util.concurrent.Future; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -16,25 +18,32 @@ */ public class NullToFutureResultAdapterTest { - @Test - public void testAcceptance() throws Exception { - final ResultAdapter adapter = new NullToFutureResultAdapter(); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[]{}), - null), is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), null), - is(false)); - } + @Test + public void testAcceptance() throws Exception { + final ResultAdapter adapter = new NullToFutureResultAdapter(); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + null), + is(false)); + } - @Test - public void testAdaptingFuture() throws Exception { - final ResultAdapter adapter = new NullToFutureResultAdapter(); - final Future value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[]{}), - null); - assertThat(value, is(notNullValue())); - assertThat(value.get(), is(nullValue())); - } - -} \ No newline at end of file + @Test + public void testAdaptingFuture() throws Exception { + final ResultAdapter adapter = new NullToFutureResultAdapter(); + final Future value = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}), + null); + assertThat(value, is(notNullValue())); + assertThat(value.get(), is(nullValue())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapterTest.java index 48682404..0d6f14d8 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapterTest.java @@ -17,27 +17,34 @@ */ public class NullToIterableResultAdapterTest { - @Test - public void testAcceptance() throws Exception { - final ResultAdapter adapter = new NullToIterableResultAdapter(); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[]{}), - null), is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), null), - is(false)); - } + @Test + public void testAcceptance() throws Exception { + final ResultAdapter adapter = new NullToIterableResultAdapter(); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + null), + is(false)); + } - @Test - public void testAdaptingToIterable() throws Exception { - final ResultAdapter adapter = new NullToIterableResultAdapter(); - final Iterable value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[]{}), - null); - assertThat(value, is(notNullValue())); - assertThat(value.iterator(), is(notNullValue())); - final Iterator iterator = value.iterator(); - assertThat(iterator.hasNext(), is(false)); - } - -} \ No newline at end of file + @Test + public void testAdaptingToIterable() throws Exception { + final ResultAdapter adapter = new NullToIterableResultAdapter(); + final Iterable value = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[] {}), + null); + assertThat(value, is(notNullValue())); + assertThat(value.iterator(), is(notNullValue())); + final Iterator iterator = value.iterator(); + assertThat(iterator.hasNext(), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapterTest.java index 42ac7bc1..897377ce 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapterTest.java @@ -17,25 +17,32 @@ */ public class NullToIteratorResultAdapterTest { - @Test - public void testAcceptance() throws Exception { - final ResultAdapter adapter = new NullToIteratorResultAdapter(); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[]{}), - null), is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), null), - is(false)); - } + @Test + public void testAcceptance() throws Exception { + final ResultAdapter adapter = new NullToIteratorResultAdapter(); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + null), + is(false)); + } - @Test - public void testAdaptingToIterable() throws Exception { - final ResultAdapter adapter = new NullToIteratorResultAdapter(); - final Iterator value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[]{}), - null); - assertThat(value, is(notNullValue())); - assertThat(value.hasNext(), is(false)); - } - -} \ No newline at end of file + @Test + public void testAdaptingToIterable() throws Exception { + final ResultAdapter adapter = new NullToIteratorResultAdapter(); + final Iterator value = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}), + null); + assertThat(value, is(notNullValue())); + assertThat(value.hasNext(), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapterTest.java index bb5b88dd..3fec5c17 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapterTest.java @@ -7,7 +7,9 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -15,26 +17,35 @@ */ public class NullToListenableFutureResultAdapterTest { - @Test - public void testAccepting() throws Exception { - final ResultAdapter adapter = new NullToListenableFutureResultAdapter(); - assertThat(adapter.accepts(null, new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), null), - is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), - new Object[]{}), null), is(true)); - } + @Test + public void testAccepting() throws Exception { + final ResultAdapter adapter = new NullToListenableFutureResultAdapter(); + assertThat(adapter.accepts(null, new Object()), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + null), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), + new Object[] {}), + null), + is(true)); + } - @Test - public void testAdaptingTheResult() throws Exception { - final ResultAdapter adapter = new NullToListenableFutureResultAdapter(); - final ListenableFuture adapted = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), - new Object[]{}), null); - assertThat(adapted, is(notNullValue())); - assertThat(adapted.get(), is(nullValue())); - } - -} \ No newline at end of file + @Test + public void testAdaptingTheResult() throws Exception { + final ResultAdapter adapter = new NullToListenableFutureResultAdapter(); + final ListenableFuture adapted = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findListenableFuture"), + new Object[] {}), + null); + assertThat(adapted, is(notNullValue())); + assertThat(adapted.get(), is(nullValue())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapterTest.java index 428c6511..5c1d449c 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapterTest.java @@ -8,7 +8,9 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -16,58 +18,74 @@ */ public class NullToSliceResultAdapterTest { - @Test - public void testAcceptance() throws Exception { - final ResultAdapter adapter = new NullToSliceResultAdapter(); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[]{}), null), - is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[]{}), null), - is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[]{}), - null), is(true)); - } + @Test + public void testAcceptance() throws Exception { + final ResultAdapter adapter = new NullToSliceResultAdapter(); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[] {}), + null), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[] {}), + null), + is(true)); + } - @Test - public void testAdaptingToASlice() throws Exception { - final ResultAdapter adapter = new NullToSliceResultAdapter(); - final Slice value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[]{}), null); - assertThat(value, is(notNullValue())); - assertThat(value.getNumber(), is(0)); - assertThat(value.getNumberOfElements(), is(0)); - assertThat(value.getSize(), is(0)); - assertThat(value.getSort(), is(Sort.unsorted())); - assertThat(value.getContent(), hasSize(0)); - } + @Test + public void testAdaptingToASlice() throws Exception { + final ResultAdapter adapter = new NullToSliceResultAdapter(); + final Slice value = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}), + null); + assertThat(value, is(notNullValue())); + assertThat(value.getNumber(), is(0)); + assertThat(value.getNumberOfElements(), is(0)); + assertThat(value.getSize(), is(0)); + assertThat(value.getSort(), is(Sort.unsorted())); + assertThat(value.getContent(), hasSize(0)); + } - @Test - public void testAdaptingToAPage() throws Exception { - final ResultAdapter adapter = new NullToSliceResultAdapter(); - final Slice value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[]{}), null); - assertThat(value, is(notNullValue())); - assertThat(value.getNumber(), is(0)); - assertThat(value.getNumberOfElements(), is(0)); - assertThat(value.getSize(), is(0)); - assertThat(value.getSort(), is(Sort.unsorted())); - assertThat(value.getContent(), hasSize(0)); - } + @Test + public void testAdaptingToAPage() throws Exception { + final ResultAdapter adapter = new NullToSliceResultAdapter(); + final Slice value = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[] {}), + null); + assertThat(value, is(notNullValue())); + assertThat(value.getNumber(), is(0)); + assertThat(value.getNumberOfElements(), is(0)); + assertThat(value.getSize(), is(0)); + assertThat(value.getSort(), is(Sort.unsorted())); + assertThat(value.getContent(), hasSize(0)); + } - @Test - public void testAdaptingToAGeoPage() throws Exception { - final ResultAdapter adapter = new NullToSliceResultAdapter(); - final Slice value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[]{}), - null); - assertThat(value, is(notNullValue())); - assertThat(value.getNumber(), is(0)); - assertThat(value.getNumberOfElements(), is(0)); - assertThat(value.getSize(), is(0)); - assertThat(value.getSort(), is(Sort.unsorted())); - assertThat(value.getContent(), hasSize(0)); - } - -} \ No newline at end of file + @Test + public void testAdaptingToAGeoPage() throws Exception { + final ResultAdapter adapter = new NullToSliceResultAdapter(); + final Slice value = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[] {}), + null); + assertThat(value, is(notNullValue())); + assertThat(value.getNumber(), is(0)); + assertThat(value.getNumberOfElements(), is(0)); + assertThat(value.getSize(), is(0)); + assertThat(value.getSort(), is(Sort.unsorted())); + assertThat(value.getContent(), hasSize(0)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapterTest.java index 419c9777..d799afe5 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapterTest.java @@ -18,59 +18,96 @@ */ public class NumberIterableResultAdapterTest { - @Test - public void testAccepting() throws Exception { - final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter(); - assertThat(adapter.accepts(null, null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[]{}), - Arrays.asList("", 1)), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[]{}), - Arrays.asList(1, 2)), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[]{}), - Collections.singletonList(1)), is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[]{}), - Collections.singletonList(1)), is(true)); - } + @Test + public void testAccepting() throws Exception { + final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter(); + assertThat(adapter.accepts(null, null), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}), + Arrays.asList("", 1)), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}), + Arrays.asList(1, 2)), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}), + Collections.singletonList(1)), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[] {}), + Collections.singletonList(1)), + is(true)); + } - @Test - public void testAdapting() throws Exception { - final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter(); - Long value = 100L; - assertThat(adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[]{}), - Collections.singleton(value)), Matchers.is(value.intValue())); - assertThat(adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), new Object[]{}), - Collections.singleton(value)), Matchers.is(value)); - assertThat(adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findShort"), new Object[]{}), - Collections.singleton(value)), Matchers.is(value.shortValue())); - assertThat(adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findDouble"), new Object[]{}), - Collections.singleton(value)), Matchers.is(value.doubleValue())); - assertThat(adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFloat"), new Object[]{}), - Collections.singleton(value)), Matchers.is(value.floatValue())); - assertThat(adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findByte"), new Object[]{}), - Collections.singleton(value)), Matchers.is(value.byteValue())); - } - - @Test(expectedExceptions = ResultAdapterFailureException.class) - public void testAdaptingUnsupportedNumberType() throws Exception { - final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter(); + @Test + public void testAdapting() throws Exception { + final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter(); + Long value = 100L; + assertThat( + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}), + Collections.singleton(value)), + Matchers.is(value.intValue())); + assertThat( + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findLong"), new Object[] {}), + Collections.singleton(value)), + Matchers.is(value)); + assertThat( + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findShort"), new Object[] {}), + Collections.singleton(value)), + Matchers.is(value.shortValue())); + assertThat( adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findBigDecimal"), new Object[]{}), - Collections.singletonList(1)); - } -} \ No newline at end of file + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findDouble"), new Object[] {}), + Collections.singleton(value)), + Matchers.is(value.doubleValue())); + assertThat( + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findFloat"), new Object[] {}), + Collections.singleton(value)), + Matchers.is(value.floatValue())); + assertThat( + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findByte"), new Object[] {}), + Collections.singleton(value)), + Matchers.is(value.byteValue())); + } + + @Test(expectedExceptions = ResultAdapterFailureException.class) + public void testAdaptingUnsupportedNumberType() throws Exception { + final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter(); + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findBigDecimal"), new Object[] {}), + Collections.singletonList(1)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapterTest.java index ab952c52..0045fe73 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapterTest.java @@ -9,7 +9,10 @@ import java.util.Arrays; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -17,36 +20,45 @@ */ public class PageIterableResultAdapterTest { - @Test - public void testAdapting() throws Exception { - final PageIterableResultAdapter adapter = new PageIterableResultAdapter(); - final org.springframework.data.domain.Page value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPage"), null), - Arrays.asList(1, 2, 3, 4)); - assertThat(value, is(notNullValue())); - assertThat(value.getTotalElements(), is(4L)); - assertThat(value.getTotalPages(), is(1)); - assertThat(value.getNumber(), is(0)); - assertThat(value.getNumberOfElements(), is(4)); - assertThat(value.getSize(), is(4)); - assertThat(value.getSort(), is(Sort.unsorted())); - assertThat(value.getContent(), hasSize(4)); - assertThat(value.getContent(), containsInAnyOrder(1, 2, 3, 4)); - } + @Test + public void testAdapting() throws Exception { + final PageIterableResultAdapter adapter = new PageIterableResultAdapter(); + final org.springframework.data.domain.Page value = + adapter.adapt( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPage"), null), + Arrays.asList(1, 2, 3, 4)); + assertThat(value, is(notNullValue())); + assertThat(value.getTotalElements(), is(4L)); + assertThat(value.getTotalPages(), is(1)); + assertThat(value.getNumber(), is(0)); + assertThat(value.getNumberOfElements(), is(4)); + assertThat(value.getSize(), is(4)); + assertThat(value.getSort(), is(Sort.unsorted())); + assertThat(value.getContent(), hasSize(4)); + assertThat(value.getContent(), containsInAnyOrder(1, 2, 3, 4)); + } - @Test - public void testAccepting() throws Exception { - final PageIterableResultAdapter adapter = new PageIterableResultAdapter(); - assertThat(adapter.accepts(null, null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[]{}), - new ArrayList<>()), is(true)); - } - -} \ No newline at end of file + @Test + public void testAccepting() throws Exception { + final PageIterableResultAdapter adapter = new PageIterableResultAdapter(); + assertThat(adapter.accepts(null, null), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[] {}), + new ArrayList<>()), + is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapterTest.java index 7622d9f1..43434efd 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapterTest.java @@ -10,7 +10,9 @@ import java.util.Collections; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -18,67 +20,94 @@ */ public class SimpleIterableResultAdapterTest { - @Test - public void testAdaptingEmptyCollection() throws Exception { - final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); - final Object value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null), - Collections.emptyList()); - assertThat(value, is(nullValue())); - } + @Test + public void testAdaptingEmptyCollection() throws Exception { + final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); + final Object value = + adapter.adapt( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null), + Collections.emptyList()); + assertThat(value, is(nullValue())); + } - @Test - public void testAdaptingSingletonList() throws Exception { - final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); - final Object value = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null), - Collections.singletonList(1)); - assertThat(value, is(notNullValue())); - assertThat(value, is(1)); - } + @Test + public void testAdaptingSingletonList() throws Exception { + final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); + final Object value = + adapter.adapt( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null), + Collections.singletonList(1)); + assertThat(value, is(notNullValue())); + assertThat(value, is(1)); + } - @Test(expectedExceptions = ResultAdapterFailureException.class, - expectedExceptionsMessageRegExp = ".*?; Expected only one item but found many") - public void testAdaptingMultiItemList() throws Exception { - final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); - adapter.adapt(new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null), - Arrays.asList(1, 2, 3)); - } + @Test( + expectedExceptions = ResultAdapterFailureException.class, + expectedExceptionsMessageRegExp = ".*?; Expected only one item but found many") + public void testAdaptingMultiItemList() throws Exception { + final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); + adapter.adapt( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null), + Arrays.asList(1, 2, 3)); + } - @Test(expectedExceptions = ResultAdapterFailureException.class, - expectedExceptionsMessageRegExp = "Could not adapt value: to type ; " - + "Expected value to be of the indicated type") - public void testAdaptingIncompatibleValue() throws Exception { - final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); - adapter.adapt(new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInteger"), null), - Collections.singletonList("hello")); - } + @Test( + expectedExceptions = ResultAdapterFailureException.class, + expectedExceptionsMessageRegExp = + "Could not adapt value: to type ; " + + "Expected value to be of the indicated type") + public void testAdaptingIncompatibleValue() throws Exception { + final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); + adapter.adapt( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInteger"), null), + Collections.singletonList("hello")); + } - @Test - public void testAccepting() throws Exception { - final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); - assertThat(adapter.accepts(null, null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new ArrayList<>()), is(true)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[]{}), - new ArrayList<>()), is(true)); - } - -} \ No newline at end of file + @Test + public void testAccepting() throws Exception { + final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter(); + assertThat(adapter.accepts(null, null), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new ArrayList<>()), + is(true)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[] {}), + new ArrayList<>()), + is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapterTest.java index 8c114435..3d1f3d36 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapterTest.java @@ -10,7 +10,9 @@ import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isIn; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -18,33 +20,44 @@ */ public class SliceIterableResultAdapterTest { - @Test - public void testAccepting() throws Exception { - final SliceIterableResultAdapter adapter = new SliceIterableResultAdapter(); - assertThat(adapter.accepts(null, null), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[]{}), - new Object()), is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[]{}), - new ArrayList<>()), is(true)); - } + @Test + public void testAccepting() throws Exception { + final SliceIterableResultAdapter adapter = new SliceIterableResultAdapter(); + assertThat(adapter.accepts(null, null), is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}), + new Object()), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}), + new ArrayList<>()), + is(true)); + } - @Test - public void testAdapting() throws Exception { - final SliceIterableResultAdapter adapter = new SliceIterableResultAdapter(); - final List originalValue = Arrays.asList(1, 2, 3, 4); - final Slice slice = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[]{}), - originalValue); - assertThat(slice, is(notNullValue())); - assertThat(slice.getNumberOfElements(), is(originalValue.size())); - final List content = slice.getContent(); - for (Object item : content) { - assertThat(item, isIn(originalValue)); - } + @Test + public void testAdapting() throws Exception { + final SliceIterableResultAdapter adapter = new SliceIterableResultAdapter(); + final List originalValue = Arrays.asList(1, 2, 3, 4); + final Slice slice = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}), + originalValue); + assertThat(slice, is(notNullValue())); + assertThat(slice.getNumberOfElements(), is(originalValue.size())); + final List content = slice.getContent(); + for (Object item : content) { + assertThat(item, isIn(originalValue)); } -} \ No newline at end of file + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapterTest.java index df0821f9..f55d4905 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapterTest.java @@ -14,24 +14,31 @@ */ public class VoidResultAdapterTest { - @Test - public void testAccepting() throws Exception { - final VoidResultAdapter adapter = new VoidResultAdapter(); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[]{}), null), - is(false)); - assertThat(adapter.accepts( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("doSomething"), new Object[]{}), - null), is(true)); - } + @Test + public void testAccepting() throws Exception { + final VoidResultAdapter adapter = new VoidResultAdapter(); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}), + null), + is(false)); + assertThat( + adapter.accepts( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("doSomething"), new Object[] {}), + null), + is(true)); + } - @Test - public void testAdapting() throws Exception { - final VoidResultAdapter adapter = new VoidResultAdapter(); - final Object adapted = adapter.adapt( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("doSomething"), new Object[]{}), - new Object()); - assertThat(adapted, is(nullValue())); - } - -} \ No newline at end of file + @Test + public void testAdapting() throws Exception { + final VoidResultAdapter adapter = new VoidResultAdapter(); + final Object adapted = + adapter.adapt( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("doSomething"), new Object[] {}), + new Object()); + assertThat(adapted, is(nullValue())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverterTest.java index 6365e8a3..d71cffff 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverterTest.java @@ -7,7 +7,10 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -15,38 +18,47 @@ */ public class AbstractResultConverterTest { - @Test - public void testConversionWhenInputIsNull() { - final Object converted = new NoOpResultConverter().convert(null, null); - assertThat(converted, is(nullValue())); - } + @Test + public void testConversionWhenInputIsNull() { + final Object converted = new NoOpResultConverter().convert(null, null); + assertThat(converted, is(nullValue())); + } - @Test - public void testConversionWhenTargetReturnsVoid() throws Exception { - final Object converted = new NoOpResultConverter().convert( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("doSomething"), null), new Object()); - assertThat(converted, is(nullValue())); - } + @Test + public void testConversionWhenTargetReturnsVoid() throws Exception { + final Object converted = + new NoOpResultConverter() + .convert( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("doSomething"), null), + new Object()); + assertThat(converted, is(nullValue())); + } - @Test - public void testWhenTypeMatchesTheReturnType() throws Exception { - final Person original = new Person(); - final Object converted = new NoOpResultConverter().convert( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPerson"), null), original); - assertThat(converted, is(notNullValue())); - assertThat(converted, is(instanceOf(Person.class))); - assertThat(converted, is(original)); - } + @Test + public void testWhenTypeMatchesTheReturnType() throws Exception { + final Person original = new Person(); + final Object converted = + new NoOpResultConverter() + .convert( + new ImmutableInvocation( + ReturnTypeSampleRepository.class.getMethod("findPerson"), null), + original); + assertThat(converted, is(notNullValue())); + assertThat(converted, is(instanceOf(Person.class))); + assertThat(converted, is(original)); + } - @Test - public void testThatPassesToSubClassOtherwise() throws Exception { - final Object original = new Object(); - final NoOpResultConverter converter = new NoOpResultConverter(); - final Object converted = converter.convert( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPerson"), null), original); - assertThat(converted, is(notNullValue())); - assertThat(converted, is(original)); - assertThat(converter.getOriginal(), is(original)); - } - -} \ No newline at end of file + @Test + public void testThatPassesToSubClassOtherwise() throws Exception { + final Object original = new Object(); + final NoOpResultConverter converter = new NoOpResultConverter(); + final Object converted = + converter.convert( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPerson"), null), + original); + assertThat(converted, is(notNullValue())); + assertThat(converted, is(original)); + assertThat(converter.getOriginal(), is(original)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverterTest.java index 3cf00265..e122523c 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverterTest.java @@ -10,7 +10,9 @@ import java.util.concurrent.FutureTask; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -18,32 +20,35 @@ */ public class FutureToIterableConverterTest { - @Test - public void testConvertingFutureValueToIterable() throws Exception { - final FutureToIterableConverter converter = new FutureToIterableConverter(); - final Object original = new Object(); - final FutureTask task = new FutureTask<>(() -> original); - task.run(); - final Object converted = converter.convert( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), task); - assertThat(converted, is(notNullValue())); - assertThat(converted, is(instanceOf(Iterable.class))); - //noinspection unchecked - final Iterable iterable = (Iterable) converted; - final Iterator iterator = iterable.iterator(); - assertThat(iterator.hasNext(), is(true)); - final Object value = iterator.next(); - assertThat(value, is(notNullValue())); - assertThat(value, is(original)); - assertThat(iterator.hasNext(), is(false)); - } + @Test + public void testConvertingFutureValueToIterable() throws Exception { + final FutureToIterableConverter converter = new FutureToIterableConverter(); + final Object original = new Object(); + final FutureTask task = new FutureTask<>(() -> original); + task.run(); + final Object converted = + converter.convert( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), + task); + assertThat(converted, is(notNullValue())); + assertThat(converted, is(instanceOf(Iterable.class))); + //noinspection unchecked + final Iterable iterable = (Iterable) converted; + final Iterator iterator = iterable.iterator(); + assertThat(iterator.hasNext(), is(true)); + final Object value = iterator.next(); + assertThat(value, is(notNullValue())); + assertThat(value, is(original)); + assertThat(iterator.hasNext(), is(false)); + } - @Test(expectedExceptions = ResultConversionFailureException.class) - public void testConvertingFutureError() throws Exception { - final FutureToIterableConverter converter = new FutureToIterableConverter(); - final FutureTask task = new FutureTask<>(new ErrorThrowingCallable()); - task.run(); - converter.convert(new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), task); - } - -} \ No newline at end of file + @Test(expectedExceptions = ResultConversionFailureException.class) + public void testConvertingFutureError() throws Exception { + final FutureToIterableConverter converter = new FutureToIterableConverter(); + final FutureTask task = new FutureTask<>(new ErrorThrowingCallable()); + task.run(); + converter.convert( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), + task); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverterTest.java index de5c46fa..dd9d2303 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverterTest.java @@ -8,7 +8,10 @@ import java.util.Iterator; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -16,25 +19,25 @@ */ public class IteratorToIterableConverterTest { - @Test - public void testConvertingIteratorToIterable() throws Exception { - final IteratorToIterableConverter converter = new IteratorToIterableConverter(); - final Object converted = converter.convert( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), - Arrays.asList(1, 2, 3, 4).iterator()); - assertThat(converted, is(notNullValue())); - assertThat(converted, is(instanceOf(Iterable.class))); - final Iterable iterable = (Iterable) converted; - final Iterator iterator = iterable.iterator(); - assertThat(iterator.hasNext(), is(true)); - assertThat(iterator.next(), equalTo(1)); - assertThat(iterator.hasNext(), is(true)); - assertThat(iterator.next(), equalTo(2)); - assertThat(iterator.hasNext(), is(true)); - assertThat(iterator.next(), equalTo(3)); - assertThat(iterator.hasNext(), is(true)); - assertThat(iterator.next(), equalTo(4)); - assertThat(iterator.hasNext(), is(false)); - } - -} \ No newline at end of file + @Test + public void testConvertingIteratorToIterable() throws Exception { + final IteratorToIterableConverter converter = new IteratorToIterableConverter(); + final Object converted = + converter.convert( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), + Arrays.asList(1, 2, 3, 4).iterator()); + assertThat(converted, is(notNullValue())); + assertThat(converted, is(instanceOf(Iterable.class))); + final Iterable iterable = (Iterable) converted; + final Iterator iterator = iterable.iterator(); + assertThat(iterator.hasNext(), is(true)); + assertThat(iterator.next(), equalTo(1)); + assertThat(iterator.hasNext(), is(true)); + assertThat(iterator.next(), equalTo(2)); + assertThat(iterator.hasNext(), is(true)); + assertThat(iterator.next(), equalTo(3)); + assertThat(iterator.hasNext(), is(true)); + assertThat(iterator.next(), equalTo(4)); + assertThat(iterator.hasNext(), is(false)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverterTest.java index 630d964b..aede9a41 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverterTest.java @@ -8,7 +8,9 @@ import java.util.Iterator; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -16,37 +18,42 @@ */ public class SingleValueToIterableConverterTest { - @Test - public void testConvertingSingleValueToIterable() throws Exception { - final SingleValueToIterableConverter converter = new SingleValueToIterableConverter(); - final Object original = new Object(); - final Object converted = converter.convert( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), original); - assertThat(converted, is(notNullValue())); - assertThat(converted, is(instanceOf(Iterable.class))); - final Iterable iterable = (Iterable) converted; - final Iterator iterator = iterable.iterator(); - assertThat(iterator.hasNext(), is(true)); - assertThat(iterator.next(), is(original)); - assertThat(iterator.hasNext(), is(false)); - } - - @Test - public void testConvertingIterableToIterable() throws Exception { - final SingleValueToIterableConverter converter = new SingleValueToIterableConverter(); - final Object original = Arrays.asList(1, 2, 3); - final Object converted = converter.convert( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), original); - assertThat(converted, is(original)); - } - - @Test - public void testConvertingIteratorToIterable() throws Exception { - final SingleValueToIterableConverter converter = new SingleValueToIterableConverter(); - final Object original = Arrays.asList(1, 2, 3).iterator(); - final Object converted = converter.convert( - new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), original); - assertThat(converted, is(original)); - } - -} \ No newline at end of file + @Test + public void testConvertingSingleValueToIterable() throws Exception { + final SingleValueToIterableConverter converter = new SingleValueToIterableConverter(); + final Object original = new Object(); + final Object converted = + converter.convert( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), + original); + assertThat(converted, is(notNullValue())); + assertThat(converted, is(instanceOf(Iterable.class))); + final Iterable iterable = (Iterable) converted; + final Iterator iterator = iterable.iterator(); + assertThat(iterator.hasNext(), is(true)); + assertThat(iterator.next(), is(original)); + assertThat(iterator.hasNext(), is(false)); + } + + @Test + public void testConvertingIterableToIterable() throws Exception { + final SingleValueToIterableConverter converter = new SingleValueToIterableConverter(); + final Object original = Arrays.asList(1, 2, 3); + final Object converted = + converter.convert( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), + original); + assertThat(converted, is(original)); + } + + @Test + public void testConvertingIteratorToIterable() throws Exception { + final SingleValueToIterableConverter converter = new SingleValueToIterableConverter(); + final Object original = Arrays.asList(1, 2, 3).iterator(); + final Object converted = + converter.convert( + new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null), + original); + assertThat(converted, is(original)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolverTest.java index 75ae5d28..3edc9269 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolverTest.java @@ -1,6 +1,10 @@ package com.mmnaseri.utils.spring.data.proxy.impl.resolvers; -import com.mmnaseri.utils.spring.data.domain.impl.*; +import com.mmnaseri.utils.spring.data.domain.impl.DefaultOperatorContext; +import com.mmnaseri.utils.spring.data.domain.impl.DescribedDataStoreOperation; +import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata; +import com.mmnaseri.utils.spring.data.domain.impl.MethodInvocationDataStoreOperation; +import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor; import com.mmnaseri.utils.spring.data.error.DataOperationDefinitionException; import com.mmnaseri.utils.spring.data.error.UnknownDataOperationException; import com.mmnaseri.utils.spring.data.proxy.TypeMapping; @@ -17,7 +21,9 @@ import java.util.ArrayList; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -25,50 +31,56 @@ */ public class DefaultDataOperationResolverTest { - private DefaultDataOperationResolver resolver; + private DefaultDataOperationResolver resolver; - @BeforeMethod - public void setUp() { - final ArrayList> mappings = new ArrayList<>(); - mappings.add(new ImmutableTypeMapping<>(MappedType.class, new MappedType())); - final MethodQueryDescriptionExtractor descriptionExtractor = new MethodQueryDescriptionExtractor( - new DefaultOperatorContext()); - final ImmutableRepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - Person.class, - SampleMappedRepository.class, - "id"); - final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry(); - resolver = new DefaultDataOperationResolver(mappings, descriptionExtractor, repositoryMetadata, - functionRegistry, new DefaultRepositoryFactoryConfiguration()); - } + @BeforeMethod + public void setUp() { + final ArrayList> mappings = new ArrayList<>(); + mappings.add(new ImmutableTypeMapping<>(MappedType.class, new MappedType())); + final MethodQueryDescriptionExtractor descriptionExtractor = + new MethodQueryDescriptionExtractor(new DefaultOperatorContext()); + final ImmutableRepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, Person.class, SampleMappedRepository.class, "id"); + final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry(); + resolver = + new DefaultDataOperationResolver( + mappings, + descriptionExtractor, + repositoryMetadata, + functionRegistry, + new DefaultRepositoryFactoryConfiguration()); + } - @Test - public void testLookingForMethodThatHasMapping() throws Exception { - final DataStoreOperation operation = resolver.resolve( - SampleMappedRepository.class.getMethod("mappedSignature", String.class)); - assertThat(operation, is(notNullValue())); - assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); - final MethodInvocationDataStoreOperation invocation = (MethodInvocationDataStoreOperation) operation; - assertThat(invocation.getInstance(), is(instanceOf(MappedType.class))); - assertThat(invocation.getMethod(), is(MappedType.class.getMethod("mappedSignature", CharSequence.class))); - } + @Test + public void testLookingForMethodThatHasMapping() throws Exception { + final DataStoreOperation operation = + resolver.resolve(SampleMappedRepository.class.getMethod("mappedSignature", String.class)); + assertThat(operation, is(notNullValue())); + assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); + final MethodInvocationDataStoreOperation invocation = + (MethodInvocationDataStoreOperation) operation; + assertThat(invocation.getInstance(), is(instanceOf(MappedType.class))); + assertThat( + invocation.getMethod(), + is(MappedType.class.getMethod("mappedSignature", CharSequence.class))); + } - @Test - public void testLookingForQueryMethod() throws Exception { - final DataStoreOperation operation = resolver.resolve( - SampleMappedRepository.class.getMethod("findByFirstName", String.class)); - assertThat(operation, is(notNullValue())); - assertThat(operation, is(instanceOf(DescribedDataStoreOperation.class))); - } + @Test + public void testLookingForQueryMethod() throws Exception { + final DataStoreOperation operation = + resolver.resolve(SampleMappedRepository.class.getMethod("findByFirstName", String.class)); + assertThat(operation, is(notNullValue())); + assertThat(operation, is(instanceOf(DescribedDataStoreOperation.class))); + } - @Test(expectedExceptions = UnknownDataOperationException.class) - public void testLookingForUnmappedMethod() throws Exception { - resolver.resolve(SampleMappedRepository.class.getMethod("nativeMethod")); - } + @Test(expectedExceptions = UnknownDataOperationException.class) + public void testLookingForUnmappedMethod() throws Exception { + resolver.resolve(SampleMappedRepository.class.getMethod("nativeMethod")); + } - @Test(expectedExceptions = DataOperationDefinitionException.class) - public void testLookingForMalformedMethod() throws Exception { - resolver.resolve(SampleMappedRepository.class.getMethod("normalMethodBy")); - } - -} \ No newline at end of file + @Test(expectedExceptions = DataOperationDefinitionException.class) + public void testLookingForMalformedMethod() throws Exception { + resolver.resolve(SampleMappedRepository.class.getMethod("normalMethodBy")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolverTest.java index 717ec208..2bd21704 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolverTest.java @@ -7,7 +7,10 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -15,26 +18,26 @@ */ public class QueryMethodDataOperationResolverTest { - @Test - public void testThatItCallsAQueryExtractor() throws Exception { - final NoOpMethodQueryDescriptionExtractor extractor = new NoOpMethodQueryDescriptionExtractor(); - final QueryMethodDataOperationResolver resolver = new QueryMethodDataOperationResolver(extractor, null, null, - null); - assertThat(extractor.isCalled(), is(false)); - final DataStoreOperation operation = resolver.resolve( - SampleMappedRepository.class.getMethod("normalMethodBy")); - assertThat(operation, is(notNullValue())); - assertThat(operation, is(instanceOf(DescribedDataStoreOperation.class))); - assertThat(extractor.isCalled(), is(true)); - } + @Test + public void testThatItCallsAQueryExtractor() throws Exception { + final NoOpMethodQueryDescriptionExtractor extractor = new NoOpMethodQueryDescriptionExtractor(); + final QueryMethodDataOperationResolver resolver = + new QueryMethodDataOperationResolver(extractor, null, null, null); + assertThat(extractor.isCalled(), is(false)); + final DataStoreOperation operation = + resolver.resolve(SampleMappedRepository.class.getMethod("normalMethodBy")); + assertThat(operation, is(notNullValue())); + assertThat(operation, is(instanceOf(DescribedDataStoreOperation.class))); + assertThat(extractor.isCalled(), is(true)); + } - @Test - public void testMethodThatIsAnnotatedWithVendorQuery() throws Exception { - final QueryMethodDataOperationResolver resolver = new QueryMethodDataOperationResolver( - new NoOpMethodQueryDescriptionExtractor(), null, null, null); - final DataStoreOperation method = resolver.resolve( - SampleMappedRepository.class.getMethod("nativeMethod")); - assertThat(method, is(nullValue())); - } - -} \ No newline at end of file + @Test + public void testMethodThatIsAnnotatedWithVendorQuery() throws Exception { + final QueryMethodDataOperationResolver resolver = + new QueryMethodDataOperationResolver( + new NoOpMethodQueryDescriptionExtractor(), null, null, null); + final DataStoreOperation method = + resolver.resolve(SampleMappedRepository.class.getMethod("nativeMethod")); + assertThat(method, is(nullValue())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolverTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolverTest.java index 40e053ff..c688b19f 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolverTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolverTest.java @@ -3,7 +3,11 @@ import com.mmnaseri.utils.spring.data.domain.impl.MethodInvocationDataStoreOperation; import com.mmnaseri.utils.spring.data.proxy.TypeMapping; import com.mmnaseri.utils.spring.data.proxy.impl.ImmutableTypeMapping; -import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.*; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.ChildClass; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.ProxiedClass; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.SuperClass; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.SuperInterface; +import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.SuperInterfaceImpl; import com.mmnaseri.utils.spring.data.store.DataStoreOperation; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -12,7 +16,10 @@ import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -20,67 +27,74 @@ */ public class SignatureDataOperationResolverTest { - private SignatureDataOperationResolver resolver; + private SignatureDataOperationResolver resolver; - @BeforeMethod - public void setUp() { - final List> mappings = new ArrayList<>(); - mappings.add(new ImmutableTypeMapping<>(SuperInterface.class, new SuperInterfaceImpl())); - mappings.add(new ImmutableTypeMapping<>(ChildClass.class, new ChildClass())); - resolver = new SignatureDataOperationResolver(mappings); - } + @BeforeMethod + public void setUp() { + final List> mappings = new ArrayList<>(); + mappings.add(new ImmutableTypeMapping<>(SuperInterface.class, new SuperInterfaceImpl())); + mappings.add(new ImmutableTypeMapping<>(ChildClass.class, new ChildClass())); + resolver = new SignatureDataOperationResolver(mappings); + } - @Test - public void testLookingForExactMatchViaInterface() throws Exception { - final DataStoreOperation operation = resolver.resolve( - ProxiedClass.class.getMethod("saySomething", String.class, Double.class)); - assertThat(operation, is(notNullValue())); - assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); - final MethodInvocationDataStoreOperation invocationOperation = (MethodInvocationDataStoreOperation) operation; - assertThat(invocationOperation.getInstance(), is(instanceOf(SuperInterface.class))); - assertThat(invocationOperation.getMethod(), - is(SuperInterface.class.getMethod("saySomething", CharSequence.class, Double.class))); - } + @Test + public void testLookingForExactMatchViaInterface() throws Exception { + final DataStoreOperation operation = + resolver.resolve(ProxiedClass.class.getMethod("saySomething", String.class, Double.class)); + assertThat(operation, is(notNullValue())); + assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); + final MethodInvocationDataStoreOperation invocationOperation = + (MethodInvocationDataStoreOperation) operation; + assertThat(invocationOperation.getInstance(), is(instanceOf(SuperInterface.class))); + assertThat( + invocationOperation.getMethod(), + is(SuperInterface.class.getMethod("saySomething", CharSequence.class, Double.class))); + } - @Test - public void testLookingForExactMatchViaClass() throws Exception { - final DataStoreOperation operation = resolver.resolve( - ProxiedClass.class.getMethod("saySomething", String.class, Integer.class)); - assertThat(operation, is(notNullValue())); - assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); - final MethodInvocationDataStoreOperation invocationOperation = (MethodInvocationDataStoreOperation) operation; - assertThat(invocationOperation.getInstance(), is(instanceOf(ChildClass.class))); - assertThat(invocationOperation.getMethod(), - is(ChildClass.class.getMethod("saySomething", String.class, Integer.class))); - } + @Test + public void testLookingForExactMatchViaClass() throws Exception { + final DataStoreOperation operation = + resolver.resolve(ProxiedClass.class.getMethod("saySomething", String.class, Integer.class)); + assertThat(operation, is(notNullValue())); + assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); + final MethodInvocationDataStoreOperation invocationOperation = + (MethodInvocationDataStoreOperation) operation; + assertThat(invocationOperation.getInstance(), is(instanceOf(ChildClass.class))); + assertThat( + invocationOperation.getMethod(), + is(ChildClass.class.getMethod("saySomething", String.class, Integer.class))); + } - @Test - public void testLookingForMatchViaSuperClassSuperSignature() throws Exception { - final DataStoreOperation operation = resolver.resolve( - ProxiedClass.class.getMethod("saySomething", String.class, float.class)); - assertThat(operation, is(notNullValue())); - assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); - final MethodInvocationDataStoreOperation invocationOperation = (MethodInvocationDataStoreOperation) operation; - assertThat(invocationOperation.getInstance(), is(instanceOf(SuperClass.class))); - assertThat(invocationOperation.getMethod(), - is(SuperClass.class.getMethod("saySomething", CharSequence.class, Number.class))); - } + @Test + public void testLookingForMatchViaSuperClassSuperSignature() throws Exception { + final DataStoreOperation operation = + resolver.resolve(ProxiedClass.class.getMethod("saySomething", String.class, float.class)); + assertThat(operation, is(notNullValue())); + assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); + final MethodInvocationDataStoreOperation invocationOperation = + (MethodInvocationDataStoreOperation) operation; + assertThat(invocationOperation.getInstance(), is(instanceOf(SuperClass.class))); + assertThat( + invocationOperation.getMethod(), + is(SuperClass.class.getMethod("saySomething", CharSequence.class, Number.class))); + } - @Test - public void testLookingForMaskedMethod() throws Exception { - final DataStoreOperation operation = resolver.resolve(ProxiedClass.class.getMethod("doSomething")); - assertThat(operation, is(notNullValue())); - assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); - final MethodInvocationDataStoreOperation invocationOperation = (MethodInvocationDataStoreOperation) operation; - assertThat(invocationOperation.getInstance(), is(instanceOf(SuperInterface.class))); - assertThat(invocationOperation.getMethod(), is(SuperInterface.class.getMethod("doSomething"))); - } + @Test + public void testLookingForMaskedMethod() throws Exception { + final DataStoreOperation operation = + resolver.resolve(ProxiedClass.class.getMethod("doSomething")); + assertThat(operation, is(notNullValue())); + assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class))); + final MethodInvocationDataStoreOperation invocationOperation = + (MethodInvocationDataStoreOperation) operation; + assertThat(invocationOperation.getInstance(), is(instanceOf(SuperInterface.class))); + assertThat(invocationOperation.getMethod(), is(SuperInterface.class.getMethod("doSomething"))); + } - @Test - public void testLookingForMethodThatDoesNotMatch() throws Exception { - final DataStoreOperation resolved = resolver.resolve( - ProxiedClass.class.getMethod("saySomething", String.class, Boolean.class)); - assertThat(resolved, is(nullValue())); - } - -} \ No newline at end of file + @Test + public void testLookingForMethodThatDoesNotMatch() throws Exception { + final DataStoreOperation resolved = + resolver.resolve(ProxiedClass.class.getMethod("saySomething", String.class, Boolean.class)); + assertThat(resolved, is(nullValue())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunctionTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunctionTest.java index f6e1cf7d..8c07c9d5 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunctionTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunctionTest.java @@ -16,21 +16,20 @@ */ public class CountDataFunctionTest { - @Test(expectedExceptions = InvalidArgumentException.class) - public void testThatNullSelectionResultsInError() { - final DataFunction function = new CountDataFunction(); - function.apply(null, null, null, null); - } + @Test(expectedExceptions = InvalidArgumentException.class) + public void testThatNullSelectionResultsInError() { + final DataFunction function = new CountDataFunction(); + function.apply(null, null, null, null); + } - @Test - public void testThatItReflectsTheSizeOfTheCollection() { - final DataFunction function = new CountDataFunction(); - final List selection = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - final Long count = function.apply(null, null, null, selection); - assertThat(count, Matchers.is((long) selection.size())); - selection.add(new Object()); - } + @Test + public void testThatItReflectsTheSizeOfTheCollection() { + final DataFunction function = new CountDataFunction(); + final List selection = new LinkedList<>(); + for (int i = 0; i < 10; i++) { + final Long count = function.apply(null, null, null, selection); + assertThat(count, Matchers.is((long) selection.size())); + selection.add(new Object()); } - -} \ No newline at end of file + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistryTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistryTest.java index 7d454d03..f01684e4 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistryTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistryTest.java @@ -11,7 +11,10 @@ import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isIn; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -19,39 +22,38 @@ */ public class DefaultDataFunctionRegistryTest { - @Test - public void testDefaultFunctions() { - final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry(); - final Set functions = registry.getFunctions(); - final Set expected = new HashSet<>(Arrays.asList("count", "delete")); - assertThat(functions, hasSize(2)); - for (String function : functions) { - assertThat(function, isIn(expected)); - expected.remove(function); - } - assertThat(expected, is(Matchers.empty())); + @Test + public void testDefaultFunctions() { + final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry(); + final Set functions = registry.getFunctions(); + final Set expected = new HashSet<>(Arrays.asList("count", "delete")); + assertThat(functions, hasSize(2)); + for (String function : functions) { + assertThat(function, isIn(expected)); + expected.remove(function); } - - @Test(expectedExceptions = FunctionNotFoundException.class) - public void testNonExistentFunction() { - final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry(); - registry.getFunction("xyz"); - } - - @Test(expectedExceptions = DuplicateFunctionException.class) - public void testRegisteringDuplicateFunction() { - final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry(); - registry.register("count", new DeleteDataFunction()); - } - - @Test - public void testRegisteringLegitimateFunction() { - final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry(); - final String item = "size"; - final DataFunction function = new CountDataFunction(); - registry.register(item, function); - assertThat(registry.getFunctions(), hasItem(item)); - assertThat(registry.getFunction(item), is(function)); - } - -} \ No newline at end of file + assertThat(expected, is(Matchers.empty())); + } + + @Test(expectedExceptions = FunctionNotFoundException.class) + public void testNonExistentFunction() { + final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry(); + registry.getFunction("xyz"); + } + + @Test(expectedExceptions = DuplicateFunctionException.class) + public void testRegisteringDuplicateFunction() { + final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry(); + registry.register("count", new DeleteDataFunction()); + } + + @Test + public void testRegisteringLegitimateFunction() { + final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry(); + final String item = "size"; + final DataFunction function = new CountDataFunction(); + registry.register(item, function); + assertThat(registry.getFunctions(), hasItem(item)); + assertThat(registry.getFunction(item), is(function)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptorTest.java index 232fe4be..bd28ed48 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptorTest.java @@ -25,107 +25,147 @@ */ public class DefaultQueryDescriptorTest { - private OperatorContext operatorContext; + private OperatorContext operatorContext; - @BeforeMethod - public void setUp() { - operatorContext = new DefaultOperatorContext(); - } + @BeforeMethod + public void setUp() { + operatorContext = new DefaultOperatorContext(); + } - @Test - public void testGettingPageWhenPageExtractorIsNull() { - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, null, null, - null); - assertThat(descriptor.getPage(new ImmutableInvocation(null, new Object[]{})), is(nullValue())); - } + @Test + public void testGettingPageWhenPageExtractorIsNull() { + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, null, null, null); + assertThat(descriptor.getPage(new ImmutableInvocation(null, new Object[] {})), is(nullValue())); + } - @Test - public void testGettingSortWhenSortExtractorIsNull() { - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, null, null, - null); - assertThat(descriptor.getSort(new ImmutableInvocation(null, new Object[]{})), is(nullValue())); - } + @Test + public void testGettingSortWhenSortExtractorIsNull() { + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, null, null, null); + assertThat(descriptor.getSort(new ImmutableInvocation(null, new Object[] {})), is(nullValue())); + } - @Test - public void testMatchingWhenThereAreNotAnyConditions() { - final List> branches = Collections.emptyList(); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, - null); - assertThat(descriptor.matches(null, new ImmutableInvocation(null, null)), is(false)); - assertThat(descriptor.matches(new Object(), new ImmutableInvocation(null, null)), is(true)); - } + @Test + public void testMatchingWhenThereAreNotAnyConditions() { + final List> branches = Collections.emptyList(); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null); + assertThat(descriptor.matches(null, new ImmutableInvocation(null, null)), is(false)); + assertThat(descriptor.matches(new Object(), new ImmutableInvocation(null, null)), is(true)); + } - @Test - public void testThatEachBranchIsConjunctive() { - final List> branches = new ArrayList<>(); - final ArrayList branch = new ArrayList<>(); - branches.add(branch); - //getByFirstNameAndLastName(:0, :1) - branch.add(new ImmutableParameter("firstName", Collections.emptySet(), new int[]{0}, - operatorContext.getBySuffix("Equals"))); - branch.add(new ImmutableParameter("lastName", Collections.emptySet(), new int[]{1}, - operatorContext.getBySuffix("IsNot"))); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, - null); - final Person person = new Person().setFirstName("X").setLastName("Y"); - assertThat(descriptor.matches(person, new ImmutableInvocation(null, new Object[]{"A", "Y"})), is(false)); - assertThat(descriptor.matches(person, new ImmutableInvocation(null, new Object[]{"X", "Y"})), is(false)); - assertThat(descriptor.matches(person, new ImmutableInvocation(null, new Object[]{"A", "B"})), is(false)); - assertThat(descriptor.matches(person, new ImmutableInvocation(null, new Object[]{"X", "B"})), is(true)); - } + @Test + public void testThatEachBranchIsConjunctive() { + final List> branches = new ArrayList<>(); + final ArrayList branch = new ArrayList<>(); + branches.add(branch); + // getByFirstNameAndLastName(:0, :1) + branch.add( + new ImmutableParameter( + "firstName", + Collections.emptySet(), + new int[] {0}, + operatorContext.getBySuffix("Equals"))); + branch.add( + new ImmutableParameter( + "lastName", + Collections.emptySet(), + new int[] {1}, + operatorContext.getBySuffix("IsNot"))); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null); + final Person person = new Person().setFirstName("X").setLastName("Y"); + assertThat( + descriptor.matches(person, new ImmutableInvocation(null, new Object[] {"A", "Y"})), + is(false)); + assertThat( + descriptor.matches(person, new ImmutableInvocation(null, new Object[] {"X", "Y"})), + is(false)); + assertThat( + descriptor.matches(person, new ImmutableInvocation(null, new Object[] {"A", "B"})), + is(false)); + assertThat( + descriptor.matches(person, new ImmutableInvocation(null, new Object[] {"X", "B"})), + is(true)); + } - @Test - public void testThatBranchesAreDisjunctive() { - final List> branches = new ArrayList<>(); - final ArrayList first = new ArrayList<>(); - final ArrayList second = new ArrayList<>(); - final ArrayList third = new ArrayList<>(); - branches.add(first); - branches.add(second); - branches.add(third); - //getByFirstNameAndLastNameOrIdOrAddressCityAndAddressStreet(:0, :1, :2, :3, :4) - first.add(new ImmutableParameter("firstName", Collections.emptySet(), new int[]{0}, - operatorContext.getBySuffix("Equals"))); - first.add(new ImmutableParameter("lastName", Collections.emptySet(), new int[]{1}, - operatorContext.getBySuffix("Equals"))); - second.add(new ImmutableParameter("id", Collections.emptySet(), new int[]{2}, - operatorContext.getBySuffix("Equals"))); - third.add(new ImmutableParameter("address.city", Collections.emptySet(), new int[]{3}, - operatorContext.getBySuffix("Equals"))); - third.add(new ImmutableParameter("address.street", Collections.emptySet(), new int[]{4}, - operatorContext.getBySuffix("Equals"))); - final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, - null); - final Person person = new Person().setId("1").setFirstName("X").setLastName("Y").setAddress( - new Address().setCity("Shiraz").setStreet("Chaharbagh")); - assertThat(descriptor.matches(person, - new ImmutableInvocation(null, new Object[]{"X", "Y", "2", "Mashad", "Reza"})), - is(true)); //first branch - assertThat(descriptor.matches(person, - new ImmutableInvocation(null, new Object[]{"A", "B", "1", "Mashad", "Reza"})), - is(true)); //second branch - assertThat(descriptor.matches(person, new ImmutableInvocation(null, new Object[]{"A", "B", "3", "Shiraz", - "Chaharbagh"})), - is(true)); //third branch - assertThat(descriptor.matches(person, - new ImmutableInvocation(null, new Object[]{"A", "B", "3", "Tehran", "Tajrish"})), - is(false)); //none - } + @Test + public void testThatBranchesAreDisjunctive() { + final List> branches = new ArrayList<>(); + final ArrayList first = new ArrayList<>(); + final ArrayList second = new ArrayList<>(); + final ArrayList third = new ArrayList<>(); + branches.add(first); + branches.add(second); + branches.add(third); + // getByFirstNameAndLastNameOrIdOrAddressCityAndAddressStreet(:0, :1, :2, :3, :4) + first.add( + new ImmutableParameter( + "firstName", + Collections.emptySet(), + new int[] {0}, + operatorContext.getBySuffix("Equals"))); + first.add( + new ImmutableParameter( + "lastName", + Collections.emptySet(), + new int[] {1}, + operatorContext.getBySuffix("Equals"))); + second.add( + new ImmutableParameter( + "id", Collections.emptySet(), new int[] {2}, operatorContext.getBySuffix("Equals"))); + third.add( + new ImmutableParameter( + "address.city", + Collections.emptySet(), + new int[] {3}, + operatorContext.getBySuffix("Equals"))); + third.add( + new ImmutableParameter( + "address.street", + Collections.emptySet(), + new int[] {4}, + operatorContext.getBySuffix("Equals"))); + final DefaultQueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null); + final Person person = + new Person() + .setId("1") + .setFirstName("X") + .setLastName("Y") + .setAddress(new Address().setCity("Shiraz").setStreet("Chaharbagh")); + assertThat( + descriptor.matches( + person, new ImmutableInvocation(null, new Object[] {"X", "Y", "2", "Mashad", "Reza"})), + is(true)); // first branch + assertThat( + descriptor.matches( + person, new ImmutableInvocation(null, new Object[] {"A", "B", "1", "Mashad", "Reza"})), + is(true)); // second branch + assertThat( + descriptor.matches( + person, + new ImmutableInvocation(null, new Object[] {"A", "B", "3", "Shiraz", "Chaharbagh"})), + is(true)); // third branch + assertThat( + descriptor.matches( + person, + new ImmutableInvocation(null, new Object[] {"A", "B", "3", "Tehran", "Tajrish"})), + is(false)); // none + } - @Test - public void testToString() { - final QueryDescriptor noFunctionNotDistinct = new DefaultQueryDescriptor(false, null, 0, null, null, - Collections.emptyList(), - null, null); - assertThat(noFunctionNotDistinct.toString(), is("[]")); - final QueryDescriptor functionNotDistinct = new DefaultQueryDescriptor(false, "xyz", 0, null, null, - Collections.emptyList(), - null, null); - assertThat(functionNotDistinct.toString(), is("xyz []")); - final QueryDescriptor functionDistinct = new DefaultQueryDescriptor(true, "xyz", 0, null, null, - Collections.emptyList(), - null, null); - assertThat(functionDistinct.toString(), is("xyz distinct []")); - } - -} \ No newline at end of file + @Test + public void testToString() { + final QueryDescriptor noFunctionNotDistinct = + new DefaultQueryDescriptor(false, null, 0, null, null, Collections.emptyList(), null, null); + assertThat(noFunctionNotDistinct.toString(), is("[]")); + final QueryDescriptor functionNotDistinct = + new DefaultQueryDescriptor( + false, "xyz", 0, null, null, Collections.emptyList(), null, null); + assertThat(functionNotDistinct.toString(), is("xyz []")); + final QueryDescriptor functionDistinct = + new DefaultQueryDescriptor(true, "xyz", 0, null, null, Collections.emptyList(), null, null); + assertThat(functionDistinct.toString(), is("xyz distinct []")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunctionTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunctionTest.java index bb729547..1de214f7 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunctionTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunctionTest.java @@ -14,11 +14,17 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; import java.util.concurrent.atomic.AtomicLong; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isIn; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -26,120 +32,129 @@ */ public class DeleteDataFunctionTest { - private QueryDescriptor query; - private DeleteDataFunction function; - private SpyingDataStore dataStore; + private QueryDescriptor query; + private DeleteDataFunction function; + private SpyingDataStore dataStore; - @BeforeMethod - public void setUp() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, Person.class, null, - "id"); - final MemoryDataStore delegate = new MemoryDataStore<>(Person.class); - query = new DefaultQueryDescriptor(false, null, 0, null, null, null, null, repositoryMetadata); - function = new DeleteDataFunction(); - dataStore = new SpyingDataStore<>(delegate, new AtomicLong()); - } + @BeforeMethod + public void setUp() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, Person.class, null, "id"); + final MemoryDataStore delegate = new MemoryDataStore<>(Person.class); + query = new DefaultQueryDescriptor(false, null, 0, null, null, null, null, repositoryMetadata); + function = new DeleteDataFunction(); + dataStore = new SpyingDataStore<>(delegate, new AtomicLong()); + } - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = "Data store .*") - public void testPassingNullDataStore() { - final DataFunction> function = new DeleteDataFunction(); - function.apply(null, query, null, new LinkedList<>()); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Data store .*") + public void testPassingNullDataStore() { + final DataFunction> function = new DeleteDataFunction(); + function.apply(null, query, null, new LinkedList<>()); + } - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = "Query .*") - public void testPassingNullQuery() { - final DataFunction> function = new DeleteDataFunction(); - function.apply(dataStore, null, null, new LinkedList<>()); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Query .*") + public void testPassingNullQuery() { + final DataFunction> function = new DeleteDataFunction(); + function.apply(dataStore, null, null, new LinkedList<>()); + } - @Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = "Selection .*") - public void testPassingNullSelection() { - function.apply(dataStore, query, null, null); - } + @Test( + expectedExceptions = InvalidArgumentException.class, + expectedExceptionsMessageRegExp = "Selection .*") + public void testPassingNullSelection() { + function.apply(dataStore, query, null, null); + } - @Test(expectedExceptions = DataFunctionException.class, expectedExceptionsMessageRegExp = "Failed to read .*") - public void testWrongIdentifierProperty() { - final DataFunction> function = new DeleteDataFunction(); - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, Person.class, null, - "xyz"); - final QueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, null, null, - repositoryMetadata); - function.apply(dataStore, descriptor, null, Collections.singletonList(new Person())); - } + @Test( + expectedExceptions = DataFunctionException.class, + expectedExceptionsMessageRegExp = "Failed to read .*") + public void testWrongIdentifierProperty() { + final DataFunction> function = new DeleteDataFunction(); + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, Person.class, null, "xyz"); + final QueryDescriptor descriptor = + new DefaultQueryDescriptor(false, null, 0, null, null, null, null, repositoryMetadata); + function.apply(dataStore, descriptor, null, Collections.singletonList(new Person())); + } - @Test(expectedExceptions = DataFunctionException.class, - expectedExceptionsMessageRegExp = "Cannot delete an entity without the key property being set: id") - public void testNullIdentifierValue() { - final DataFunction> function = new DeleteDataFunction(); - function.apply(dataStore, query, null, Collections.singletonList(new Person())); - } + @Test( + expectedExceptions = DataFunctionException.class, + expectedExceptionsMessageRegExp = + "Cannot delete an entity without the key property being set: id") + public void testNullIdentifierValue() { + final DataFunction> function = new DeleteDataFunction(); + function.apply(dataStore, query, null, Collections.singletonList(new Person())); + } - @Test - public void testThatItSendsRequestsToTheUnderlyingDataStore() { - final List selection = new ArrayList<>(); - selection.add(new Person().setId("1")); - selection.add(new Person().setId("2")); - function.apply(dataStore, query, null, selection); - assertThat(dataStore.getRequests(), hasSize(2)); - assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE)); - assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(selection.get(0).getId())); - assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE)); - assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(selection.get(1).getId())); - } + @Test + public void testThatItSendsRequestsToTheUnderlyingDataStore() { + final List selection = new ArrayList<>(); + selection.add(new Person().setId("1")); + selection.add(new Person().setId("2")); + function.apply(dataStore, query, null, selection); + assertThat(dataStore.getRequests(), hasSize(2)); + assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE)); + assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(selection.get(0).getId())); + assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE)); + assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(selection.get(1).getId())); + } - @Test - public void testThatItDeletesTheExactSetOfItemsSpecified() { - final List entities = new ArrayList<>(); - entities.add(new Person().setId("1")); - entities.add(new Person().setId("2")); - entities.add(new Person().setId("3")); - entities.add(new Person().setId("4")); - for (Person person : entities) { - dataStore.save(person.getId(), person); - } - dataStore.reset(); - final List selection = entities.subList(1, 3); - function.apply(dataStore, query, null, selection); - assertThat(dataStore.getRequests(), hasSize(2)); - assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE)); - assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(entities.get(1).getId())); - assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE)); - assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(entities.get(2).getId())); - assertThat(dataStore.hasKey(entities.get(0).getId()), is(true)); - assertThat(dataStore.hasKey(entities.get(1).getId()), is(false)); - assertThat(dataStore.hasKey(entities.get(2).getId()), is(false)); - assertThat(dataStore.hasKey(entities.get(3).getId()), is(true)); + @Test + public void testThatItDeletesTheExactSetOfItemsSpecified() { + final List entities = new ArrayList<>(); + entities.add(new Person().setId("1")); + entities.add(new Person().setId("2")); + entities.add(new Person().setId("3")); + entities.add(new Person().setId("4")); + for (Person person : entities) { + dataStore.save(person.getId(), person); } + dataStore.reset(); + final List selection = entities.subList(1, 3); + function.apply(dataStore, query, null, selection); + assertThat(dataStore.getRequests(), hasSize(2)); + assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE)); + assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(entities.get(1).getId())); + assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE)); + assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(entities.get(2).getId())); + assertThat(dataStore.hasKey(entities.get(0).getId()), is(true)); + assertThat(dataStore.hasKey(entities.get(1).getId()), is(false)); + assertThat(dataStore.hasKey(entities.get(2).getId()), is(false)); + assertThat(dataStore.hasKey(entities.get(3).getId()), is(true)); + } - @Test - public void testThatItReturnsTheDeletedItems() { - final List entities = new ArrayList<>(); - entities.add(new Person().setId("1")); - entities.add(new Person().setId("2")); - entities.add(new Person().setId("3")); - entities.add(new Person().setId("4")); - for (Person person : entities) { - dataStore.save(person.getId(), person); - } - dataStore.reset(); - final List selection = new ArrayList<>(entities.subList(1, 3)); - selection.add(new Person().setId("5")); - final List deleted = function.apply(dataStore, query, null, selection); - assertThat(dataStore.getRequests(), hasSize(3)); - assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE)); - assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(entities.get(1).getId())); - assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE)); - assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(entities.get(2).getId())); - assertThat(dataStore.getRequests().get(2).getOperation(), is(Operation.DELETE)); - assertThat(dataStore.getRequests().get(2).getKey(), Matchers.is(selection.get(2).getId())); - assertThat(deleted, hasSize(2)); - final List deletedIds = new ArrayList<>( - Arrays.asList(entities.get(1).getId(), entities.get(2).getId())); - for (Person person : deleted) { - assertThat(person.getId(), isIn(deletedIds)); - deletedIds.remove(person.getId()); - } - assertThat(deletedIds, is(Collections.emptyList())); + @Test + public void testThatItReturnsTheDeletedItems() { + final List entities = new ArrayList<>(); + entities.add(new Person().setId("1")); + entities.add(new Person().setId("2")); + entities.add(new Person().setId("3")); + entities.add(new Person().setId("4")); + for (Person person : entities) { + dataStore.save(person.getId(), person); } - -} \ No newline at end of file + dataStore.reset(); + final List selection = new ArrayList<>(entities.subList(1, 3)); + selection.add(new Person().setId("5")); + final List deleted = function.apply(dataStore, query, null, selection); + assertThat(dataStore.getRequests(), hasSize(3)); + assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE)); + assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(entities.get(1).getId())); + assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE)); + assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(entities.get(2).getId())); + assertThat(dataStore.getRequests().get(2).getOperation(), is(Operation.DELETE)); + assertThat(dataStore.getRequests().get(2).getKey(), Matchers.is(selection.get(2).getId())); + assertThat(deleted, hasSize(2)); + final List deletedIds = + new ArrayList<>(Arrays.asList(entities.get(1).getId(), entities.get(2).getId())); + for (Person person : deleted) { + assertThat(person.getId(), isIn(deletedIds)); + deletedIds.remove(person.getId()); + } + assertThat(deletedIds, is(Collections.emptyList())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractorTest.java index 4a7570c1..df86fdec 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractorTest.java @@ -8,7 +8,9 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -16,37 +18,36 @@ */ public class DirectSortParameterExtractorTest { - @Test(expectedExceptions = InvalidArgumentException.class) - public void testNullInvocation() { - final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0); - extractor.extract(null); - } - - @Test(expectedExceptions = InvalidArgumentException.class) - public void testPassingNullSort() { - final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0); - extractor.extract(new ImmutableInvocation(null, new Object[]{null})); - } - - @Test(expectedExceptions = InvalidArgumentException.class) - public void testPassingWrongTypeOfArgument() { - final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0); - extractor.extract(new ImmutableInvocation(null, new Object[]{new Object()})); - } - - @Test - public void testPassingSortValue() { - final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0); - final com.mmnaseri.utils.spring.data.query.Sort extracted = extractor.extract( - new ImmutableInvocation(null, new Object[]{Sort.by("a", "b")})); - assertThat(extracted, is(notNullValue())); - assertThat(extracted.getOrders(), hasSize(2)); - assertThat(extracted.getOrders().get(0).getProperty(), is("a")); - assertThat(extracted.getOrders().get(0).getDirection(), is(SortDirection.ASCENDING)); - assertThat(extracted.getOrders().get(0).getNullHandling(), is(NullHandling.DEFAULT)); - assertThat(extracted.getOrders().get(1).getProperty(), is("b")); - assertThat(extracted.getOrders().get(1).getDirection(), is(SortDirection.ASCENDING)); - assertThat(extracted.getOrders().get(1).getNullHandling(), is(NullHandling.DEFAULT)); - } - -} \ No newline at end of file + @Test(expectedExceptions = InvalidArgumentException.class) + public void testNullInvocation() { + final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0); + extractor.extract(null); + } + + @Test(expectedExceptions = InvalidArgumentException.class) + public void testPassingNullSort() { + final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0); + extractor.extract(new ImmutableInvocation(null, new Object[] {null})); + } + + @Test(expectedExceptions = InvalidArgumentException.class) + public void testPassingWrongTypeOfArgument() { + final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0); + extractor.extract(new ImmutableInvocation(null, new Object[] {new Object()})); + } + + @Test + public void testPassingSortValue() { + final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0); + final com.mmnaseri.utils.spring.data.query.Sort extracted = + extractor.extract(new ImmutableInvocation(null, new Object[] {Sort.by("a", "b")})); + assertThat(extracted, is(notNullValue())); + assertThat(extracted.getOrders(), hasSize(2)); + assertThat(extracted.getOrders().get(0).getProperty(), is("a")); + assertThat(extracted.getOrders().get(0).getDirection(), is(SortDirection.ASCENDING)); + assertThat(extracted.getOrders().get(0).getNullHandling(), is(NullHandling.DEFAULT)); + assertThat(extracted.getOrders().get(1).getProperty(), is("b")); + assertThat(extracted.getOrders().get(1).getDirection(), is(SortDirection.ASCENDING)); + assertThat(extracted.getOrders().get(1).getNullHandling(), is(NullHandling.DEFAULT)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractorTest.java index 67bd1cf9..26df55eb 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractorTest.java @@ -16,33 +16,32 @@ */ public class PageablePageParameterExtractorTest { - @Test(expectedExceptions = InvalidArgumentException.class) - public void testNullInvocation() { - final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0); - extractor.extract(null); - } - - - @Test(expectedExceptions = InvalidArgumentException.class) - public void testPassingNullValue() { - final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0); - extractor.extract(new ImmutableInvocation(null, new Object[]{null})); - } - - @Test(expectedExceptions = InvalidArgumentException.class) - public void testPassingWrongType() { - final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0); - extractor.extract(new ImmutableInvocation(null, new Object[]{new Object()})); - } - - @Test - public void testPassingPageRequest() { - final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0); - final PageRequest pageRequest = PageRequest.of(3, 7); - final Page extracted = extractor.extract(new ImmutableInvocation(null, new Object[]{pageRequest})); - assertThat(extracted, is(notNullValue())); - assertThat(extracted.getPageNumber(), is(pageRequest.getPageNumber())); - assertThat(extracted.getPageSize(), is(pageRequest.getPageSize())); - } - -} \ No newline at end of file + @Test(expectedExceptions = InvalidArgumentException.class) + public void testNullInvocation() { + final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0); + extractor.extract(null); + } + + @Test(expectedExceptions = InvalidArgumentException.class) + public void testPassingNullValue() { + final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0); + extractor.extract(new ImmutableInvocation(null, new Object[] {null})); + } + + @Test(expectedExceptions = InvalidArgumentException.class) + public void testPassingWrongType() { + final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0); + extractor.extract(new ImmutableInvocation(null, new Object[] {new Object()})); + } + + @Test + public void testPassingPageRequest() { + final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0); + final PageRequest pageRequest = PageRequest.of(3, 7); + final Page extracted = + extractor.extract(new ImmutableInvocation(null, new Object[] {pageRequest})); + assertThat(extracted, is(notNullValue())); + assertThat(extracted.getPageNumber(), is(pageRequest.getPageNumber())); + assertThat(extracted.getPageSize(), is(pageRequest.getPageSize())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractorTest.java index 23cf52d2..55e74cdd 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractorTest.java @@ -9,7 +9,9 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -17,45 +19,50 @@ */ public class PageableSortParameterExtractorTest { - @Test(expectedExceptions = InvalidArgumentException.class) - public void testNullInvocation() { - final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); - extractor.extract(null); - } - - - @Test(expectedExceptions = InvalidArgumentException.class) - public void testPassingNullValue() { - final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); - extractor.extract(new ImmutableInvocation(null, new Object[]{null})); - } - - @Test(expectedExceptions = InvalidArgumentException.class) - public void testPassingWrongType() { - final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); - extractor.extract(new ImmutableInvocation(null, new Object[]{new Object()})); - } - - @Test - public void testPassingPageableWithNullSort() { - final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); - final Sort extracted = extractor.extract(new ImmutableInvocation(null, new Object[]{PageRequest.of(0, 1)})); - assertThat(extracted instanceof ImmutableSort, is(true)); - } - - @Test - public void testPassingPageableWithNullProperSort() { - final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); - final Sort extracted = extractor.extract(new ImmutableInvocation(null, new Object[]{ - PageRequest.of(0, 1, org.springframework.data.domain.Sort.Direction.DESC, "a", "b")})); - assertThat(extracted, is(notNullValue())); - assertThat(extracted.getOrders(), hasSize(2)); - assertThat(extracted.getOrders().get(0).getProperty(), is("a")); - assertThat(extracted.getOrders().get(0).getDirection(), is(SortDirection.DESCENDING)); - assertThat(extracted.getOrders().get(0).getNullHandling(), is(NullHandling.DEFAULT)); - assertThat(extracted.getOrders().get(1).getProperty(), is("b")); - assertThat(extracted.getOrders().get(1).getDirection(), is(SortDirection.DESCENDING)); - assertThat(extracted.getOrders().get(1).getNullHandling(), is(NullHandling.DEFAULT)); - } - -} \ No newline at end of file + @Test(expectedExceptions = InvalidArgumentException.class) + public void testNullInvocation() { + final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); + extractor.extract(null); + } + + @Test(expectedExceptions = InvalidArgumentException.class) + public void testPassingNullValue() { + final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); + extractor.extract(new ImmutableInvocation(null, new Object[] {null})); + } + + @Test(expectedExceptions = InvalidArgumentException.class) + public void testPassingWrongType() { + final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); + extractor.extract(new ImmutableInvocation(null, new Object[] {new Object()})); + } + + @Test + public void testPassingPageableWithNullSort() { + final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); + final Sort extracted = + extractor.extract(new ImmutableInvocation(null, new Object[] {PageRequest.of(0, 1)})); + assertThat(extracted instanceof ImmutableSort, is(true)); + } + + @Test + public void testPassingPageableWithNullProperSort() { + final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0); + final Sort extracted = + extractor.extract( + new ImmutableInvocation( + null, + new Object[] { + PageRequest.of( + 0, 1, org.springframework.data.domain.Sort.Direction.DESC, "a", "b") + })); + assertThat(extracted, is(notNullValue())); + assertThat(extracted.getOrders(), hasSize(2)); + assertThat(extracted.getOrders().get(0).getProperty(), is("a")); + assertThat(extracted.getOrders().get(0).getDirection(), is(SortDirection.DESCENDING)); + assertThat(extracted.getOrders().get(0).getNullHandling(), is(NullHandling.DEFAULT)); + assertThat(extracted.getOrders().get(1).getProperty(), is("b")); + assertThat(extracted.getOrders().get(1).getDirection(), is(SortDirection.DESCENDING)); + assertThat(extracted.getOrders().get(1).getNullHandling(), is(NullHandling.DEFAULT)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractorTest.java index 89412f08..2be21c14 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractorTest.java @@ -17,23 +17,22 @@ */ public class WrappedSortParameterExtractorTest { - @Test(expectedExceptions = RepositoryDefinitionException.class) - public void testPassingNull() { - new WrappedSortParameterExtractor(null); - } - - @Test(expectedExceptions = InvalidArgumentException.class) - public void testNullInvocation() { - final WrappedSortParameterExtractor extractor = new WrappedSortParameterExtractor( - new ImmutableSort(new ArrayList<>())); - extractor.extract(null); - } - - @Test - public void testIdentity() { - final Sort sort = new ImmutableSort(new ArrayList<>()); - final WrappedSortParameterExtractor extractor = new WrappedSortParameterExtractor(sort); - assertThat(extractor.extract(new ImmutableInvocation(null, new Object[]{})), is(sort)); - } - -} \ No newline at end of file + @Test(expectedExceptions = RepositoryDefinitionException.class) + public void testPassingNull() { + new WrappedSortParameterExtractor(null); + } + + @Test(expectedExceptions = InvalidArgumentException.class) + public void testNullInvocation() { + final WrappedSortParameterExtractor extractor = + new WrappedSortParameterExtractor(new ImmutableSort(new ArrayList<>())); + extractor.extract(null); + } + + @Test + public void testIdentity() { + final Sort sort = new ImmutableSort(new ArrayList<>()); + final WrappedSortParameterExtractor extractor = new WrappedSortParameterExtractor(sort); + assertThat(extractor.extract(new ImmutableInvocation(null, new Object[] {})), is(sort)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryDslPredicateExecutorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryDslPredicateExecutorTest.java index 3c5d63f8..0e1ca05f 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryDslPredicateExecutorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/repository/DefaultQueryDslPredicateExecutorTest.java @@ -25,8 +25,6 @@ * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (4/28/16) */ -@SuppressWarnings("deprecation") -@Ignore public class DefaultQueryDslPredicateExecutorTest { private MemoryDataStore dataStore; diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListenerTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListenerTest.java index 40fe832c..fb9cf865 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListenerTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListenerTest.java @@ -12,7 +12,11 @@ import static com.mmnaseri.utils.spring.data.sample.usecases.store.SampleAuditorAware.AUDITOR; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -20,84 +24,84 @@ */ public class AuditDataEventListenerTest { - @Test - public void testBeforeInsertForImplicitAuditing() { - final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware()); - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - ImplicitlyAuditableEntity.class, - null, "id"); - final ImplicitlyAuditableEntity entity = new ImplicitlyAuditableEntity(); - final Date before = new Date(); - listener.onEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, null, entity)); - final Date after = new Date(); - assertThat(entity.getCreatedBy(), is(notNullValue())); - assertThat(entity.getCreatedBy(), is(AUDITOR)); - assertThat(entity.getCreatedDate(), is(notNullValue())); - assertThat(entity.getCreatedDate().getTime(), is(greaterThanOrEqualTo(before.getTime()))); - assertThat(entity.getCreatedDate().getTime(), is(lessThanOrEqualTo(after.getTime()))); - assertThat(entity.getLastModifiedDate(), is(nullValue())); - assertThat(entity.getLastModifiedBy(), is(nullValue())); - } + @Test + public void testBeforeInsertForImplicitAuditing() { + final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware()); + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, ImplicitlyAuditableEntity.class, null, "id"); + final ImplicitlyAuditableEntity entity = new ImplicitlyAuditableEntity(); + final Date before = new Date(); + listener.onEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, null, entity)); + final Date after = new Date(); + assertThat(entity.getCreatedBy(), is(notNullValue())); + assertThat(entity.getCreatedBy(), is(AUDITOR)); + assertThat(entity.getCreatedDate(), is(notNullValue())); + assertThat(entity.getCreatedDate().getTime(), is(greaterThanOrEqualTo(before.getTime()))); + assertThat(entity.getCreatedDate().getTime(), is(lessThanOrEqualTo(after.getTime()))); + assertThat(entity.getLastModifiedDate(), is(nullValue())); + assertThat(entity.getLastModifiedBy(), is(nullValue())); + } - @Test - public void testBeforeUpdateForImplicitAuditing() { - final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware()); - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - ImplicitlyAuditableEntity.class, - null, "id"); - final ImplicitlyAuditableEntity entity = new ImplicitlyAuditableEntity(); - final Date before = new Date(); - listener.onEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, null, entity)); - final Date after = new Date(); - assertThat(entity.getLastModifiedBy(), is(notNullValue())); - assertThat(entity.getLastModifiedBy(), is(AUDITOR)); - assertThat(entity.getLastModifiedDate(), is(notNullValue())); - assertThat(entity.getLastModifiedDate().getTime(), is(greaterThanOrEqualTo(before.getTime()))); - assertThat(entity.getLastModifiedDate().getTime(), is(lessThanOrEqualTo(after.getTime()))); - assertThat(entity.getCreatedDate(), is(nullValue())); - assertThat(entity.getCreatedBy(), is(nullValue())); - } + @Test + public void testBeforeUpdateForImplicitAuditing() { + final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware()); + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, ImplicitlyAuditableEntity.class, null, "id"); + final ImplicitlyAuditableEntity entity = new ImplicitlyAuditableEntity(); + final Date before = new Date(); + listener.onEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, null, entity)); + final Date after = new Date(); + assertThat(entity.getLastModifiedBy(), is(notNullValue())); + assertThat(entity.getLastModifiedBy(), is(AUDITOR)); + assertThat(entity.getLastModifiedDate(), is(notNullValue())); + assertThat(entity.getLastModifiedDate().getTime(), is(greaterThanOrEqualTo(before.getTime()))); + assertThat(entity.getLastModifiedDate().getTime(), is(lessThanOrEqualTo(after.getTime()))); + assertThat(entity.getCreatedDate(), is(nullValue())); + assertThat(entity.getCreatedBy(), is(nullValue())); + } - @Test - public void testBeforeInsertForExplicitAuditing() { - final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware()); - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - AuditableEntity.class, null, - "id"); - final AuditableEntity entity = new AuditableEntity(); - final Date before = new Date(); - listener.onEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, null, entity)); - final Date after = new Date(); - assertThat(entity.getCreatedBy().isPresent(), is(true)); - assertThat(entity.getCreatedBy().get(), is(notNullValue())); - assertThat(entity.getCreatedBy().get(), is(AUDITOR)); - assertThat(entity.getCreatedDate().isPresent(), is(true)); - assertThat(entity.getCreatedDate().get(), is(notNullValue())); - assertThat(entity.getCreatedDate().get().toEpochMilli(), is(greaterThanOrEqualTo(before.getTime()))); - assertThat(entity.getCreatedDate().get().toEpochMilli(), is(lessThanOrEqualTo(after.getTime()))); - assertThat(entity.getLastModifiedDate(), is(Optional.empty())); - assertThat(entity.getLastModifiedBy(), is(Optional.empty())); - } + @Test + public void testBeforeInsertForExplicitAuditing() { + final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware()); + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, AuditableEntity.class, null, "id"); + final AuditableEntity entity = new AuditableEntity(); + final Date before = new Date(); + listener.onEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, null, entity)); + final Date after = new Date(); + assertThat(entity.getCreatedBy().isPresent(), is(true)); + assertThat(entity.getCreatedBy().get(), is(notNullValue())); + assertThat(entity.getCreatedBy().get(), is(AUDITOR)); + assertThat(entity.getCreatedDate().isPresent(), is(true)); + assertThat(entity.getCreatedDate().get(), is(notNullValue())); + assertThat( + entity.getCreatedDate().get().toEpochMilli(), is(greaterThanOrEqualTo(before.getTime()))); + assertThat( + entity.getCreatedDate().get().toEpochMilli(), is(lessThanOrEqualTo(after.getTime()))); + assertThat(entity.getLastModifiedDate(), is(Optional.empty())); + assertThat(entity.getLastModifiedBy(), is(Optional.empty())); + } - @Test - public void testBeforeUpdateForExplicitAuditing() { - final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware()); - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - AuditableEntity.class, null, - "id"); - final AuditableEntity entity = new AuditableEntity(); - final Date before = new Date(); - listener.onEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, null, entity)); - final Date after = new Date(); - assertThat(entity.getLastModifiedBy().isPresent(), is(true)); - assertThat(entity.getLastModifiedBy().get(), is(notNullValue())); - assertThat(entity.getLastModifiedBy().get(), is(AUDITOR)); - assertThat(entity.getLastModifiedDate().isPresent(), is(true)); - assertThat(entity.getLastModifiedDate().get(), is(notNullValue())); - assertThat(entity.getLastModifiedDate().get().toEpochMilli(), is(greaterThanOrEqualTo(before.getTime()))); - assertThat(entity.getLastModifiedDate().get().toEpochMilli(), is(lessThanOrEqualTo(after.getTime()))); - assertThat(entity.getCreatedDate(), is(Optional.empty())); - assertThat(entity.getCreatedBy(), is(Optional.empty())); - } - -} \ No newline at end of file + @Test + public void testBeforeUpdateForExplicitAuditing() { + final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware()); + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, AuditableEntity.class, null, "id"); + final AuditableEntity entity = new AuditableEntity(); + final Date before = new Date(); + listener.onEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, null, entity)); + final Date after = new Date(); + assertThat(entity.getLastModifiedBy().isPresent(), is(true)); + assertThat(entity.getLastModifiedBy().get(), is(notNullValue())); + assertThat(entity.getLastModifiedBy().get(), is(AUDITOR)); + assertThat(entity.getLastModifiedDate().isPresent(), is(true)); + assertThat(entity.getLastModifiedDate().get(), is(notNullValue())); + assertThat( + entity.getLastModifiedDate().get().toEpochMilli(), + is(greaterThanOrEqualTo(before.getTime()))); + assertThat( + entity.getLastModifiedDate().get().toEpochMilli(), is(lessThanOrEqualTo(after.getTime()))); + assertThat(entity.getCreatedDate(), is(Optional.empty())); + assertThat(entity.getCreatedBy(), is(Optional.empty())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapperTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapperTest.java index e18e07fe..752dd1c8 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapperTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapperTest.java @@ -2,7 +2,16 @@ import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata; import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata; -import com.mmnaseri.utils.spring.data.sample.models.*; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithCreatedBy; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithCreatedDate; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithDateTimeLastModifiedDate; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithFinalCreatedBy; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithLastModifiedBy; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithSqlDateLastModifiedDate; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithTimeLastModifiedDate; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithTimestampDateLastModifiedDate; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithUtilDateLastModifiedDate; +import com.mmnaseri.utils.spring.data.sample.models.EntityWithWriteOnlyCreatedBy; import com.mmnaseri.utils.spring.data.sample.usecases.store.SampleAuditorAware; import org.springframework.data.domain.AuditorAware; import org.springframework.util.ReflectionUtils; @@ -18,7 +27,9 @@ import java.util.Optional; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -27,210 +38,204 @@ @SuppressWarnings("WeakerAccess, unused") public class AuditableWrapperTest { - private AuditorAware auditorAware; - - @BeforeMethod - public void setUp() { - auditorAware = new SampleAuditorAware(); - } - - @Test - public void testCreatedBy() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithCreatedBy.class, null, - "id"); - final EntityWithCreatedBy entity = new EntityWithCreatedBy(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - assertThat(entity.getCreatedBy(), is(nullValue())); - assertThat(wrapper.getCreatedBy(), is(Optional.empty())); - assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true)); - wrapper.setCreatedBy(auditorAware.getCurrentAuditor().get()); - assertThat(wrapper.getCreatedBy().isPresent(), is(true)); - assertThat(wrapper.getCreatedBy().get(), is(SampleAuditorAware.AUDITOR)); - assertThat(entity.getCreatedBy(), is(SampleAuditorAware.AUDITOR)); - } - - @Test - public void testLastModifiedBy() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithLastModifiedBy.class, - null, "id"); - final EntityWithLastModifiedBy entity = new EntityWithLastModifiedBy(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - assertThat(entity.getLastModifiedBy(), is(nullValue())); - assertThat(wrapper.getLastModifiedBy(), is(Optional.empty())); - assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true)); - wrapper.setLastModifiedBy(auditorAware.getCurrentAuditor().get()); - assertThat(wrapper.getLastModifiedBy().isPresent(), is(true)); - assertThat(wrapper.getLastModifiedBy().get(), is(SampleAuditorAware.AUDITOR)); - assertThat(entity.getLastModifiedBy(), is(SampleAuditorAware.AUDITOR)); - } - - @Test - public void testCreatedDate() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithCreatedDate.class, null, - "id"); - final EntityWithCreatedDate entity = new EntityWithCreatedDate(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - assertThat(entity.getCreatedDate(), is(nullValue())); - assertThat(wrapper.getCreatedDate(), is(Optional.empty())); - final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); - wrapper.setCreatedDate(time); - assertThat(wrapper.getCreatedDate().isPresent(), is(true)); - assertThat(wrapper.getCreatedDate().get(), is(time)); - assertThat(entity.getCreatedDate().toInstant(), is(time)); - } - - @Test - public void testUtilDateLastModifiedDate() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithUtilDateLastModifiedDate.class, - null, "id"); - final EntityWithUtilDateLastModifiedDate entity = new EntityWithUtilDateLastModifiedDate(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); - assertThat(entity.getLastModifiedDate(), is(nullValue())); - assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); - wrapper.setLastModifiedDate(time); - assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); - assertThat(wrapper.getLastModifiedDate().get(), is(time)); - assertThat(entity.getLastModifiedDate().toInstant(), is(time)); - } - - @Test - public void testSqlDateLastModifiedDate() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithSqlDateLastModifiedDate.class, - null, "id"); - final EntityWithSqlDateLastModifiedDate entity = new EntityWithSqlDateLastModifiedDate(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); - assertThat(entity.getLastModifiedDate(), is(nullValue())); - assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); - wrapper.setLastModifiedDate(time); - assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); - assertThat(wrapper.getLastModifiedDate().get(), is(time)); - assertThat(entity.getLastModifiedDate().getTime(), is(time.toEpochMilli())); - } - - @Test - public void testTimestampLastModifiedDate() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithTimestampDateLastModifiedDate.class, - null, "id"); - final EntityWithTimestampDateLastModifiedDate entity = new EntityWithTimestampDateLastModifiedDate(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); - assertThat(entity.getLastModifiedDate(), is(nullValue())); - assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); - wrapper.setLastModifiedDate(time); - assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); - assertThat(wrapper.getLastModifiedDate().get(), is(time)); - assertThat(entity.getLastModifiedDate(), is(new Timestamp(time.toEpochMilli()))); - } - - @Test - public void testTimeLastModifiedDate() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithTimeLastModifiedDate.class, - null, "id"); - final EntityWithTimeLastModifiedDate entity = new EntityWithTimeLastModifiedDate(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); - assertThat(entity.getLastModifiedDate(), is(nullValue())); - assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); - wrapper.setLastModifiedDate(time); - assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); - assertThat(wrapper.getLastModifiedDate().get(), is(time)); - assertThat(entity.getLastModifiedDate(), is(new Time(time.toEpochMilli()))); - } - - @Test - public void testDateTimeLastModifiedDate() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithDateTimeLastModifiedDate.class, - null, "id"); - final EntityWithDateTimeLastModifiedDate entity = new EntityWithDateTimeLastModifiedDate(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - final Instant time = Instant.now(); - assertThat(entity.getLastModifiedDate(), is(nullValue())); - assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); - wrapper.setLastModifiedDate(time); - assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); - assertThat(wrapper.getLastModifiedDate().get(), is(time)); - assertThat(entity.getLastModifiedDate(), is(time)); - } - - @Test - public void testSettingNullValue() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithCreatedBy.class, null, - "id"); - final EntityWithCreatedBy entity = new EntityWithCreatedBy(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - assertThat(entity.getCreatedBy(), is(nullValue())); - //noinspection ConstantConditions - wrapper.setCreatedBy(null); - assertThat(entity.getCreatedBy(), is(nullValue())); - } - - @Test - public void testGettingIdentifier() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithCreatedBy.class, null, - "id"); - final EntityWithCreatedBy entity = new EntityWithCreatedBy(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - assertThat(wrapper.getId(), is(nullValue())); - entity.setId("some identifier"); - assertThat(wrapper.getId(), is(notNullValue())); - assertThat(wrapper.getId(), is(entity.getId())); - } - - @Test - public void testDirtyChecking() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithCreatedBy.class, null, - "id"); - final EntityWithCreatedBy entity = new EntityWithCreatedBy(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - assertThat(wrapper.isNew(), is(true)); - entity.setId("some identifier"); - assertThat(wrapper.isNew(), is(false)); - } - - @Test - public void testSettingReadOnlyProperty() { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithFinalCreatedBy.class, - null, "id"); - final EntityWithFinalCreatedBy entity = new EntityWithFinalCreatedBy(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - assertThat(entity.getCreatedBy(), is(nullValue())); - assertThat(wrapper.getCreatedBy(), is(Optional.empty())); - wrapper.setCreatedBy(auditorAware.getCurrentAuditor()); - assertThat(wrapper.getCreatedBy(), is(Optional.empty())); - assertThat(entity.getCreatedBy(), is(nullValue())); - } - - @Test - public void testWriteOnlyCreatedBy() throws Exception { - final RepositoryMetadata repositoryMetadata = new ImmutableRepositoryMetadata(String.class, - EntityWithWriteOnlyCreatedBy.class, - null, "id"); - final EntityWithWriteOnlyCreatedBy entity = new EntityWithWriteOnlyCreatedBy(); - final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); - final Field createdBy = ReflectionUtils.findField(EntityWithWriteOnlyCreatedBy.class, "createdBy"); - Objects.requireNonNull(createdBy).setAccessible(true); - assertThat(createdBy.get(entity), is(nullValue())); - assertThat(wrapper.getCreatedBy(), is(Optional.empty())); - assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true)); - wrapper.setCreatedBy(auditorAware.getCurrentAuditor().get()); - //the wrapper will not be able to read the value ... - assertThat(wrapper.getCreatedBy(), is(Optional.empty())); - //... but the value is set anyway - assertThat(createdBy.get(entity), is(SampleAuditorAware.AUDITOR)); - } - -} \ No newline at end of file + private AuditorAware auditorAware; + + @BeforeMethod + public void setUp() { + auditorAware = new SampleAuditorAware(); + } + + @Test + public void testCreatedBy() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, EntityWithCreatedBy.class, null, "id"); + final EntityWithCreatedBy entity = new EntityWithCreatedBy(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + assertThat(entity.getCreatedBy(), is(nullValue())); + assertThat(wrapper.getCreatedBy(), is(Optional.empty())); + assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true)); + wrapper.setCreatedBy(auditorAware.getCurrentAuditor().get()); + assertThat(wrapper.getCreatedBy().isPresent(), is(true)); + assertThat(wrapper.getCreatedBy().get(), is(SampleAuditorAware.AUDITOR)); + assertThat(entity.getCreatedBy(), is(SampleAuditorAware.AUDITOR)); + } + + @Test + public void testLastModifiedBy() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, EntityWithLastModifiedBy.class, null, "id"); + final EntityWithLastModifiedBy entity = new EntityWithLastModifiedBy(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + assertThat(entity.getLastModifiedBy(), is(nullValue())); + assertThat(wrapper.getLastModifiedBy(), is(Optional.empty())); + assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true)); + wrapper.setLastModifiedBy(auditorAware.getCurrentAuditor().get()); + assertThat(wrapper.getLastModifiedBy().isPresent(), is(true)); + assertThat(wrapper.getLastModifiedBy().get(), is(SampleAuditorAware.AUDITOR)); + assertThat(entity.getLastModifiedBy(), is(SampleAuditorAware.AUDITOR)); + } + + @Test + public void testCreatedDate() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, EntityWithCreatedDate.class, null, "id"); + final EntityWithCreatedDate entity = new EntityWithCreatedDate(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + assertThat(entity.getCreatedDate(), is(nullValue())); + assertThat(wrapper.getCreatedDate(), is(Optional.empty())); + final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); + wrapper.setCreatedDate(time); + assertThat(wrapper.getCreatedDate().isPresent(), is(true)); + assertThat(wrapper.getCreatedDate().get(), is(time)); + assertThat(entity.getCreatedDate().toInstant(), is(time)); + } + + @Test + public void testUtilDateLastModifiedDate() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, EntityWithUtilDateLastModifiedDate.class, null, "id"); + final EntityWithUtilDateLastModifiedDate entity = new EntityWithUtilDateLastModifiedDate(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); + assertThat(entity.getLastModifiedDate(), is(nullValue())); + assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); + wrapper.setLastModifiedDate(time); + assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); + assertThat(wrapper.getLastModifiedDate().get(), is(time)); + assertThat(entity.getLastModifiedDate().toInstant(), is(time)); + } + + @Test + public void testSqlDateLastModifiedDate() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, EntityWithSqlDateLastModifiedDate.class, null, "id"); + final EntityWithSqlDateLastModifiedDate entity = new EntityWithSqlDateLastModifiedDate(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); + assertThat(entity.getLastModifiedDate(), is(nullValue())); + assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); + wrapper.setLastModifiedDate(time); + assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); + assertThat(wrapper.getLastModifiedDate().get(), is(time)); + assertThat(entity.getLastModifiedDate().getTime(), is(time.toEpochMilli())); + } + + @Test + public void testTimestampLastModifiedDate() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, EntityWithTimestampDateLastModifiedDate.class, null, "id"); + final EntityWithTimestampDateLastModifiedDate entity = + new EntityWithTimestampDateLastModifiedDate(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); + assertThat(entity.getLastModifiedDate(), is(nullValue())); + assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); + wrapper.setLastModifiedDate(time); + assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); + assertThat(wrapper.getLastModifiedDate().get(), is(time)); + assertThat(entity.getLastModifiedDate(), is(new Timestamp(time.toEpochMilli()))); + } + + @Test + public void testTimeLastModifiedDate() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, EntityWithTimeLastModifiedDate.class, null, "id"); + final EntityWithTimeLastModifiedDate entity = new EntityWithTimeLastModifiedDate(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS); + assertThat(entity.getLastModifiedDate(), is(nullValue())); + assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); + wrapper.setLastModifiedDate(time); + assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); + assertThat(wrapper.getLastModifiedDate().get(), is(time)); + assertThat(entity.getLastModifiedDate(), is(new Time(time.toEpochMilli()))); + } + + @Test + public void testDateTimeLastModifiedDate() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, EntityWithDateTimeLastModifiedDate.class, null, "id"); + final EntityWithDateTimeLastModifiedDate entity = new EntityWithDateTimeLastModifiedDate(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + final Instant time = Instant.now(); + assertThat(entity.getLastModifiedDate(), is(nullValue())); + assertThat(wrapper.getLastModifiedDate(), is(Optional.empty())); + wrapper.setLastModifiedDate(time); + assertThat(wrapper.getLastModifiedDate().isPresent(), is(true)); + assertThat(wrapper.getLastModifiedDate().get(), is(time)); + assertThat(entity.getLastModifiedDate(), is(time)); + } + + @Test + public void testSettingNullValue() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, EntityWithCreatedBy.class, null, "id"); + final EntityWithCreatedBy entity = new EntityWithCreatedBy(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + assertThat(entity.getCreatedBy(), is(nullValue())); + //noinspection ConstantConditions + wrapper.setCreatedBy(null); + assertThat(entity.getCreatedBy(), is(nullValue())); + } + + @Test + public void testGettingIdentifier() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, EntityWithCreatedBy.class, null, "id"); + final EntityWithCreatedBy entity = new EntityWithCreatedBy(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + assertThat(wrapper.getId(), is(nullValue())); + entity.setId("some identifier"); + assertThat(wrapper.getId(), is(notNullValue())); + assertThat(wrapper.getId(), is(entity.getId())); + } + + @Test + public void testDirtyChecking() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, EntityWithCreatedBy.class, null, "id"); + final EntityWithCreatedBy entity = new EntityWithCreatedBy(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + assertThat(wrapper.isNew(), is(true)); + entity.setId("some identifier"); + assertThat(wrapper.isNew(), is(false)); + } + + @Test + public void testSettingReadOnlyProperty() { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata(String.class, EntityWithFinalCreatedBy.class, null, "id"); + final EntityWithFinalCreatedBy entity = new EntityWithFinalCreatedBy(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + assertThat(entity.getCreatedBy(), is(nullValue())); + assertThat(wrapper.getCreatedBy(), is(Optional.empty())); + wrapper.setCreatedBy(auditorAware.getCurrentAuditor()); + assertThat(wrapper.getCreatedBy(), is(Optional.empty())); + assertThat(entity.getCreatedBy(), is(nullValue())); + } + + @Test + public void testWriteOnlyCreatedBy() throws Exception { + final RepositoryMetadata repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, EntityWithWriteOnlyCreatedBy.class, null, "id"); + final EntityWithWriteOnlyCreatedBy entity = new EntityWithWriteOnlyCreatedBy(); + final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata); + final Field createdBy = + ReflectionUtils.findField(EntityWithWriteOnlyCreatedBy.class, "createdBy"); + Objects.requireNonNull(createdBy).setAccessible(true); + assertThat(createdBy.get(entity), is(nullValue())); + assertThat(wrapper.getCreatedBy(), is(Optional.empty())); + assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true)); + wrapper.setCreatedBy(auditorAware.getCurrentAuditor().get()); + // the wrapper will not be able to read the value ... + assertThat(wrapper.getCreatedBy(), is(Optional.empty())); + // ... but the value is set anyway + assertThat(createdBy.get(entity), is(SampleAuditorAware.AUDITOR)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContextTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContextTest.java index c9fb74cd..95df189e 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContextTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContextTest.java @@ -8,7 +8,9 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -16,76 +18,80 @@ */ public class DefaultDataStoreEventListenerContextTest { - @Test(expectedExceptions = InvalidArgumentException.class) - public void testTriggeringNullEvent() { - DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext(); - context.trigger(null); - } + @Test(expectedExceptions = InvalidArgumentException.class) + public void testTriggeringNullEvent() { + DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext(); + context.trigger(null); + } - @Test - public void testExactEventType() { - final AfterInsertEventListener first = new AfterInsertEventListener(); - final AfterInsertEventListener second = new AfterInsertEventListener(); - final AfterInsertDataStoreEvent event = new AfterInsertDataStoreEvent(null, null, null); - final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext(); - context.register(first); - context.register(second); - context.trigger(event); - assertThat(first.getEvents(), hasSize(1)); - assertThat(first.getEvents().get(0), is(event)); - assertThat(second.getEvents(), hasSize(1)); - assertThat(second.getEvents().get(0), is(event)); - } + @Test + public void testExactEventType() { + final AfterInsertEventListener first = new AfterInsertEventListener(); + final AfterInsertEventListener second = new AfterInsertEventListener(); + final AfterInsertDataStoreEvent event = new AfterInsertDataStoreEvent(null, null, null); + final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext(); + context.register(first); + context.register(second); + context.trigger(event); + assertThat(first.getEvents(), hasSize(1)); + assertThat(first.getEvents().get(0), is(event)); + assertThat(second.getEvents(), hasSize(1)); + assertThat(second.getEvents().get(0), is(event)); + } - @Test - public void testParentEventType() { - final AllCatchingEventListener first = new AllCatchingEventListener(); - final AfterInsertEventListener second = new AfterInsertEventListener(); - final AfterInsertDataStoreEvent event = new AfterInsertDataStoreEvent(null, null, null); - final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext(); - context.register(first); - context.register(second); - context.trigger(event); - assertThat(first.getEvents(), hasSize(1)); - assertThat(first.getEvents().get(0), Matchers.is(event)); - assertThat(second.getEvents(), hasSize(1)); - assertThat(second.getEvents().get(0), is(event)); - } + @Test + public void testParentEventType() { + final AllCatchingEventListener first = new AllCatchingEventListener(); + final AfterInsertEventListener second = new AfterInsertEventListener(); + final AfterInsertDataStoreEvent event = new AfterInsertDataStoreEvent(null, null, null); + final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext(); + context.register(first); + context.register(second); + context.trigger(event); + assertThat(first.getEvents(), hasSize(1)); + assertThat(first.getEvents().get(0), Matchers.is(event)); + assertThat(second.getEvents(), hasSize(1)); + assertThat(second.getEvents().get(0), is(event)); + } - @Test - public void testEventPropagation() { - final AfterInsertDataStoreEvent firstEvent = new AfterInsertDataStoreEvent(null, null, null); - final AfterInsertDataStoreEvent secondEvent = new AfterInsertDataStoreEvent(null, null, null); - final AfterInsertEventListener first = new AfterInsertEventListener(); - final AfterInsertEventListener second = new AfterInsertEventListener(); - final DefaultDataStoreEventListenerContext parent = new DefaultDataStoreEventListenerContext(); - final DefaultDataStoreEventListenerContext child = new DefaultDataStoreEventListenerContext(parent); - parent.register(first); - child.register(second); - child.trigger(firstEvent); - parent.trigger(secondEvent); - assertThat(first.getEvents(), hasSize(2)); - assertThat(first.getEvents(), contains(firstEvent, secondEvent)); - assertThat(second.getEvents(), hasSize(1)); - assertThat(second.getEvents().get(0), is(firstEvent)); - } + @Test + public void testEventPropagation() { + final AfterInsertDataStoreEvent firstEvent = new AfterInsertDataStoreEvent(null, null, null); + final AfterInsertDataStoreEvent secondEvent = new AfterInsertDataStoreEvent(null, null, null); + final AfterInsertEventListener first = new AfterInsertEventListener(); + final AfterInsertEventListener second = new AfterInsertEventListener(); + final DefaultDataStoreEventListenerContext parent = new DefaultDataStoreEventListenerContext(); + final DefaultDataStoreEventListenerContext child = + new DefaultDataStoreEventListenerContext(parent); + parent.register(first); + child.register(second); + child.trigger(firstEvent); + parent.trigger(secondEvent); + assertThat(first.getEvents(), hasSize(2)); + assertThat(first.getEvents(), contains(firstEvent, secondEvent)); + assertThat(second.getEvents(), hasSize(1)); + assertThat(second.getEvents().get(0), is(firstEvent)); + } - @Test - public void testFindingEventListeners() { - final AfterInsertEventListener first = new AfterInsertEventListener(); - final AfterInsertEventListener second = new AfterInsertEventListener(); - final DefaultDataStoreEventListenerContext parent = new DefaultDataStoreEventListenerContext(); - final DefaultDataStoreEventListenerContext child = new DefaultDataStoreEventListenerContext(parent); - parent.register(first); - child.register(second); - assertThat(parent.getListeners(AfterInsertDataStoreEvent.class), hasSize(1)); - assertThat(parent.getListeners(AfterInsertDataStoreEvent.class).get(0), - Matchers.is(first)); - assertThat(child.getListeners(AfterInsertDataStoreEvent.class), hasSize(2)); - assertThat(child.getListeners(AfterInsertDataStoreEvent.class).get(0), - Matchers.is(second)); - assertThat(child.getListeners(AfterInsertDataStoreEvent.class).get(1), - Matchers.is(first)); - } - -} \ No newline at end of file + @Test + public void testFindingEventListeners() { + final AfterInsertEventListener first = new AfterInsertEventListener(); + final AfterInsertEventListener second = new AfterInsertEventListener(); + final DefaultDataStoreEventListenerContext parent = new DefaultDataStoreEventListenerContext(); + final DefaultDataStoreEventListenerContext child = + new DefaultDataStoreEventListenerContext(parent); + parent.register(first); + child.register(second); + assertThat(parent.getListeners(AfterInsertDataStoreEvent.class), hasSize(1)); + assertThat( + parent.getListeners(AfterInsertDataStoreEvent.class).get(0), + Matchers.is(first)); + assertThat(child.getListeners(AfterInsertDataStoreEvent.class), hasSize(2)); + assertThat( + child.getListeners(AfterInsertDataStoreEvent.class).get(0), + Matchers.is(second)); + assertThat( + child.getListeners(AfterInsertDataStoreEvent.class).get(1), + Matchers.is(first)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistryTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistryTest.java index fdd3debf..83fc3669 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistryTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistryTest.java @@ -13,28 +13,27 @@ */ public class DefaultDataStoreRegistryTest { - @Test - public void testRegisteringDataStore() { - final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry(); - final MemoryDataStore dataStore = new MemoryDataStore<>(Person.class); - registry.register(dataStore); - assertThat(registry.getDataStore(Person.class), Matchers.is(dataStore)); - } + @Test + public void testRegisteringDataStore() { + final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry(); + final MemoryDataStore dataStore = new MemoryDataStore<>(Person.class); + registry.register(dataStore); + assertThat(registry.getDataStore(Person.class), Matchers.is(dataStore)); + } - @Test - public void testOverridingDataStore() { - final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry(); - final MemoryDataStore first = new MemoryDataStore<>(Person.class); - final MemoryDataStore second = new MemoryDataStore<>(Person.class); - registry.register(first); - registry.register(second); - assertThat(registry.getDataStore(Person.class), Matchers.is(second)); - } + @Test + public void testOverridingDataStore() { + final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry(); + final MemoryDataStore first = new MemoryDataStore<>(Person.class); + final MemoryDataStore second = new MemoryDataStore<>(Person.class); + registry.register(first); + registry.register(second); + assertThat(registry.getDataStore(Person.class), Matchers.is(second)); + } - @Test(expectedExceptions = DataStoreNotFoundException.class) - public void testLookingForInvalidDataStore() { - final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry(); - registry.getDataStore(Person.class); - } - -} \ No newline at end of file + @Test(expectedExceptions = DataStoreNotFoundException.class) + public void testLookingForInvalidDataStore() { + final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry(); + registry.getDataStore(Person.class); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStoreTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStoreTest.java index 647c011c..02e69672 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStoreTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStoreTest.java @@ -3,7 +3,11 @@ import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata; import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata; import com.mmnaseri.utils.spring.data.error.CorruptDataException; -import com.mmnaseri.utils.spring.data.sample.mocks.*; +import com.mmnaseri.utils.spring.data.sample.mocks.EventTrigger; +import com.mmnaseri.utils.spring.data.sample.mocks.Operation; +import com.mmnaseri.utils.spring.data.sample.mocks.OperationRequest; +import com.mmnaseri.utils.spring.data.sample.mocks.SpyingDataStore; +import com.mmnaseri.utils.spring.data.sample.mocks.SpyingListenerContext; import com.mmnaseri.utils.spring.data.sample.models.DummyEvent; import com.mmnaseri.utils.spring.data.sample.models.Person; import com.mmnaseri.utils.spring.data.sample.repositories.SimplePersonRepository; @@ -17,7 +21,11 @@ import java.util.concurrent.atomic.AtomicLong; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -26,174 +34,189 @@ @SuppressWarnings("WeakerAccess") public class EventPublishingDataStoreTest { - private static final AtomicLong counter = new AtomicLong(0); - private RepositoryMetadata repositoryMetadata; - private DataStore delegate; - private SpyingDataStore delegateSpy; - private DataStore dataStore; - private SpyingListenerContext listenerContext; - - @BeforeMethod - public void setUp() { - repositoryMetadata = new ImmutableRepositoryMetadata(String.class, Person.class, SimplePersonRepository.class, - "id"); - listenerContext = new SpyingListenerContext(counter); - delegate = new MemoryDataStore<>(Person.class); - delegateSpy = new SpyingDataStore<>(delegate, counter); - dataStore = new EventPublishingDataStore<>(delegateSpy, repositoryMetadata, listenerContext); - } - - @Test - public void testHasKeyDelegation() { - final String key = "1"; - delegate.save(key, new Person()); - assertThat(dataStore.hasKey(key), is(true)); - } - - @Test - public void testRetrieveDelegation() { - final String key = "key"; - assertThat(dataStore.retrieve(key), is(delegate.retrieve(key))); - delegate.save(key, new Person()); - assertThat(dataStore.retrieve(key), is(delegate.retrieve(key))); - } - - @Test - public void testRetrieveAllDelegation() { - final String k1 = "k1"; - final String k2 = "k2"; - assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll())); - delegate.save(k1, new Person()); - delegate.save(k2, new Person()); - assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll())); - } - - @Test - public void testEntityTypeDelegation() { - assertThat(dataStore.getEntityType(), Matchers.>is(delegate.getEntityType())); - } - - @Test - public void testEventPublishingDelegation() { - final DummyEvent event = new DummyEvent(); - ((EventPublishingDataStore) dataStore).publishEvent(event); - assertThat(listenerContext.getEvents(), hasSize(1)); - assertThat(listenerContext.getEvents().get(0).getEvent(), Matchers.is(event)); - } - - @Test - public void testKeysDelegation() { - final AtomicBoolean called = new AtomicBoolean(false); - final DataStore localDataStore = new EventPublishingDataStore<>( - new MemoryDataStore(Person.class) { - - @Override - public Collection keys() { - called.set(true); - return super.keys(); - } - }, repositoryMetadata, listenerContext); - assertThat(called.get(), is(false)); - localDataStore.keys(); - assertThat(called.get(), is(true)); - } - - @Test(expectedExceptions = CorruptDataException.class) - public void testSavingNullKey() { - dataStore.save(null, new Person()); - } - - @Test(expectedExceptions = CorruptDataException.class) - public void testSavingNullEntity() { - dataStore.save("", null); - } - - @Test - public void testInsert() { - final String key = "k"; - final Person entity = new Person(); - dataStore.save(key, entity); - assertThat(listenerContext.getEvents(), hasSize(2)); - assertThat(listenerContext.getEvents().get(0).getEvent(), is(instanceOf(BeforeInsertDataStoreEvent.class))); - assertThat(listenerContext.getEvents().get(1).getEvent(), is(instanceOf(AfterInsertDataStoreEvent.class))); - assertThat(delegateSpy.getRequests(), hasSize(2)); - final OperationRequest save = delegateSpy.getRequests().get(1); - assertThat(save.getOperation(), is(Operation.SAVE)); - assertThat(save.getKey(), Matchers.is(key)); - assertThat(save.getEntity(), Matchers.is(entity)); - final EventTrigger before = listenerContext.getEvents().get(0); - final EventTrigger after = listenerContext.getEvents().get(1); - assertThat(before.getTimestamp(), is(lessThan(save.getTimestamp()))); - assertThat(save.getTimestamp(), is(lessThan(after.getTimestamp()))); - assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore)); - assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore)); - } - - @Test - public void testUpdate() { - final String key = "k"; - final Person entity = new Person(); - dataStore.save(key, entity); - listenerContext.reset(); - delegateSpy.reset(); - dataStore.save(key, entity); - assertThat(listenerContext.getEvents(), hasSize(2)); - assertThat(listenerContext.getEvents().get(0).getEvent(), is(instanceOf(BeforeUpdateDataStoreEvent.class))); - assertThat(listenerContext.getEvents().get(1).getEvent(), is(instanceOf(AfterUpdateDataStoreEvent.class))); - assertThat(delegateSpy.getRequests(), hasSize(2)); - final OperationRequest request = delegateSpy.getRequests().get(1); - assertThat(request.getOperation(), is(Operation.SAVE)); - assertThat(request.getKey(), Matchers.is(key)); - assertThat(request.getEntity(), Matchers.is(entity)); - final EventTrigger before = listenerContext.getEvents().get(0); - final EventTrigger after = listenerContext.getEvents().get(1); - assertThat(before.getTimestamp(), is(lessThan(request.getTimestamp()))); - assertThat(request.getTimestamp(), is(lessThan(after.getTimestamp()))); - assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore)); - assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore)); - } - - @Test - public void testDeletingNonExistentKey() { - dataStore.delete("key"); - assertThat(delegateSpy.getRequests(), hasSize(1)); - assertThat(listenerContext.getEvents(), is(Matchers.empty())); - } - - @Test - public void testDelete() { - final String key = "k"; - final Person entity = new Person(); - dataStore.save(key, entity); - listenerContext.reset(); - delegateSpy.reset(); - dataStore.delete(key); - assertThat(listenerContext.getEvents(), hasSize(2)); - assertThat(listenerContext.getEvents().get(0).getEvent(), is(instanceOf(BeforeDeleteDataStoreEvent.class))); - assertThat(listenerContext.getEvents().get(1).getEvent(), is(instanceOf(AfterDeleteDataStoreEvent.class))); - assertThat(delegateSpy.getRequests(), hasSize(3)); - final OperationRequest request = delegateSpy.getRequests().get(2); - assertThat(request.getOperation(), is(Operation.DELETE)); - assertThat(request.getKey(), Matchers.is(key)); - assertThat(request.getEntity(), is(nullValue())); - final EventTrigger before = listenerContext.getEvents().get(0); - final EventTrigger after = listenerContext.getEvents().get(1); - assertThat(before.getTimestamp(), is(lessThan(request.getTimestamp()))); - assertThat(request.getTimestamp(), is(lessThan(after.getTimestamp()))); - assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore)); - assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore)); - } - - @Test - public void testTruncating() { - final String k1 = "k1"; - final String k2 = "k2"; - assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll())); - delegate.save(k1, new Person()); - delegate.save(k2, new Person()); - assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll())); - dataStore.truncate(); - assertThat(delegate.retrieveAll(), is(Matchers.empty())); - } - -} \ No newline at end of file + private static final AtomicLong counter = new AtomicLong(0); + private RepositoryMetadata repositoryMetadata; + private DataStore delegate; + private SpyingDataStore delegateSpy; + private DataStore dataStore; + private SpyingListenerContext listenerContext; + + @BeforeMethod + public void setUp() { + repositoryMetadata = + new ImmutableRepositoryMetadata( + String.class, Person.class, SimplePersonRepository.class, "id"); + listenerContext = new SpyingListenerContext(counter); + delegate = new MemoryDataStore<>(Person.class); + delegateSpy = new SpyingDataStore<>(delegate, counter); + dataStore = new EventPublishingDataStore<>(delegateSpy, repositoryMetadata, listenerContext); + } + + @Test + public void testHasKeyDelegation() { + final String key = "1"; + delegate.save(key, new Person()); + assertThat(dataStore.hasKey(key), is(true)); + } + + @Test + public void testRetrieveDelegation() { + final String key = "key"; + assertThat(dataStore.retrieve(key), is(delegate.retrieve(key))); + delegate.save(key, new Person()); + assertThat(dataStore.retrieve(key), is(delegate.retrieve(key))); + } + + @Test + public void testRetrieveAllDelegation() { + final String k1 = "k1"; + final String k2 = "k2"; + assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll())); + delegate.save(k1, new Person()); + delegate.save(k2, new Person()); + assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll())); + } + + @Test + public void testEntityTypeDelegation() { + assertThat(dataStore.getEntityType(), Matchers.>is(delegate.getEntityType())); + } + + @Test + public void testEventPublishingDelegation() { + final DummyEvent event = new DummyEvent(); + ((EventPublishingDataStore) dataStore).publishEvent(event); + assertThat(listenerContext.getEvents(), hasSize(1)); + assertThat(listenerContext.getEvents().get(0).getEvent(), Matchers.is(event)); + } + + @Test + public void testKeysDelegation() { + final AtomicBoolean called = new AtomicBoolean(false); + final DataStore localDataStore = + new EventPublishingDataStore<>( + new MemoryDataStore(Person.class) { + + @Override + public Collection keys() { + called.set(true); + return super.keys(); + } + }, + repositoryMetadata, + listenerContext); + assertThat(called.get(), is(false)); + localDataStore.keys(); + assertThat(called.get(), is(true)); + } + + @Test(expectedExceptions = CorruptDataException.class) + public void testSavingNullKey() { + dataStore.save(null, new Person()); + } + + @Test(expectedExceptions = CorruptDataException.class) + public void testSavingNullEntity() { + dataStore.save("", null); + } + + @Test + public void testInsert() { + final String key = "k"; + final Person entity = new Person(); + dataStore.save(key, entity); + assertThat(listenerContext.getEvents(), hasSize(2)); + assertThat( + listenerContext.getEvents().get(0).getEvent(), + is(instanceOf(BeforeInsertDataStoreEvent.class))); + assertThat( + listenerContext.getEvents().get(1).getEvent(), + is(instanceOf(AfterInsertDataStoreEvent.class))); + assertThat(delegateSpy.getRequests(), hasSize(2)); + final OperationRequest save = delegateSpy.getRequests().get(1); + assertThat(save.getOperation(), is(Operation.SAVE)); + assertThat(save.getKey(), Matchers.is(key)); + assertThat(save.getEntity(), Matchers.is(entity)); + final EventTrigger before = listenerContext.getEvents().get(0); + final EventTrigger after = listenerContext.getEvents().get(1); + assertThat(before.getTimestamp(), is(lessThan(save.getTimestamp()))); + assertThat(save.getTimestamp(), is(lessThan(after.getTimestamp()))); + assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore)); + assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore)); + } + + @Test + public void testUpdate() { + final String key = "k"; + final Person entity = new Person(); + dataStore.save(key, entity); + listenerContext.reset(); + delegateSpy.reset(); + dataStore.save(key, entity); + assertThat(listenerContext.getEvents(), hasSize(2)); + assertThat( + listenerContext.getEvents().get(0).getEvent(), + is(instanceOf(BeforeUpdateDataStoreEvent.class))); + assertThat( + listenerContext.getEvents().get(1).getEvent(), + is(instanceOf(AfterUpdateDataStoreEvent.class))); + assertThat(delegateSpy.getRequests(), hasSize(2)); + final OperationRequest request = delegateSpy.getRequests().get(1); + assertThat(request.getOperation(), is(Operation.SAVE)); + assertThat(request.getKey(), Matchers.is(key)); + assertThat(request.getEntity(), Matchers.is(entity)); + final EventTrigger before = listenerContext.getEvents().get(0); + final EventTrigger after = listenerContext.getEvents().get(1); + assertThat(before.getTimestamp(), is(lessThan(request.getTimestamp()))); + assertThat(request.getTimestamp(), is(lessThan(after.getTimestamp()))); + assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore)); + assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore)); + } + + @Test + public void testDeletingNonExistentKey() { + dataStore.delete("key"); + assertThat(delegateSpy.getRequests(), hasSize(1)); + assertThat(listenerContext.getEvents(), is(Matchers.empty())); + } + + @Test + public void testDelete() { + final String key = "k"; + final Person entity = new Person(); + dataStore.save(key, entity); + listenerContext.reset(); + delegateSpy.reset(); + dataStore.delete(key); + assertThat(listenerContext.getEvents(), hasSize(2)); + assertThat( + listenerContext.getEvents().get(0).getEvent(), + is(instanceOf(BeforeDeleteDataStoreEvent.class))); + assertThat( + listenerContext.getEvents().get(1).getEvent(), + is(instanceOf(AfterDeleteDataStoreEvent.class))); + assertThat(delegateSpy.getRequests(), hasSize(3)); + final OperationRequest request = delegateSpy.getRequests().get(2); + assertThat(request.getOperation(), is(Operation.DELETE)); + assertThat(request.getKey(), Matchers.is(key)); + assertThat(request.getEntity(), is(nullValue())); + final EventTrigger before = listenerContext.getEvents().get(0); + final EventTrigger after = listenerContext.getEvents().get(1); + assertThat(before.getTimestamp(), is(lessThan(request.getTimestamp()))); + assertThat(request.getTimestamp(), is(lessThan(after.getTimestamp()))); + assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore)); + assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore)); + } + + @Test + public void testTruncating() { + final String k1 = "k1"; + final String k2 = "k2"; + assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll())); + delegate.save(k1, new Person()); + delegate.save(k2, new Person()); + assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll())); + dataStore.truncate(); + assertThat(delegate.retrieveAll(), is(Matchers.empty())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStoreTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStoreTest.java index bc066f89..0dbfa469 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStoreTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStoreTest.java @@ -7,7 +7,11 @@ import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -15,112 +19,111 @@ */ public class MemoryDataStoreTest { - private MemoryDataStore dataStore; - - @BeforeMethod - public void setUp() { - dataStore = new MemoryDataStore<>(Person.class); - } - - @Test - public void testEntityType() { - assertThat(dataStore.getEntityType(), is(equalTo(Person.class))); - } - - @Test - public void testSaveAndRetrieve() { - assertThat(dataStore.retrieveAll(), is(Matchers.empty())); - final Person person = new Person(); - dataStore.save("key", person); - assertThat(dataStore.retrieveAll(), hasSize(1)); - } - - @Test - public void testRetrievalByKey() { - final Person person = new Person(); - final String key = "key"; - assertThat(dataStore.retrieve(key), is(nullValue())); - assertThat(dataStore.retrieve(key + "x"), is(nullValue())); - dataStore.save(key, person); - assertThat(dataStore.retrieve(key), is(person)); - assertThat(dataStore.retrieve(key + "x"), is(nullValue())); - } - - @Test - public void testExistence() { - final Person person = new Person(); - final String key = "key"; - assertThat(dataStore.hasKey(key), is(false)); - assertThat(dataStore.hasKey(key + "x"), is(false)); - dataStore.save(key, person); - assertThat(dataStore.hasKey(key), is(true)); - assertThat(dataStore.hasKey(key + "x"), is(false)); - } - - @Test - public void testSaveAndDelete() { - final Person person1 = new Person(); - final Person person2 = new Person(); - final String key1 = "key1"; - final String key2 = "key2"; - assertThat(dataStore.retrieveAll(), is(Matchers.empty())); - dataStore.save(key1, person1); - assertThat(dataStore.hasKey(key1), is(true)); - dataStore.save(key2, person2); - assertThat(dataStore.hasKey(key2), is(true)); - assertThat(dataStore.retrieveAll(), hasSize(2)); - assertThat(dataStore.retrieveAll(), containsInAnyOrder(person1, person2)); - dataStore.delete(key1 + "x"); - assertThat(dataStore.hasKey(key2), is(true)); - assertThat(dataStore.retrieveAll(), hasSize(2)); - assertThat(dataStore.retrieveAll(), containsInAnyOrder(person1, person2)); - dataStore.delete(key1); - assertThat(dataStore.hasKey(key1), is(false)); - assertThat(dataStore.hasKey(key2), is(true)); - assertThat(dataStore.retrieveAll(), hasSize(1)); - assertThat(dataStore.retrieveAll(), containsInAnyOrder(person2)); - dataStore.delete(key2); - assertThat(dataStore.hasKey(key1), is(false)); - assertThat(dataStore.hasKey(key2), is(false)); - assertThat(dataStore.retrieveAll(), is(Matchers.empty())); - } - - @Test - public void testKeys() { - dataStore.save("1", new Person()); - dataStore.save("2", new Person()); - dataStore.save("3", new Person()); - assertThat(dataStore.keys(), containsInAnyOrder("1", "2", "3")); - } - - @Test(expectedExceptions = DataStoreException.class) - public void testSavingWithNullKey() { - dataStore.save(null, new Person()); - } - - @Test(expectedExceptions = DataStoreException.class) - public void testSavingWithNullEntity() { - dataStore.save("1", null); - } - - @Test(expectedExceptions = DataStoreException.class) - public void testDeletingWithNullKey() { - dataStore.delete(null); - } - - @Test(expectedExceptions = DataStoreException.class) - public void testRetrievingWithNullKey() { - dataStore.retrieve(null); - } - - @Test - public void testTruncating() { - dataStore.save("1", new Person()); - dataStore.save("2", new Person()); - dataStore.save("3", new Person()); - assertThat(dataStore.retrieveAll(), hasSize(3)); - dataStore.truncate(); - assertThat(dataStore.retrieveAll(), is(Matchers.empty())); - } - -} \ No newline at end of file + private MemoryDataStore dataStore; + + @BeforeMethod + public void setUp() { + dataStore = new MemoryDataStore<>(Person.class); + } + + @Test + public void testEntityType() { + assertThat(dataStore.getEntityType(), is(equalTo(Person.class))); + } + + @Test + public void testSaveAndRetrieve() { + assertThat(dataStore.retrieveAll(), is(Matchers.empty())); + final Person person = new Person(); + dataStore.save("key", person); + assertThat(dataStore.retrieveAll(), hasSize(1)); + } + + @Test + public void testRetrievalByKey() { + final Person person = new Person(); + final String key = "key"; + assertThat(dataStore.retrieve(key), is(nullValue())); + assertThat(dataStore.retrieve(key + "x"), is(nullValue())); + dataStore.save(key, person); + assertThat(dataStore.retrieve(key), is(person)); + assertThat(dataStore.retrieve(key + "x"), is(nullValue())); + } + + @Test + public void testExistence() { + final Person person = new Person(); + final String key = "key"; + assertThat(dataStore.hasKey(key), is(false)); + assertThat(dataStore.hasKey(key + "x"), is(false)); + dataStore.save(key, person); + assertThat(dataStore.hasKey(key), is(true)); + assertThat(dataStore.hasKey(key + "x"), is(false)); + } + + @Test + public void testSaveAndDelete() { + final Person person1 = new Person(); + final Person person2 = new Person(); + final String key1 = "key1"; + final String key2 = "key2"; + assertThat(dataStore.retrieveAll(), is(Matchers.empty())); + dataStore.save(key1, person1); + assertThat(dataStore.hasKey(key1), is(true)); + dataStore.save(key2, person2); + assertThat(dataStore.hasKey(key2), is(true)); + assertThat(dataStore.retrieveAll(), hasSize(2)); + assertThat(dataStore.retrieveAll(), containsInAnyOrder(person1, person2)); + dataStore.delete(key1 + "x"); + assertThat(dataStore.hasKey(key2), is(true)); + assertThat(dataStore.retrieveAll(), hasSize(2)); + assertThat(dataStore.retrieveAll(), containsInAnyOrder(person1, person2)); + dataStore.delete(key1); + assertThat(dataStore.hasKey(key1), is(false)); + assertThat(dataStore.hasKey(key2), is(true)); + assertThat(dataStore.retrieveAll(), hasSize(1)); + assertThat(dataStore.retrieveAll(), containsInAnyOrder(person2)); + dataStore.delete(key2); + assertThat(dataStore.hasKey(key1), is(false)); + assertThat(dataStore.hasKey(key2), is(false)); + assertThat(dataStore.retrieveAll(), is(Matchers.empty())); + } + + @Test + public void testKeys() { + dataStore.save("1", new Person()); + dataStore.save("2", new Person()); + dataStore.save("3", new Person()); + assertThat(dataStore.keys(), containsInAnyOrder("1", "2", "3")); + } + + @Test(expectedExceptions = DataStoreException.class) + public void testSavingWithNullKey() { + dataStore.save(null, new Person()); + } + + @Test(expectedExceptions = DataStoreException.class) + public void testSavingWithNullEntity() { + dataStore.save("1", null); + } + + @Test(expectedExceptions = DataStoreException.class) + public void testDeletingWithNullKey() { + dataStore.delete(null); + } + + @Test(expectedExceptions = DataStoreException.class) + public void testRetrievingWithNullKey() { + dataStore.retrieve(null); + } + + @Test + public void testTruncating() { + dataStore.save("1", new Person()); + dataStore.save("2", new Person()); + dataStore.save("3", new Person()); + assertThat(dataStore.retrieveAll(), hasSize(3)); + dataStore.truncate(); + assertThat(dataStore.retrieveAll(), is(Matchers.empty())); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitorTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitorTest.java index 11b6be14..8f21d4f8 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitorTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitorTest.java @@ -15,57 +15,55 @@ */ public class PropertyVisitorTest { - @Test - public void testLookingForFieldWithAnnotation() throws Exception { - final PropertyVisitor visitor = new PropertyVisitor(Id.class); - assertThat(visitor.getProperty(), is(nullValue())); - visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field")); - assertThat(visitor.getProperty(), is("field")); - } + @Test + public void testLookingForFieldWithAnnotation() throws Exception { + final PropertyVisitor visitor = new PropertyVisitor(Id.class); + assertThat(visitor.getProperty(), is(nullValue())); + visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field")); + assertThat(visitor.getProperty(), is("field")); + } - @Test - public void testLookingForFieldWithWrongAnnotation() throws Exception { - final PropertyVisitor visitor = new PropertyVisitor(LastModifiedBy.class); - assertThat(visitor.getProperty(), is(nullValue())); - visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field")); - assertThat(visitor.getProperty(), is(nullValue())); - } + @Test + public void testLookingForFieldWithWrongAnnotation() throws Exception { + final PropertyVisitor visitor = new PropertyVisitor(LastModifiedBy.class); + assertThat(visitor.getProperty(), is(nullValue())); + visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field")); + assertThat(visitor.getProperty(), is(nullValue())); + } + @Test + public void testLookingForMethodWithAnnotation() throws Exception { + final PropertyVisitor visitor = new PropertyVisitor(Id.class); + assertThat(visitor.getProperty(), is(nullValue())); + visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty")); + assertThat(visitor.getProperty(), is("property")); + } - @Test - public void testLookingForMethodWithAnnotation() throws Exception { - final PropertyVisitor visitor = new PropertyVisitor(Id.class); - assertThat(visitor.getProperty(), is(nullValue())); - visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty")); - assertThat(visitor.getProperty(), is("property")); - } + @Test + public void testLookingForMethodWithWrongAnnotation() throws Exception { + final PropertyVisitor visitor = new PropertyVisitor(LastModifiedBy.class); + assertThat(visitor.getProperty(), is(nullValue())); + visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty")); + assertThat(visitor.getProperty(), is(nullValue())); + } - @Test - public void testLookingForMethodWithWrongAnnotation() throws Exception { - final PropertyVisitor visitor = new PropertyVisitor(LastModifiedBy.class); - assertThat(visitor.getProperty(), is(nullValue())); - visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty")); - assertThat(visitor.getProperty(), is(nullValue())); - } + @Test + public void testLookingFieldFirst() throws Exception { + final PropertyVisitor visitor = new PropertyVisitor(Id.class); + assertThat(visitor.getProperty(), is(nullValue())); + visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field")); + assertThat(visitor.getProperty(), is("field")); + visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty")); + assertThat(visitor.getProperty(), is("field")); + } - @Test - public void testLookingFieldFirst() throws Exception { - final PropertyVisitor visitor = new PropertyVisitor(Id.class); - assertThat(visitor.getProperty(), is(nullValue())); - visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field")); - assertThat(visitor.getProperty(), is("field")); - visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty")); - assertThat(visitor.getProperty(), is("field")); - } - - @Test - public void testLookingMethodFirst() throws Exception { - final PropertyVisitor visitor = new PropertyVisitor(Id.class); - assertThat(visitor.getProperty(), is(nullValue())); - visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty")); - assertThat(visitor.getProperty(), is("property")); - visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field")); - assertThat(visitor.getProperty(), is("property")); - } - -} \ No newline at end of file + @Test + public void testLookingMethodFirst() throws Exception { + final PropertyVisitor visitor = new PropertyVisitor(Id.class); + assertThat(visitor.getProperty(), is(nullValue())); + visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty")); + assertThat(visitor.getProperty(), is("property")); + visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field")); + assertThat(visitor.getProperty(), is("property")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListenerTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListenerTest.java index 5325a29d..9bead30c 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListenerTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListenerTest.java @@ -9,7 +9,10 @@ import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -17,26 +20,26 @@ */ public class SmartDataStoreEventListenerTest { - @Test - public void testEventTypeRecognition() { - final SmartDataStoreEventListener listener = new SmartDataStoreEventListener<>( - new AllCatchingEventListener()); - assertThat(listener.getEventType(), is(notNullValue())); - assertThat(listener.getEventType(), is(equalTo(DataStoreEvent.class))); - } + @Test + public void testEventTypeRecognition() { + final SmartDataStoreEventListener listener = + new SmartDataStoreEventListener<>(new AllCatchingEventListener()); + assertThat(listener.getEventType(), is(notNullValue())); + assertThat(listener.getEventType(), is(equalTo(DataStoreEvent.class))); + } - @Test - public void testEventDelegation() { - final SpyingEventListener spy = new AllCatchingEventListener(); - final SmartDataStoreEventListener listener = new SmartDataStoreEventListener<>(spy); - final AfterDeleteDataStoreEvent first = new AfterDeleteDataStoreEvent(null, null, null); - final BeforeInsertDataStoreEvent second = new BeforeInsertDataStoreEvent(null, null, null); - listener.onEvent(first); - listener.onEvent(second); - final List events = spy.getEvents(); - assertThat(events, hasSize(2)); - assertThat(events.get(0), Matchers.is(first)); - assertThat(events.get(1), Matchers.is(second)); - } - -} \ No newline at end of file + @Test + public void testEventDelegation() { + final SpyingEventListener spy = new AllCatchingEventListener(); + final SmartDataStoreEventListener listener = + new SmartDataStoreEventListener<>(spy); + final AfterDeleteDataStoreEvent first = new AfterDeleteDataStoreEvent(null, null, null); + final BeforeInsertDataStoreEvent second = new BeforeInsertDataStoreEvent(null, null, null); + listener.onEvent(first); + listener.onEvent(second); + final List events = spy.getEvents(); + assertThat(events, hasSize(2)); + assertThat(events.get(0), Matchers.is(first)); + assertThat(events.get(1), Matchers.is(second)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/AbstractUtilityClassTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/AbstractUtilityClassTest.java index 552b0b99..8bb8d3c4 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/AbstractUtilityClassTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/AbstractUtilityClassTest.java @@ -2,10 +2,18 @@ import org.testng.annotations.Test; -import java.lang.reflect.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.testng.Assert.fail; /** @@ -14,53 +22,52 @@ */ public abstract class AbstractUtilityClassTest { - protected abstract Class getUtilityClass(); + protected abstract Class getUtilityClass(); - @Test - public void testConstructorIsPrivate() { - final Constructor[] constructors = getUtilityClass().getDeclaredConstructors(); - assertThat(constructors, is(arrayWithSize(1))); - final Constructor constructor = constructors[0]; - assertThat(Modifier.isPrivate(constructor.getModifiers()), is(true)); - } - - @Test - public void testConstructorThrowsException() throws Exception { - final Constructor[] constructors = getUtilityClass().getDeclaredConstructors(); - final Constructor constructor = constructors[0]; - constructor.setAccessible(true); - try { - constructor.newInstance(); - } catch (InvocationTargetException e) { - assertThat(e.getCause(), is(notNullValue())); - assertThat(e.getCause(), is(instanceOf(UnsupportedOperationException.class))); - return; - } - fail("Expected utility class constructor to throw an exception"); - } + @Test + public void testConstructorIsPrivate() { + final Constructor[] constructors = getUtilityClass().getDeclaredConstructors(); + assertThat(constructors, is(arrayWithSize(1))); + final Constructor constructor = constructors[0]; + assertThat(Modifier.isPrivate(constructor.getModifiers()), is(true)); + } - @Test - public void testClassIsFinal() { - assertThat(Modifier.isFinal(getUtilityClass().getModifiers()), is(true)); + @Test + public void testConstructorThrowsException() throws Exception { + final Constructor[] constructors = getUtilityClass().getDeclaredConstructors(); + final Constructor constructor = constructors[0]; + constructor.setAccessible(true); + try { + constructor.newInstance(); + } catch (InvocationTargetException e) { + assertThat(e.getCause(), is(notNullValue())); + assertThat(e.getCause(), is(instanceOf(UnsupportedOperationException.class))); + return; } + fail("Expected utility class constructor to throw an exception"); + } - @Test - public void testClassHasNoInstanceMethods() { - for (Method method : getUtilityClass().getDeclaredMethods()) { - assertThat(Modifier.isStatic(method.getModifiers()), is(true)); - } - } + @Test + public void testClassIsFinal() { + assertThat(Modifier.isFinal(getUtilityClass().getModifiers()), is(true)); + } - @Test - public void testClassHasNoInstanceFields() { - for (Field field : getUtilityClass().getDeclaredFields()) { - assertThat(Modifier.isStatic(field.getModifiers()), is(true)); - } + @Test + public void testClassHasNoInstanceMethods() { + for (Method method : getUtilityClass().getDeclaredMethods()) { + assertThat(Modifier.isStatic(method.getModifiers()), is(true)); } + } - @Test - public void testClassHasNoSuperClass() { - assertThat(getUtilityClass().getSuperclass(), is(equalTo((Class) Object.class))); + @Test + public void testClassHasNoInstanceFields() { + for (Field field : getUtilityClass().getDeclaredFields()) { + assertThat(Modifier.isStatic(field.getModifiers()), is(true)); } + } + @Test + public void testClassHasNoSuperClass() { + assertThat(getUtilityClass().getSuperclass(), is(equalTo((Class) Object.class))); + } } diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtilsTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtilsTest.java index 39735863..3f96a146 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtilsTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtilsTest.java @@ -2,11 +2,31 @@ import org.testng.annotations.Test; -import java.util.*; -import java.util.concurrent.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Deque; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.Set; +import java.util.Stack; +import java.util.TreeSet; +import java.util.Vector; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.PriorityBlockingQueue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -14,51 +34,53 @@ */ public class CollectionInstanceUtilsTest extends AbstractUtilityClassTest { - @Override - protected Class getUtilityClass() { - return CollectionInstanceUtils.class; - } + @Override + protected Class getUtilityClass() { + return CollectionInstanceUtils.class; + } - @Test - public void testSupportedConcreteTypes() { - final List> collectionTypes = Arrays.asList(HashSet.class, - TreeSet.class, - CopyOnWriteArraySet.class, - LinkedHashSet.class, - ArrayList.class, - LinkedList.class, - Vector.class, - Stack.class, - PriorityQueue.class, - PriorityBlockingQueue.class, - ArrayDeque.class, - ConcurrentLinkedQueue.class, - LinkedBlockingQueue.class, - LinkedBlockingDeque.class); - for (Class collectionType : collectionTypes) { - final Collection collection = CollectionInstanceUtils.getCollection(collectionType); - assertThat(collection, is(notNullValue())); - assertThat(collection, is(instanceOf(collectionType))); - } + @Test + public void testSupportedConcreteTypes() { + final List> collectionTypes = + Arrays.asList( + HashSet.class, + TreeSet.class, + CopyOnWriteArraySet.class, + LinkedHashSet.class, + ArrayList.class, + LinkedList.class, + Vector.class, + Stack.class, + PriorityQueue.class, + PriorityBlockingQueue.class, + ArrayDeque.class, + ConcurrentLinkedQueue.class, + LinkedBlockingQueue.class, + LinkedBlockingDeque.class); + for (Class collectionType : collectionTypes) { + final Collection collection = CollectionInstanceUtils.getCollection(collectionType); + assertThat(collection, is(notNullValue())); + assertThat(collection, is(instanceOf(collectionType))); } + } - @Test - public void testSupportedAbstractTypes() { - assertThat(CollectionInstanceUtils.getCollection(Set.class), is(instanceOf(Set.class))); - assertThat(CollectionInstanceUtils.getCollection(List.class), is(instanceOf(List.class))); - assertThat(CollectionInstanceUtils.getCollection(Queue.class), is(instanceOf(Queue.class))); - assertThat(CollectionInstanceUtils.getCollection(Deque.class), is(instanceOf(Deque.class))); - assertThat(CollectionInstanceUtils.getCollection(Collection.class), is(instanceOf(Collection.class))); - } + @Test + public void testSupportedAbstractTypes() { + assertThat(CollectionInstanceUtils.getCollection(Set.class), is(instanceOf(Set.class))); + assertThat(CollectionInstanceUtils.getCollection(List.class), is(instanceOf(List.class))); + assertThat(CollectionInstanceUtils.getCollection(Queue.class), is(instanceOf(Queue.class))); + assertThat(CollectionInstanceUtils.getCollection(Deque.class), is(instanceOf(Deque.class))); + assertThat( + CollectionInstanceUtils.getCollection(Collection.class), is(instanceOf(Collection.class))); + } - @Test(expectedExceptions = IllegalArgumentException.class) - public void testUnknownType() { - CollectionInstanceUtils.getCollection(Class.class); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testNullValue() { - CollectionInstanceUtils.getCollection(null); - } + @Test(expectedExceptions = IllegalArgumentException.class) + public void testUnknownType() { + CollectionInstanceUtils.getCollection(Class.class); + } -} \ No newline at end of file + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNullValue() { + CollectionInstanceUtils.getCollection(null); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilterTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilterTest.java index 9241d343..0ea77ca3 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilterTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilterTest.java @@ -12,22 +12,26 @@ */ public class GetterMethodFilterTest { - @Test - public void testFailures() throws Exception { - final GetterMethodFilter filter = new GetterMethodFilter(); - assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getProperty")), is(false)); - assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getProperty", int.class)), is(false)); - assertThat(filter.matches(SampleClass.class.getDeclaredMethod("hasProperty")), is(false)); - assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getProperty", String.class)), is(false)); - assertThat(filter.matches(SampleClass.class.getDeclaredMethod("hasProperty", String.class)), is(false)); - assertThat(filter.matches(SampleClass.class.getDeclaredMethod("hasState")), is(false)); - assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getterMethod")), is(false)); - } + @Test + public void testFailures() throws Exception { + final GetterMethodFilter filter = new GetterMethodFilter(); + assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getProperty")), is(false)); + assertThat( + filter.matches(SampleClass.class.getDeclaredMethod("getProperty", int.class)), is(false)); + assertThat(filter.matches(SampleClass.class.getDeclaredMethod("hasProperty")), is(false)); + assertThat( + filter.matches(SampleClass.class.getDeclaredMethod("getProperty", String.class)), + is(false)); + assertThat( + filter.matches(SampleClass.class.getDeclaredMethod("hasProperty", String.class)), + is(false)); + assertThat(filter.matches(SampleClass.class.getDeclaredMethod("hasState")), is(false)); + assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getterMethod")), is(false)); + } - @Test - public void testProperGetter() throws Exception { - final GetterMethodFilter filter = new GetterMethodFilter(); - assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getValue")), is(true)); - } - -} \ No newline at end of file + @Test + public void testProperGetter() throws Exception { + final GetterMethodFilter filter = new GetterMethodFilter(); + assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getValue")), is(true)); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/PropertyUtilsTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/PropertyUtilsTest.java index 19caa543..cd1ab5f4 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/PropertyUtilsTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/PropertyUtilsTest.java @@ -2,7 +2,11 @@ import com.mmnaseri.utils.spring.data.error.ParserException; import com.mmnaseri.utils.spring.data.query.PropertyDescriptor; -import com.mmnaseri.utils.spring.data.sample.models.*; +import com.mmnaseri.utils.spring.data.sample.models.Address; +import com.mmnaseri.utils.spring.data.sample.models.NoAccessorPerson; +import com.mmnaseri.utils.spring.data.sample.models.Person; +import com.mmnaseri.utils.spring.data.sample.models.State; +import com.mmnaseri.utils.spring.data.sample.models.Zip; import com.mmnaseri.utils.spring.data.sample.usecases.tools.ClassWithErrorThrowingAccessors; import com.mmnaseri.utils.spring.data.sample.usecases.tools.ClassWithFinalId; import com.mmnaseri.utils.spring.data.sample.usecases.tools.ClassWithNoGetters; @@ -16,7 +20,10 @@ import java.util.Objects; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * @author Milad Naseri (m.m.naseri@gmail.com) @@ -24,250 +31,271 @@ */ public class PropertyUtilsTest extends AbstractUtilityClassTest { - @Override - protected Class getUtilityClass() { - return PropertyUtils.class; - } - - @Test(expectedExceptions = ParserException.class, - expectedExceptionsMessageRegExp = "Expected pattern '.*?' was not encountered.*") - public void testPropertyPathThatDoesNotStartWithCapitalLetter() { - PropertyUtils.getPropertyDescriptor(Person.class, "address"); - } - - @Test - public void testFirstLevelPropertyPath() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(Person.class, "Address"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("address")); - assertThat(descriptor.getType(), equalTo((Class) Address.class)); - } - - @Test - public void testFirstLevelPropertyWithoutExplicitBreaking() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(Person.class, "AddressZip"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("addressZip")); - assertThat(descriptor.getType(), equalTo((Class) Zip.class)); - } - - @Test - public void testPropertyWithExplicitBreaking() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(Person.class, "Address_Zip"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("address.zip")); - assertThat(descriptor.getType(), equalTo((Class) Zip.class)); - } - - @Test - public void testMultiLevelPropertyWithoutExplicitBreaking() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(Person.class, "AddressZipPrefix"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("addressZip.prefix")); - assertThat(descriptor.getType(), equalTo((Class) String.class)); - } - - @Test - public void testMultiLevelPropertyWithExplicitBreaking() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(Person.class, "Address_ZipPrefix"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("address.zip.prefix")); - assertThat(descriptor.getType(), equalTo((Class) String.class)); - } - - @Test(expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Person`") - public void testNonExistingFirstLevelProperty() { - PropertyUtils.getPropertyDescriptor(Person.class, "Xyz"); - } - - @Test(expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Zip`") - public void testNonExistingThirdLevelProperty() { - PropertyUtils.getPropertyDescriptor(Person.class, "Address_ZipXyz"); - } - - @Test - public void testFirstLevelPropertyWithoutExplicitBreakingUsingFields() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "AddressZip"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("addressZip")); - assertThat(descriptor.getType(), equalTo((Class) Zip.class)); - } - - @Test - public void testPropertyWithExplicitBreakingUsingFields() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, - "Address_Zip"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("address.zip")); - assertThat(descriptor.getType(), equalTo((Class) Zip.class)); - } - - @Test - public void testMultiLevelPropertyWithoutExplicitBreakingUsingFields() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, - "AddressZipPrefix"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("addressZip.prefix")); - assertThat(descriptor.getType(), equalTo((Class) String.class)); - } - - @Test - public void testMultiLevelPropertyWithExplicitBreakingUsingFields() { - final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, - "Address_ZipPrefix"); - assertThat(descriptor, is(notNullValue())); - assertThat(descriptor.getPath(), is("address.zip.prefix")); - assertThat(descriptor.getType(), equalTo((Class) String.class)); - } - - @Test(expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.NoAccessorPerson`") - public void testNonExistingFirstLevelPropertyUsingFields() { - PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Xyz"); - } - - @Test(expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Zip`") - public void testNonExistingThirdLevelPropertyUsingFields() { - PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Address_ZipXyz"); - } - - @Test - public void testReadingPropertyValue() { - final Person person = new Person(); - person.setAddress(new Address()); - person.getAddress().setCity("Tehran"); - person.getAddress().setState(new State()); - person.getAddress().getState().setName("Teheran"); - person.getAddress().getState().setAbbreviation("TEH"); - assertThat(PropertyUtils.getPropertyValue(person, "address"), Matchers.is(person.getAddress())); - assertThat(PropertyUtils.getPropertyValue(person, "address.city"), - Matchers.is(person.getAddress().getCity())); - assertThat(PropertyUtils.getPropertyValue(person, "address.state.name"), - Matchers.is(person.getAddress().getState().getName())); - assertThat(PropertyUtils.getPropertyValue(person, "address.state.abbreviation"), - Matchers.is(person.getAddress().getState().getAbbreviation())); - assertThat(PropertyUtils.getPropertyValue(person, "firstName"), is(nullValue())); - } - - @Test - public void testPrimitiveTypeConversion() { - assertThat(PropertyUtils.getTypeOf(int.class), is(Matchers.equalTo(Integer.class))); - assertThat(PropertyUtils.getTypeOf(float.class), is(Matchers.equalTo(Float.class))); - assertThat(PropertyUtils.getTypeOf(double.class), is(Matchers.equalTo(Double.class))); - assertThat(PropertyUtils.getTypeOf(byte.class), is(Matchers.equalTo(Byte.class))); - assertThat(PropertyUtils.getTypeOf(short.class), is(Matchers.equalTo(Short.class))); - assertThat(PropertyUtils.getTypeOf(long.class), is(Matchers.equalTo(Long.class))); - assertThat(PropertyUtils.getTypeOf(char.class), is(Matchers.equalTo(Character.class))); - assertThat(PropertyUtils.getTypeOf(boolean.class), is(Matchers.equalTo(Boolean.class))); - } - - @Test - public void testNonPrimitiveTypeConversion() { - assertThat(PropertyUtils.getTypeOf(Object.class), is(Matchers.equalTo(Object.class))); - assertThat(PropertyUtils.getTypeOf(String.class), is(Matchers.equalTo(String.class))); - assertThat(PropertyUtils.getTypeOf(BigDecimal.class), is(Matchers.equalTo(BigDecimal.class))); - assertThat(PropertyUtils.getTypeOf(Person.class), is(Matchers.equalTo(Person.class))); - } - - @Test - public void testPropertyNameFromGetterMethod() { - assertThat(PropertyUtils.getPropertyName( - Objects.requireNonNull(ReflectionUtils.findMethod(Person.class, "getAddress"))), - is("address")); - assertThat(PropertyUtils.getPropertyName( - Objects.requireNonNull(ReflectionUtils.findMethod(Person.class, "getAddressZip"))), - is("addressZip")); - } - - @Test - public void testReadingPropertyValueThroughField() throws Exception { - final ClassWithNoGetters object = new ClassWithNoGetters(); - final Field id = Objects.requireNonNull(ReflectionUtils.findField(ClassWithNoGetters.class, "id")); - id.setAccessible(true); - id.set(object, "1234"); - assertThat(PropertyUtils.getPropertyValue(object, "id"), is(id.get(object))); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testReadingPropertyValueThroughErrorThrowingGetter() { - final ClassWithErrorThrowingAccessors object = new ClassWithErrorThrowingAccessors(); - PropertyUtils.getPropertyValue(object, "id"); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testReadingNonExistentProperty() { - final Person person = new Person(); - PropertyUtils.getPropertyValue(person, "address.xyz"); - } - - @Test - public void testReadingWhenMiddlePropertyIsNull() { - assertThat(PropertyUtils.getPropertyValue(new Person().setAddress(new Address()), "address.zip.prefix"), - is(nullValue())); - } - - @Test - public void testSettingImmediatePropertyValueUsingField() throws Exception { - final ClassWithNoGetters object = new ClassWithNoGetters(); - final Field id = Objects.requireNonNull(ReflectionUtils.findField(ClassWithNoGetters.class, "id")); - id.setAccessible(true); - final String value = "12345"; - PropertyUtils.setPropertyValue(object, "id", value); - assertThat(id.get(object), Matchers.is(value)); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testSettingImmediatePropertyValueUsingErrorThrowingSetter() { - PropertyUtils.setPropertyValue(new ClassWithErrorThrowingAccessors(), "id", ""); - } - - @Test - public void testSettingImmediateFinalField() { - PropertyUtils.setPropertyValue(new ClassWithFinalId(), "id", ""); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testSettingUnknownProperty() { - PropertyUtils.setPropertyValue(new Person(), "xyz", ""); - } - - @Test - public void testSettingPropertyThroughSetters() { - final Person person = new Person(); - final String value = "123"; - final Object changed = PropertyUtils.setPropertyValue(person, "id", value); - assertThat(changed, Matchers.is(person)); - assertThat(person.getId(), is(value)); - } - - @Test - public void testSettingNestedProperty() { - final Person person = new Person().setAddress(new Address().setZip(new Zip())); - final String value = "Capital"; - final Object changed = PropertyUtils.setPropertyValue(person, "address.zip.area", value); - assertThat(changed, Matchers.is(person.getAddress().getZip())); - assertThat(person.getAddress().getZip().getArea(), is(value)); - } - - @Test - public void testSettingPropertyToNullThroughASetter() { - final Person person = new Person().setId("1234"); - PropertyUtils.setPropertyValue(person, "id", null); - assertThat(person.getId(), is(nullValue())); - } - - @Test(expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "Failed to set property value through the field .*") - public void testSettingPrimitiveValueToNullThroughSetter() { - PropertyUtils.setPropertyValue(new ClassWithPrimitiveField(), "position", null); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testSettingNestedPropertyWhenParentPropertyIsNull() { - PropertyUtils.setPropertyValue(new Person(), "address.zip", new Zip()); - } - -} \ No newline at end of file + @Override + protected Class getUtilityClass() { + return PropertyUtils.class; + } + + @Test( + expectedExceptions = ParserException.class, + expectedExceptionsMessageRegExp = "Expected pattern '.*?' was not encountered.*") + public void testPropertyPathThatDoesNotStartWithCapitalLetter() { + PropertyUtils.getPropertyDescriptor(Person.class, "address"); + } + + @Test + public void testFirstLevelPropertyPath() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(Person.class, "Address"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("address")); + assertThat(descriptor.getType(), equalTo((Class) Address.class)); + } + + @Test + public void testFirstLevelPropertyWithoutExplicitBreaking() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(Person.class, "AddressZip"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("addressZip")); + assertThat(descriptor.getType(), equalTo((Class) Zip.class)); + } + + @Test + public void testPropertyWithExplicitBreaking() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(Person.class, "Address_Zip"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("address.zip")); + assertThat(descriptor.getType(), equalTo((Class) Zip.class)); + } + + @Test + public void testMultiLevelPropertyWithoutExplicitBreaking() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(Person.class, "AddressZipPrefix"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("addressZip.prefix")); + assertThat(descriptor.getType(), equalTo((Class) String.class)); + } + + @Test + public void testMultiLevelPropertyWithExplicitBreaking() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(Person.class, "Address_ZipPrefix"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("address.zip.prefix")); + assertThat(descriptor.getType(), equalTo((Class) String.class)); + } + + @Test( + expectedExceptions = IllegalStateException.class, + expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Person`") + public void testNonExistingFirstLevelProperty() { + PropertyUtils.getPropertyDescriptor(Person.class, "Xyz"); + } + + @Test( + expectedExceptions = IllegalStateException.class, + expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Zip`") + public void testNonExistingThirdLevelProperty() { + PropertyUtils.getPropertyDescriptor(Person.class, "Address_ZipXyz"); + } + + @Test + public void testFirstLevelPropertyWithoutExplicitBreakingUsingFields() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "AddressZip"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("addressZip")); + assertThat(descriptor.getType(), equalTo((Class) Zip.class)); + } + + @Test + public void testPropertyWithExplicitBreakingUsingFields() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Address_Zip"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("address.zip")); + assertThat(descriptor.getType(), equalTo((Class) Zip.class)); + } + + @Test + public void testMultiLevelPropertyWithoutExplicitBreakingUsingFields() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "AddressZipPrefix"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("addressZip.prefix")); + assertThat(descriptor.getType(), equalTo((Class) String.class)); + } + + @Test + public void testMultiLevelPropertyWithExplicitBreakingUsingFields() { + final PropertyDescriptor descriptor = + PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Address_ZipPrefix"); + assertThat(descriptor, is(notNullValue())); + assertThat(descriptor.getPath(), is("address.zip.prefix")); + assertThat(descriptor.getType(), equalTo((Class) String.class)); + } + + @Test( + expectedExceptions = IllegalStateException.class, + expectedExceptionsMessageRegExp = + "Could not find property `xyz` on `class .*?\\.NoAccessorPerson`") + public void testNonExistingFirstLevelPropertyUsingFields() { + PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Xyz"); + } + + @Test( + expectedExceptions = IllegalStateException.class, + expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Zip`") + public void testNonExistingThirdLevelPropertyUsingFields() { + PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Address_ZipXyz"); + } + + @Test + public void testReadingPropertyValue() { + final Person person = new Person(); + person.setAddress(new Address()); + person.getAddress().setCity("Tehran"); + person.getAddress().setState(new State()); + person.getAddress().getState().setName("Teheran"); + person.getAddress().getState().setAbbreviation("TEH"); + assertThat(PropertyUtils.getPropertyValue(person, "address"), Matchers.is(person.getAddress())); + assertThat( + PropertyUtils.getPropertyValue(person, "address.city"), + Matchers.is(person.getAddress().getCity())); + assertThat( + PropertyUtils.getPropertyValue(person, "address.state.name"), + Matchers.is(person.getAddress().getState().getName())); + assertThat( + PropertyUtils.getPropertyValue(person, "address.state.abbreviation"), + Matchers.is(person.getAddress().getState().getAbbreviation())); + assertThat(PropertyUtils.getPropertyValue(person, "firstName"), is(nullValue())); + } + + @Test + public void testPrimitiveTypeConversion() { + assertThat(PropertyUtils.getTypeOf(int.class), is(Matchers.equalTo(Integer.class))); + assertThat(PropertyUtils.getTypeOf(float.class), is(Matchers.equalTo(Float.class))); + assertThat(PropertyUtils.getTypeOf(double.class), is(Matchers.equalTo(Double.class))); + assertThat(PropertyUtils.getTypeOf(byte.class), is(Matchers.equalTo(Byte.class))); + assertThat(PropertyUtils.getTypeOf(short.class), is(Matchers.equalTo(Short.class))); + assertThat(PropertyUtils.getTypeOf(long.class), is(Matchers.equalTo(Long.class))); + assertThat(PropertyUtils.getTypeOf(char.class), is(Matchers.equalTo(Character.class))); + assertThat(PropertyUtils.getTypeOf(boolean.class), is(Matchers.equalTo(Boolean.class))); + } + + @Test + public void testNonPrimitiveTypeConversion() { + assertThat(PropertyUtils.getTypeOf(Object.class), is(Matchers.equalTo(Object.class))); + assertThat(PropertyUtils.getTypeOf(String.class), is(Matchers.equalTo(String.class))); + assertThat(PropertyUtils.getTypeOf(BigDecimal.class), is(Matchers.equalTo(BigDecimal.class))); + assertThat(PropertyUtils.getTypeOf(Person.class), is(Matchers.equalTo(Person.class))); + } + + @Test + public void testPropertyNameFromGetterMethod() { + assertThat( + PropertyUtils.getPropertyName( + Objects.requireNonNull(ReflectionUtils.findMethod(Person.class, "getAddress"))), + is("address")); + assertThat( + PropertyUtils.getPropertyName( + Objects.requireNonNull(ReflectionUtils.findMethod(Person.class, "getAddressZip"))), + is("addressZip")); + } + + @Test + public void testReadingPropertyValueThroughField() throws Exception { + final ClassWithNoGetters object = new ClassWithNoGetters(); + final Field id = + Objects.requireNonNull(ReflectionUtils.findField(ClassWithNoGetters.class, "id")); + id.setAccessible(true); + id.set(object, "1234"); + assertThat(PropertyUtils.getPropertyValue(object, "id"), is(id.get(object))); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testReadingPropertyValueThroughErrorThrowingGetter() { + final ClassWithErrorThrowingAccessors object = new ClassWithErrorThrowingAccessors(); + PropertyUtils.getPropertyValue(object, "id"); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testReadingNonExistentProperty() { + final Person person = new Person(); + PropertyUtils.getPropertyValue(person, "address.xyz"); + } + + @Test + public void testReadingWhenMiddlePropertyIsNull() { + assertThat( + PropertyUtils.getPropertyValue( + new Person().setAddress(new Address()), "address.zip.prefix"), + is(nullValue())); + } + + @Test + public void testSettingImmediatePropertyValueUsingField() throws Exception { + final ClassWithNoGetters object = new ClassWithNoGetters(); + final Field id = + Objects.requireNonNull(ReflectionUtils.findField(ClassWithNoGetters.class, "id")); + id.setAccessible(true); + final String value = "12345"; + PropertyUtils.setPropertyValue(object, "id", value); + assertThat(id.get(object), Matchers.is(value)); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testSettingImmediatePropertyValueUsingErrorThrowingSetter() { + PropertyUtils.setPropertyValue(new ClassWithErrorThrowingAccessors(), "id", ""); + } + + @Test + public void testSettingImmediateFinalField() { + PropertyUtils.setPropertyValue(new ClassWithFinalId(), "id", ""); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testSettingUnknownProperty() { + PropertyUtils.setPropertyValue(new Person(), "xyz", ""); + } + + @Test + public void testSettingPropertyThroughSetters() { + final Person person = new Person(); + final String value = "123"; + final Object changed = PropertyUtils.setPropertyValue(person, "id", value); + assertThat(changed, Matchers.is(person)); + assertThat(person.getId(), is(value)); + } + + @Test + public void testSettingNestedProperty() { + final Person person = new Person().setAddress(new Address().setZip(new Zip())); + final String value = "Capital"; + final Object changed = PropertyUtils.setPropertyValue(person, "address.zip.area", value); + assertThat(changed, Matchers.is(person.getAddress().getZip())); + assertThat(person.getAddress().getZip().getArea(), is(value)); + } + + @Test + public void testSettingPropertyToNullThroughASetter() { + final Person person = new Person().setId("1234"); + PropertyUtils.setPropertyValue(person, "id", null); + assertThat(person.getId(), is(nullValue())); + } + + @Test( + expectedExceptions = IllegalStateException.class, + expectedExceptionsMessageRegExp = "Failed to set property value through the field .*") + public void testSettingPrimitiveValueToNullThroughSetter() { + PropertyUtils.setPropertyValue(new ClassWithPrimitiveField(), "position", null); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void testSettingNestedPropertyWhenParentPropertyIsNull() { + PropertyUtils.setPropertyValue(new Person(), "address.zip", new Zip()); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/StringUtilsTest.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/StringUtilsTest.java index 54f0fce7..425c6723 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/StringUtilsTest.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/StringUtilsTest.java @@ -11,50 +11,52 @@ */ public class StringUtilsTest extends AbstractUtilityClassTest { - @Override - protected Class getUtilityClass() { - return StringUtils.class; - } - - @Test(expectedExceptions = NullPointerException.class, - expectedExceptionsMessageRegExp = "String value cannot be null") - public void testCapitalizingNullValue() { - StringUtils.capitalize(null); - } - - @Test - public void testCapitalizingEmptyString() { - assertThat(StringUtils.capitalize(""), is("")); - } - - @Test - public void testCapitalizingUncapitalizedString() { - assertThat(StringUtils.capitalize("hello"), is("Hello")); - } - - @Test - public void testCapitalizingCapitalizedString() { - assertThat(StringUtils.capitalize("Hello"), is("Hello")); - } - - @Test(expectedExceptions = NullPointerException.class, - expectedExceptionsMessageRegExp = "String value cannot be null") - public void testUncapitalizingNullValue() { - StringUtils.uncapitalize(null); - } - - @Test - public void testUncapitalizingEmptyString() { - assertThat(StringUtils.uncapitalize(""), is("")); - } - - @Test - public void testUncapitalizingUncapitalizedString() { - assertThat(StringUtils.uncapitalize("hello"), is("hello")); - } - - @Test - public void testUncapitalizingCapitalizedString() { - assertThat(StringUtils.uncapitalize("Hello"), is("hello")); - } -} \ No newline at end of file + @Override + protected Class getUtilityClass() { + return StringUtils.class; + } + + @Test( + expectedExceptions = NullPointerException.class, + expectedExceptionsMessageRegExp = "String value cannot be null") + public void testCapitalizingNullValue() { + StringUtils.capitalize(null); + } + + @Test + public void testCapitalizingEmptyString() { + assertThat(StringUtils.capitalize(""), is("")); + } + + @Test + public void testCapitalizingUncapitalizedString() { + assertThat(StringUtils.capitalize("hello"), is("Hello")); + } + + @Test + public void testCapitalizingCapitalizedString() { + assertThat(StringUtils.capitalize("Hello"), is("Hello")); + } + + @Test( + expectedExceptions = NullPointerException.class, + expectedExceptionsMessageRegExp = "String value cannot be null") + public void testUncapitalizingNullValue() { + StringUtils.uncapitalize(null); + } + + @Test + public void testUncapitalizingEmptyString() { + assertThat(StringUtils.uncapitalize(""), is("")); + } + + @Test + public void testUncapitalizingUncapitalizedString() { + assertThat(StringUtils.uncapitalize("hello"), is("hello")); + } + + @Test + public void testUncapitalizingCapitalizedString() { + assertThat(StringUtils.uncapitalize("Hello"), is("hello")); + } +} diff --git a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/utils/TestUtils.java b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/utils/TestUtils.java index 25186762..7ade0e27 100644 --- a/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/utils/TestUtils.java +++ b/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/utils/TestUtils.java @@ -9,12 +9,11 @@ */ public class TestUtils { - public static List iterableToList(Iterable iterable) { - final List list = new ArrayList<>(); - for (E item : iterable) { - list.add(item); - } - return list; + public static List iterableToList(Iterable iterable) { + final List list = new ArrayList<>(); + for (E item : iterable) { + list.add(item); } - + return list; + } }