├── .gitignore ├── LICENSE ├── README.md ├── README_en.md ├── docs ├── user_guide.md └── user_guide_cn.md ├── pom.xml └── src ├── main └── java │ └── cn │ └── jimmyshi │ └── beanquery │ ├── BeanPropertyMatcher.java │ ├── BeanQuery.java │ ├── BeanQueryCustomizedMatchers.java │ ├── DefaultNullValuePropertyValueGetter.java │ ├── MatcherPredicate.java │ ├── Selector.java │ ├── comparators │ ├── ComparableObjectComparator.java │ ├── DefaultSortOrderableComparator.java │ ├── DelegatedSortOrderableComparator.java │ ├── PropertyComparator.java │ └── SortOrderableComparator.java │ └── selectors │ ├── BeanSelector.java │ ├── ClassSelector.java │ ├── CompositeSelector.java │ ├── DefaultSelector.java │ ├── KeyValueMapSelector.java │ ├── NestedKeyValueMapSelector.java │ ├── PropertySelector.java │ └── StringSelector.java └── test ├── java └── cn │ └── jimmyshi │ └── beanquery │ ├── BeanPropertyMatcherTest.java │ ├── DataLoader.java │ ├── DefaultNullValuePropertyValueGetterTest.java │ ├── comparators │ ├── ComparableObjectComparatorTest.java │ ├── DefaultSortOrderableComparatorTest.java │ └── PropertyComparatorTest.java │ ├── example │ ├── Address.java │ ├── Author.java │ ├── BeanQueryExample.java │ └── Book.java │ └── selectors │ ├── BeanSelectorTest.java │ ├── ClassSelectorTest.java │ ├── CompositeSelectorTest.java │ ├── KeyValueMapSelectorTest.java │ ├── NestedKeyValueMapSelectorTest.java │ ├── PropertySelectorTest.java │ ├── SelectorTestBase.java │ └── StringSelectorTest.java └── resources └── jsonData ├── expected ├── shouldBooksShortedByName.json ├── shouldInPriceAscOrder.json ├── shouldInPriceDescOrder.json ├── shouldIncludeNullValueWhenSortingAsc.json ├── shouldIncludeNullValueWhenSortingDesc.json ├── shouldNotChangeOrder.json ├── shouldReturnAllFields.json ├── shouldReturnFieldsOnly.json ├── shouldReturnFieldsOnlyWithAllOfAndExcept.json ├── testChainedOrderByProperties.json ├── testChainedOrderByPropertiesDesc.json ├── testNestedResultFeature.json ├── testNotExistingProperties.json ├── testSelectListNestedProperties.json ├── testSelectMapNestedProperties.json ├── testSelectNestedProperties.json ├── testSelectNullProperties.json ├── testUsingCollectionHamcestMatchers.json ├── testUsingMapHamcrestMatchers.json └── testUsingMultipleWhereConditions.json └── source ├── forChainedOrder.json ├── forMultipleWhereConditions.json ├── forOrders.json ├── forOrdersWithNullValue.json ├── main.json └── withoutAuthorMapAndList.json /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | .settings/ 4 | target/ 5 | .classpath 6 | .project 7 | 8 | # Package Files # 9 | *.jar 10 | *.war 11 | *.ear 12 | 13 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 14 | hs_err_pid* 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Bean-query 2 | ========== 3 | 4 | [Click Here](./README_en.md) for English version. 5 | 6 | Bean Query 复用[Apache Commons BeanUtils](http://commons.apache.org/proper/commons-beanutils/), [Apache Commons Collections](http://commons.apache.org/proper/commons-collections/), [Java Hamcrest](http://hamcrest.org/JavaHamcrest/) 7 | 来简化对Bean(集合)的排序,过滤和转换。 8 | 9 | # 文档 10 | 11 | * 阅读 [使用说明](./docs/user_guide_cn.md)来学习怎么使用 12 | * [BeanQueryExample.java](./src/test/java/cn/jimmyshi/beanquery/example/BeanQueryExample.java)用Junit测试用例的方式展示用法。 13 | 14 | # 快速入门 15 | 16 | BeanQuery的使用非常简单也很直接,例子代码如下: 17 | ```java 18 | //静态导入BeanQuery 19 | import static cn.jimmyshi.beanquery.BeanQuery.*; 20 | 21 | 22 | //使用 select、from、where、orderBy、desc和asc来组装一个Query,然后执行execute方法来获得结果。 23 | List> result = select("price,name,mainAuthor.name, authors[1].name as secondAuthor.name") 24 | .nested() 25 | .from(bookCollection) 26 | .where( 27 | //选择name属性值是"Book2"或者以“Book1”开头 28 | anyOf( 29 | value("name", startsWith("Book1")), 30 | value("name", is("Book2")) 31 | ), 32 | //并且prince的值位于区间(53,65) 33 | allOf( 34 | value("price", greaterThan(53d)), 35 | value("price",lessThan(65d)) 36 | ) 37 | ) 38 | .orderBy("name").desc()//根据"name"属性按照倒序对结果进行排列 39 | .execute(); 40 | ``` 41 | 执行完以上代码后,`result`列表中的每个Map都是`java.util.LinkedHashMap`实例,每个Map的都由下面的这三个Entry组成: 42 | 43 | * key=price, value=book.getPrice() 44 | * key=name, value=book.getName() 45 | * Key=mainAuthor, value=a map with { key=name, value=book.getMainAuthor().getName() } 46 | * key=secondsAuthor, value=a map with { key=name, value=book.getAuthors().get(1).getName() } 47 | 48 | -------------------------------------------------------------------------------- /README_en.md: -------------------------------------------------------------------------------- 1 | Bean-query 2 | ========== 3 | 4 | [点击这里](./README.md) 查看中文版. 5 | 6 | Bean Query reuses [Apache Commons BeanUtils](http://commons.apache.org/proper/commons-beanutils/), [Apache Commons Collections](http://commons.apache.org/proper/commons-collections/), [Java Hamcrest](http://hamcrest.org/JavaHamcrest/) to make sorting, filtering and converting a (collection of) java bean(s) easily. 7 | 8 | # Documents 9 | 10 | * Read [User Guide](./docs/user_guide.md) to study the usage. 11 | * Read [BeanQueryExample.java](./src/test/java/cn/jimmyshi/beanquery/example/BeanQueryExample.java) for Junit test case based code illustration. 12 | 13 | # Quick Start 14 | 15 | Usage of BeanQuery is simple, sample code below: 16 | ```java 17 | //import the BeanQuery 18 | import static cn.jimmyshi.beanquery.BeanQuery.*; 19 | 20 | 21 | //use select/from/where/orderBy/desc/asc to composite a query and execute it to get the result 22 | List> result = select("price,name,mainAuthor.name, authors[1].name as secondAuthor.name") 23 | .nested() 24 | .from(bookCollection) 25 | .where( 26 | //select books that name is Book2 or starts with Book1 27 | anyOf( 28 | value("name", startsWith("Book1")), 29 | value("name", is("Book2")) 30 | ), 31 | //and price is between (53,65) 32 | allOf( 33 | value("price", greaterThan(53d)), 34 | value("price",lessThan(65d)) 35 | ) 36 | ) 37 | .orderBy("name").desc()//sort the result in desc direction according to the name property 38 | .execute(); 39 | ``` 40 | After executing above codes, all items of the `result` object is a `java.util.LinkedHashMap` instance with 3 entries in below order: 41 | 42 | * key=price, value=book.getPrice() 43 | * key=name, value=book.getName() 44 | * Key=mainAuthor, value=a map with { key=name, value=book.getMainAuthor().getName() } 45 | * key=secondsAuthor, value=a map with { key=name, value=book.getAuthors().get(1).getName() } 46 | 47 | -------------------------------------------------------------------------------- /docs/user_guide.md: -------------------------------------------------------------------------------- 1 | User Guide 2 | === 3 | 4 | # Index 5 | 1. [Usage](#usage) 6 | 1.1. [Using Bean Query](#using-bean-query) 7 | 1.2. [Sorting](#sorting) 8 | 1.3. [Filtering](#filtering) 9 | 1.4. [Converting](#converting) 10 | 2. [Concepts](#concepts) 11 | 2.1. [Hamcrest matchers](#hamcrest-matchers) 12 | 2.2. [BeanUtils](#beanutils) 13 | 14 | # Usage 15 | Bean Query reuses [Apache Commons BeanUtils](http://commons.apache.org/proper/commons-beanutils/), [Apache Commons Collections](http://commons.apache.org/proper/commons-collections/), [Java Hamcrest](http://hamcrest.org/JavaHamcrest/) to make [sorting](#sorting), [filtering](#filtering) and [converting](#converting) a (collection of) java bean(s) easily. 16 | 17 | * The first section [Using Bean Query](#using-bean-query) guide you through all important methods. 18 | * Sections [sorting](#sorting), [filtering](#filtering) and [converting](#converting) classify usage according to different scenario. 19 | * If you prefer test case based illustration, you can read test case suit [BeanQueryExample.java](.././src/test/java/cn/jimmyshi/beanquery/example/BeanQueryExample.java). 20 | 21 | ## Using Bean Query 22 | In order to use BeanQuey, you need to know how to enable the BeanQuery project, how to create the BeanQuery instance, how to setup where condition, how to setup sorting `Comparator`, and how to execute the BeanQuery. 23 | This section lead you to go through all important methods of this BeanQuery lib. 24 | 25 | * 1. Added BeanQuery to your project dependencies. 26 | 27 | ```xml 28 | 29 | cn.jimmyshi 30 | bean-query 31 | ${Bean-Query-Version} 32 | 33 | ``` 34 | 35 | * 2. Static import BeanQuery 36 | 37 | ```java 38 | import static cn.jimmyshi.beanquery.BeanQuery.*; 39 | ``` 40 | 41 | * 3. Create a [`BeanQuery`](.././src/main/java/cn/jimmyshi/beanquery/BeanQuery.java) instance with one of the below methods. 42 | 43 | ```java 44 | public static BeanQuery> select(KeyValueMapSelector... selectors); 45 | public static BeanQuery> select(String selectString); 46 | public static BeanQuery> select(String... propertyStrings); 47 | public static BeanQuery selectBean(Class beanClass); 48 | public static BeanQuery select(Selector selector); 49 | ``` 50 | 51 | * 4. Setup filtering condition(optional) with below methods: 52 | 53 | ```java 54 | public BeanQuery where(Matcher matcher); 55 | public BeanQuery where(Matcher... matchers); 56 | ``` 57 | 58 | * 5. Setup comparators (optional) to sort the filtered result with below methods: 59 | 60 | ```java 61 | public BeanQuery orderBy(Comparator beanComparator); 62 | public BeanQuery orderBy(String orderByProperty); 63 | public BeanQuery orderBy(String orderByProperty, Comparator propertyValueComparator); 64 | public BeanQuery desc(); 65 | public BeanQuery asc(); 66 | ``` 67 | 68 | * 6. Execute the BeanQuery 69 | 70 | ```java 71 | public BeanQuery from(Collection from); 72 | public BeanQuery from(Object bean); 73 | public List execute(); 74 | public List executeFrom(Collection from); 75 | public T executeFrom(Object bean); 76 | ``` 77 | 78 | * 7. Composing all methods above together 79 | 80 | ```java 81 | //on a collection of beans 82 | List> result=select("name,price").from(bookCollection).where(value("name",startsWith("abc"))).execute(); 83 | List> result=select("name,price").where(value("name",startsWith("abc"))).executeFrom(bookCollection); 84 | //on one bean 85 | List> result=select("name,price").from(book).where(value("name",startsWith("abc"))).execute(); 86 | Map result=select("name,price").where(value("name",startsWith("abc"))).executeFrom(book); 87 | ``` 88 | 89 | ## Sorting 90 | 91 | Bean Query allows to sort a collection of java beans easily. Currently 3 sorting types are supported. 92 | 93 | ### Sorting Beans with comparator applied on bean 94 | ```java 95 | List sortedResult=selectBean(Book.class).orderBy(yourComparator).executeFrom(bookCollection); 96 | ``` 97 | Above codes sort `bookCollection` with `yourComparator`. It has the same effect as below code: 98 | ```java 99 | List copied = new ArrayList(bookCollection); 100 | Collections.sort(copied, yourComparator); 101 | sortedResult=copied; 102 | ``` 103 | ### Sorting Beans by comparator applied on bean property 104 | ```java 105 | List sortedResult=selectBean(Book.class).orderBy("author.name",beanPropertyComparator).executeFrom(bookCollection); 106 | ``` 107 | Above codes sort `bookCollection` with `beanPropertyComparator` applied on items' `author.name` property value. They have the same effect as below code: 108 | ```java 109 | List copied = new ArrayList(bookCollection); 110 | Collections.sort(copied, new Comparator() { 111 | @Override 112 | public int compare(Object o1, Object o2) { 113 | return beanPropertyComparator.compare(getProperty(o1), getProperty(o2)); 114 | } 115 | 116 | private Object getProperty(Object o) { 117 | try { 118 | return PropertyUtils.getProperty(o, "author.name"); 119 | } catch (Exception ex) { 120 | return null; 121 | } 122 | } 123 | }); 124 | sortedResult=copied; 125 | ``` 126 | 127 | The string object "author.name" is a property name to fetch property values from java beans, read section [BeanUtils property name](#beanutils-property-name) for more information. 128 | ### Sorting Beans by comparable bean property 129 | ```java 130 | List sortedResult=selectBean(Book.class).orderBy("author.name").executeFrom(bookCollection); 131 | ``` 132 | Above codes assume that each item of the `bookCollection` has a comparable property `author.name`. For each `author.name` call their `compareTo` method to compare. 133 | This function is implemented by providing a [`ComparableObjectComparator`](.././src/main/java/cn/jimmyshi/beanquery/comparators/ComparableObjectComparator.java) to compare the property value. The `compare` method of this `ComparableObjectComparator` works in the below way: 134 | 135 | 1. First convert the input objects to comparable instances(comparable1, comparable2). If they are null or not instance of comparable, the converted result is null. 136 | * If both converted result are null, return 0. 137 | * If comparable1 is null and comparable2 is not null, return -1 138 | * If comparable1 is not null and comparable2 is null, return 1 139 | 2. Then return comparable1.compareTo(comparable2) 140 | 3. If there is an exception in the above step, return 0 as the result 141 | 142 | ### Multiple Comparators 143 | 144 | ```java 145 | List sortedResult=select(Book.class).orderBy(orderByProperty("author.name").desc(), orderByProperty("bookName"),yourOwnComparator).executeFrom(bookCollection); 146 | ``` 147 | Code above compares items with their `author.name` property in DESC direction, if the result is equal, will compare with their `bookName` in ASC direction, and apply the `yourOwnComparator` comparator. 148 | 149 | 150 | ### DESC & ASC Sorting 151 | For all sorting methods, the default sorting way is considered as `ASC` sorting, you can easily revert the sort method by calling `desc()` method. Sample code as below: 152 | ```java 153 | List sortResult=selectBean(Book.class).orderBy("author.name",beanPropertyComparator).desc().executeFrom(bookCollection); 154 | ``` 155 | Above codes have the same effect as below code: 156 | ```java 157 | List copied = new ArrayList(bookCollection); 158 | Collections.sort(copied, new Comparator() { 159 | @Override 160 | public int compare(Object o1, Object o2) { 161 | return 0-beanPropertyComparator.compare(getProperty(o1), getProperty(o2));//to reverse the compare result 162 | } 163 | 164 | private Object getProperty(Object o) { 165 | try { 166 | return PropertyUtils.getProperty(o, "author.name"); 167 | } catch (Exception ex) { 168 | return null; 169 | } 170 | } 171 | }); 172 | sortedResult=copied; 173 | ``` 174 | You can apply the `desc()` method for other sorting methods like below: 175 | ```java 176 | List sortResult=selectBean(Book.class).orderBy(yourComparator).desc().executeFrom(bookCollection); 177 | List sortResult=selectBean(Book.class).orderBy("author.name").desc().executeFrom(bookCollection); 178 | ``` 179 | An `asc()` method is provided to rollback the calling of the `desc()` method so that you can sort different bean collections in different direction. Sample code as below: 180 | ```java 181 | BeanQuery query=selectBean(Book.class).orderBy(yourComparator).desc(); 182 | List result1=query.executeFrom(bookCollection1); 183 | List result2=query.asc().executeFrom(bookCollection2); 184 | ``` 185 | ## Filtering 186 | Filtering is implemented by 187 | 188 | 1. Converting Hamcrest Matchers to [commons-collections Predicate](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/Predicate.html), 189 | 2. Call [`CollectionUtils.filter`](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html#filter(java.lang.Iterable, org.apache.commons.collections4.Predicate)) method 190 | 191 | you can read section [Hamcrest matchers](#hamcrest-matchers) for more infomation. 192 | 193 | Bean Query allows you to filter a collection of java beans with Hamcrest Matchers. The matchers can be applied on bean itself or on bean properties. 194 | ```java 195 | List result=selectBean(Book.class) 196 | .where( 197 | //for books name is Book2 or starts with Book1 198 | anyOf(value("name", startsWith("Book1")), value("name", is("Book2"))), 199 | //for books price between (53,65) 200 | allOf(value("price", greaterThan(53d)),value("price",lessThan(65d))) 201 | ) 202 | .executeFrom(bookCollection); 203 | ``` 204 | After execution, object `result` contains books that their names started with "Book1" or is "Book2" and their prices between 53 & 65. 205 | 206 | * Static methods `anyOf`, `startsWith`, `is`, `greaterThan` and `lessThan` are built-in Hamcrest matcher methods. 207 | * Static method `BeanPropertyMatcher value(String property, Matcher matcher)` is defined by Bean Query to allow Hamcrest matchers applied on bean properties. 208 | * The string object "name" and "price" are a property name to fetch property value of a java bean, read section [BeanUtils property name](#beanutils-property-name) for more information. 209 | 210 | ## Converting 211 | Bean Query allows to convert the sorted/filtered result into a (list of) other object(s). There are 2 predefined converting behavior. 212 | ### Converting to specified java type 213 | ```java 214 | List sortResult=selectBean(Book.class).executeFrom(bookCollection); 215 | ``` 216 | Above codes convert the bookCollection into a list of `Book` instances. For items that are not instances of the `Book` class or its' subclass, the converted results are null. 217 | 218 | If you don't want to change items types in the result, you just want to filter/sort a (collection of) java bean(s) that might be of different type of unknown types, you can create the BeanQuery instance using `Object.class` like below. 219 | ```java 220 | BeanQuery beanQuery=selectBean(Object.class); 221 | ``` 222 | ### Converting to Map 223 | With the converting to map function, you can pick some (nested) properties of the (sorted/filtered result) bean(s) into a (list of) map(s). 224 | ```java 225 | List> result=select("price,name,mainAuthor.name as mainAuthorName").from(bookCollection).execute(); 226 | ``` 227 | After executing above line, all items of the `result` object is a `LinkedHashMap` instance with 3 entries in below order: 228 | 229 | * key=price, value=book.getPrice() 230 | * key=name, value=book.getName() 231 | * key=mainAuthorName, value=book.getMainAuthor().getName() 232 | 233 | To execute on a single object, you should code like below: 234 | ```java 235 | Map result=select("price,name,mainAuthor.name as mainAuthorName").executeFrom(book); 236 | ``` 237 | #### Converting to Map based on a java class 238 | ```java 239 | List> result = select(allOf(Book.class)).from(bookCollection).execute(); 240 | ``` 241 | Assuming besides the `getClass()` method, the `Book` class has 3 public property read methods: `public String getName()`,`public Double getPrice()` and `public Author getMainAuthor()`, 242 | After executing above codes, all items of the `result` object is a `LinkedHashMap` instance with 3 entries: 243 | 244 | * key=name, value=book.getName() 245 | * key=price, value=book.getPrice() 246 | * key=mainAuthor, value=book.getMainAuthor() 247 | 248 | If you don't want to know the price and name, you don't have to included them in the result map items. It is very simple to `except` them when creating the BeanQuery instance. Sample code below: 249 | ```java 250 | List> result = select(allOf(Book.class).except("name","price")).from(bookCollection).execute(); 251 | ``` 252 | You can also add more fields to the map items by using the `add` method. Sample code below: 253 | ```java 254 | List> result = select(allOf(Book.class).add("paperPrice","digitalPrice")).from(bookCollection).execute(); 255 | ``` 256 | **The `except` and `add` methods are designed for scenario that the based class to construct the BeanQuery and items in the from collection are of different types.** 257 | 258 | #### Converting to Map using property name and alias 259 | ```java 260 | List> result = select("name","price","price as p", "mainAuthor").executeFrom(bookCollection); 261 | List> result = select("name,price,price as p, mainAuthor").executeFrom(bookCollection); 262 | List> result = select(property("name"), property("price"), property("price").as("p"),property("mainAuthor")).executeFrom(bookCollection); 263 | ``` 264 | The above 3 lines of code has the same effect. After executing any line of them, all items of the `result` object is a `LinkedHashMap` instance with 4 entries: 265 | 266 | * key=name, value=book.getName() 267 | * key=price, value=book.getPrice() 268 | * key=p, value=book.getPrice() 269 | * key=mainAuthor, value=book.getMainAuthor() 270 | 271 | The string objects "name", "price", "mainAuthor" are property names to fetch property values of a java bean, read section [BeanUtils property name](#beanutils-property-name) for more information. 272 | 273 | The token "as" is a separator between property name and alias, it is case sensitive. 274 | 275 | #### Compose properties or alias with same prefix into a map 276 | 277 | ```java 278 | List> result= select("price,name,mainAuthor.name as author.name, mainAuthor.address as author.address").executeFrom(bookCollection); 279 | ``` 280 | After executing above line of code, all items of the `result` object is a `LinkedHashMap` instance with 4 entries: 281 | 282 | * key=name, value=book.getName() 283 | * key=price, value=book.getPrice() 284 | * key=author.name, value=book.getMainAuthor().getName() 285 | * key=author.address, value=book.getMainAuthor().getAddress() 286 | 287 | If we want to compose `author.name` and `author.address` into a map, we can call the nested() method, as shown below: 288 | 289 | ```java 290 | List> result= select("price,name,mainAuthor.name as author.name, mainAuthor.address as author.address").nested().executeFrom(bookCollection); 291 | ``` 292 | 293 | After executing above line of code, all items of the `result` object is a `LinkedHashMap` instance with 3 entries: 294 | 295 | * key=name, value=book.getName() 296 | * key=price, value=book.getPrice() 297 | * key=author, value=A LinkedHashMap with below items: 298 | * key=name, value=book.getMainAuthor().getName() 299 | * key=address, value=book.getMainAuthor().getAddress() 300 | 301 | #### Converting to Map with mixed selectors 302 | You can mix the java class based selector and property selector together. For example: 303 | ```java 304 | List> result = select(allOf(Book.class).except("authorList","authorMap","mainAuthor"), 305 | property("price").as("p"), 306 | property("mainAuthor") 307 | ).from(bookCollection).execute(); 308 | ``` 309 | ### Customize converting 310 | By implementing a instance of interface [`Selector`](.././src/main/java/cn/jimmyshi/beanquery/Selector.java) and create BeanQuery instance by calling the `public static BeanQuery select(Selector selector)` method, You can customize the converting. 311 | Sample code below: 312 | 313 | ```java 314 | List bookNames=select(new DefaultSelector() { 315 | @Override 316 | public String select(Object item) { 317 | return ((Book)item).getName(); 318 | } 319 | }).executeFrom(bookCollection); 320 | ``` 321 | 322 | The [`DefaultSelector`](.././src/main/java/cn/jimmyshi/beanquery/selectors/DefaultSelector.java) in above code is a default implementation of `Selector`. 323 | 324 | # Concepts 325 | ## Hamcrest matchers 326 | Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. 327 | 328 | * Read [Java Hamcrest Tutorial](https://code.google.com/p/hamcrest/wiki/Tutorial) to learn it. 329 | * Code repository of Hamcrest matchers: https://github.com/hamcrest/JavaHamcrest. 330 | 331 | Since `BeanQuery` is a subclass of the `org.hamcrest.Matchers` class, once you static import the `BeanQuery`, all the Hamcrest built-in matchers are available. 332 | 333 | ### Useful matchers 334 | Below content of this section is copied from the Hamcrest tutorial. 335 | 336 | Hamcrest comes with a library of useful matchers. Here are some of the most important ones. 337 | 338 | * Core 339 | - anything - always matches, useful if you don't care what the object under test is 340 | - describedAs - decorator to adding custom failure description 341 | - is - decorator to improve readability - see "Sugar", below 342 | * Logical 343 | - allOf - matches if all matchers match, short circuits (like Java &&) 344 | - anyOf - matches if any matchers match, short circuits (like Java ||) 345 | - not - matches if the wrapped matcher doesn't match and vice versa 346 | * Object 347 | - equalTo - test object equality using Object.equals 348 | - hasToString - test Object.toString 349 | - instanceOf, isCompatibleType - test type 350 | - notNullValue, nullValue - test for null 351 | - sameInstance - test object identity 352 | * Beans 353 | - hasProperty - test JavaBeans properties 354 | * Collections 355 | - array - test an array's elements against an array of matchers 356 | - hasEntry, hasKey, hasValue - test a map contains an entry, key or value 357 | - hasItem, hasItems - test a collection contains elements 358 | - hasItemInArray - test an array contains an element 359 | * Number 360 | - closeTo - test floating point values are close to a given value 361 | - greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo - test ordering 362 | * Text 363 | - equalToIgnoringCase - test string equality ignoring case 364 | - equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace 365 | - containsString, endsWith, startsWith - test string matching 366 | 367 | ## BeanUtils 368 | In this BeanQuery lib, we use `BeanUtils` to fetch property value from bean to convert, compare, filter. 369 | 370 | * Official web site: http://commons.apache.org/proper/commons-beanutils/ 371 | * User Guide: http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#package_description 372 | 373 | ### BeanUtils property name 374 | The feature we used a lot is the [`PropertyUtils.getProperty(Object bean, String name)`](http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/PropertyUtils.html#getProperty(java.lang.Object, java.lang.String)) method. 375 | With this method, it is very easy to fetch simple/nested/indexed/mapped property value of a java bean at runtime. 376 | 377 | The official guide of this method is section [2.2 Basic Property Access](http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#standard.basic) and [2.3 Nested Property Access](http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#standard.nested). 378 | Below sample codes illustrate how to use it in different scenarios. 379 | 380 | * **Get a simple property value** 381 | 382 | ```java 383 | String authorName=(String)PropertyUtils.getProperty(book,"authorName"); 384 | //above line is the same with below code 385 | String authorName=book.getAuthorName(); 386 | ``` 387 | 388 | * **Get a nested property value** 389 | 390 | ```java 391 | String authorName=(String)PropertyUtils.getProperty(book,"author.name"); 392 | //above line is the same with below code 393 | String authorName=book.getAuthor().getName(); 394 | ``` 395 | 396 | * **Get a indexed property value** 397 | 398 | ```java 399 | Author firstAuthor=(Author)PropertyUtils.getProperty(book,"authors[0]"); 400 | //above line is the same with below code 401 | Author firstAuthor=book.getAuthors().get(0); 402 | ``` 403 | 404 | * **Get a mapped property value** 405 | 406 | ```java 407 | String postCode=(String)PropertyUtils.getProperty(book,"author.addresses(home).postCode"); 408 | //above line is the same with below code 409 | Author postCode=book.getAuthor().getAddresses().get("home").getPostCode(); 410 | ``` -------------------------------------------------------------------------------- /docs/user_guide_cn.md: -------------------------------------------------------------------------------- 1 | 使用说明 2 | === 3 | 4 | # 目录 5 | 1. [用法](#usage) 6 | 1.1. [使用Bean Query](#using-bean-query) 7 | 1.2. [排序](#sorting) 8 | 1.3. [过滤](#filtering) 9 | 1.4. [转换](#converting) 10 | 2. [概念](#concepts) 11 | 2.1. [Hamcrest matchers](#hamcrest-matchers) 12 | 2.2. [BeanUtils](#beanutils) 13 | 14 | # 用法 15 | Bean Query 复用[Apache Commons BeanUtils](http://commons.apache.org/proper/commons-beanutils/), [Apache Commons Collections](http://commons.apache.org/proper/commons-collections/), [Java Hamcrest](http://hamcrest.org/JavaHamcrest/) 16 | 来简化对Bean(集合)的[排序](#sorting), [过滤](#filtering)和 [转换](#converting)。 17 | 18 | * 第一节 [使用Bean Query](#using-bean-query) 引导你了解BeanQuery所有重要的方法。 19 | * [排序](#sorting), [过滤](#filtering)和 [转换](#converting) 这三节根据使用场景分类介绍用法。 20 | * 如果你喜欢基于测试用例的使用介绍,[BeanQueryExample.java](.././src/test/java/cn/jimmyshi/beanquery/example/BeanQueryExample.java)用Junit测试用例的方式介绍了BeanQuery的使用方式。 21 | 22 | ## 使用Bean Query 23 | 要使用BeanQuery,你需要知道如何在项目中启用BeanQuery, 如何创建BeanQuery实例,如何设置过滤条件,如何设置`Comparator`用于排序以及如何执行BeanQuery。这一节引导你遍历一下BeanQuery库中所有重要的方法。 24 | 25 | * 1. 添加BeanQuery到你的项目中 26 | 27 | ```xml 28 | 29 | cn.jimmyshi 30 | bean-query 31 | ${Bean-Query-Version} 32 | 33 | ``` 34 | 35 | * 2. 静态导入BeanQuery 36 | 37 | ```java 38 | import static cn.jimmyshi.beanquery.BeanQuery.*; 39 | ``` 40 | 41 | * 3. 使用下面方法中的一个来创建[`BeanQuery`](.././src/main/java/cn/jimmyshi/beanquery/BeanQuery.java)实例 42 | 43 | ```java 44 | public static BeanQuery> select(KeyValueMapSelector... selectors); 45 | public static BeanQuery> select(String selectString); 46 | public static BeanQuery> select(String... propertyStrings); 47 | public static BeanQuery select(Class beanClass); 48 | public static BeanQuery select(Selector selector); 49 | ``` 50 | 51 | * 4. 使用下面的方法设置过滤条件(可选): 52 | 53 | ```java 54 | public BeanQuery where(Matcher matcher); 55 | public BeanQuery where(Matcher... matchers); 56 | ``` 57 | 58 | * 5. 使用下面的方法来设置comparators(可选)以对过滤完的结果进行排序: 59 | 60 | ```java 61 | public BeanQuery orderBy(Comparator beanComparator); 62 | public BeanQuery orderBy(String orderByProperty); 63 | public BeanQuery orderBy(String orderByProperty, Comparator propertyValueComparator); 64 | public BeanQuery desc(); 65 | public BeanQuery asc(); 66 | ``` 67 | 68 | * 6. 执行BeanQuery 69 | 70 | ```java 71 | public BeanQuery from(Collection from); 72 | public BeanQuery from(Object bean); 73 | public List execute(); 74 | public List executeFrom(Collection from); 75 | public T executeFrom(Object bean); 76 | ``` 77 | 78 | * 7. 把上面提到的这些方法组合到一起 79 | 80 | ```java 81 | //针对Bean集合 82 | List> result=select("name,price").from(bookCollection).where(value("name",startsWith("abc"))).execute(); 83 | List> result=select("name,price").where(value("name",startsWith("abc"))).executeFrom(bookCollection); 84 | //针对一个Bean 85 | List> result=select("name,price").from(book).where(value("name",startsWith("abc"))).execute(); 86 | Map result=select("name,price").where(value("name",startsWith("abc"))).executeFrom(book); 87 | ``` 88 | 89 | ## 排序 90 | Bean Query使得Java Bean集合的排序变得简单。当前支持三种排序方式。 91 | ### 使用应用在Bean上的Comparator来排序 92 | ```java 93 | List sortedResult=select(Book.class).orderBy(yourComparator).executeFrom(bookCollection); 94 | ``` 95 | 上面的代码使用`yourComparator`对`bookCollection`进行排序。它和下面的这些代码有同样的效果: 96 | ```java 97 | List copied = new ArrayList(bookCollection); 98 | Collections.sort(copied, yourComparator); 99 | sortedResult=copied; 100 | ``` 101 | ### 使用应用在Bean属性上的Comparator来排序 102 | ```java 103 | List sortedResult=select(Book.class).orderBy("author.name",beanPropertyComparator).executeFrom(bookCollection); 104 | ``` 105 | 上面的代码针对`beanPropertyComparator`Bean集合中的每个Bean的`author.name`属性值来进行排序。它和下面的这些代码有同样的效果: 106 | ```java 107 | List copied = new ArrayList(bookCollection); 108 | Collections.sort(copied, new Comparator() { 109 | @Override 110 | public int compare(Object o1, Object o2) { 111 | return beanPropertyComparator.compare(getProperty(o1), getProperty(o2)); 112 | } 113 | 114 | private Object getProperty(Object o) { 115 | try { 116 | return PropertyUtils.getProperty(o, "author.name"); 117 | } catch (Exception ex) { 118 | return null; 119 | } 120 | } 121 | }); 122 | sortedResult=copied; 123 | ``` 124 | 125 | 字符串 "author.name" 是一个用于从Bean中获取属性值的属性名,阅读章节[BeanUtils属性名](#beanutils-property-name) 以获取更多信息。 126 | ### 使用Bean的Comparable的属性来排序 127 | ```java 128 | List sortedResult=select(Book.class).orderBy("author.name").executeFrom(bookCollection); 129 | ``` 130 | 假设`bookCollection`中的每个Bean有一个实现了`Comparable`的名称为`author.name`的属性,上面的代码针对每个Bean的`author.name`调用他们的`compareTo`方法来比较从而进行排序 131 | 这个功能其实就是使用一个[`ComparableObjectComparator`](.././src/main/java/cn/jimmyshi/beanquery/comparators/ComparableObjectComparator.java) 应用在Bean的属性值上进行排序。`ComparableObjectComparator`类的`compare`方法的执行逻辑如下所示: 132 | 133 | 1. 首先把输入的参数转换为`Comparable`实例(comparable1,comparable2)。 如果输入参数是null或者不是`Comparable`的实现类,则转换结果视为null。 134 | * 如果转换结果都为null,则返回0 135 | * 如果comparable1是null,而comparable2不是null,则返回-1 136 | * 如果comparable1不是null,而comparable2是null,则返回1 137 | 2. 然后返回comparable1.compareTo(comparable2) 138 | 3. 如果在上面的步骤中有异常发生,则返回0。 139 | 140 | ### 使用多个Comparator 141 | 142 | ```java 143 | List sortedResult=select(Book.class).orderBy(orderByProperty("author.name").desc(), orderByProperty("bookName"),yourOwnComparator).executeFrom(bookCollection); 144 | ``` 145 | 上面的代码先使用默认`author.name`进行倒序比较,如果比较结果是一致的话,再使用`bookName`进行正序比较,如果还一致的话,就使用自定义的`yourOwnComparator`进行比较。 146 | 147 | ### 正序和逆序 148 | 在上面所述的这些排序中,默认情况下都视为正序,你可以使用`desc()`方法来逆转顺序。例子代码如下所示: 149 | ```java 150 | List sortResult=select(Book.class).orderBy("author.name",beanPropertyComparator).desc().executeFrom(bookCollection); 151 | ``` 152 | 上面的代码是下面代码的简化: 153 | ```java 154 | List copied = new ArrayList(bookCollection); 155 | Collections.sort(copied, new Comparator() { 156 | @Override 157 | public int compare(Object o1, Object o2) { 158 | return 0-beanPropertyComparator.compare(getProperty(o1), getProperty(o2));//逆转比较结果 159 | } 160 | 161 | private Object getProperty(Object o) { 162 | try { 163 | return PropertyUtils.getProperty(o, "author.name"); 164 | } catch (Exception ex) { 165 | return null; 166 | } 167 | } 168 | }); 169 | sortedResult=copied; 170 | ``` 171 | `desc()`方法也可以用于其他的排序方式,如下所示: 172 | ```java 173 | List sortResult=select(Book.class).orderBy(yourComparator).desc().executeFrom(bookCollection); 174 | List sortResult=select(Book.class).orderBy("author.name").desc().executeFrom(bookCollection); 175 | ``` 176 | 我们还提供了一个`asc()`方法用于抵消`desc()`方法,因此你可以使用不同的顺序来对不用的Bean集合进行排序。示例代码如下: 177 | ```java 178 | BeanQuery query=select(Book.class).orderBy(yourComparator).desc(); 179 | List result1=query.executeFrom(bookCollection1); 180 | List result2=query.asc().executeFrom(bookCollection2); 181 | ``` 182 | ## 过滤 183 | 过滤是这样实现的: 184 | 185 | 1. 首先把Hamcrest Matchers 转换成 [commons-collections Predicate](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/Predicate.html), 186 | 2. 调用[`CollectionUtils.filter`](http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html#filter(java.lang.Iterable, org.apache.commons.collections4.Predicate)) 方法来过滤。 187 | 188 | 更多信息请阅读[Hamcrest matchers](#hamcrest-matchers) 。 189 | 190 | Bean Query允许用户使用Hamcrest Matchers来对Bean集合进行过滤。Hamcrest Matchers可以应用在Bean本身也可以应用是Bean属性上。 191 | ```java 192 | List result=select(Book.class) 193 | .where( 194 | //for books name is Book2 or starts with Book1 195 | anyOf(value("name", startsWith("Book1")), value("name", is("Book2"))), 196 | //for books price between (53,65) 197 | allOf(value("price", greaterThan(53d)),value("price",lessThan(65d))) 198 | ) 199 | .executeFrom(bookCollection); 200 | ``` 201 | 执行完上面的代码之后,集合`result`中的book都是`name`属性都是以`Book1`开头,或者是等于`Book2`,并且其`price`属性的值界于53和65中间。 202 | 203 | 204 | * 静态方法`anyOf`, `startsWith`, `is`, `greaterThan`和`lessThan`都是Hamcrest matcher自带的方法。 205 | * 静态方法`BeanPropertyMatcher value(String property, Matcher matcher)`是Bean Query实现的用于把Hamcrest matchers应用到Bean属性上。 206 | * 字符串"name"和"price"都是用于获取Bean属性值的属性名,参考[BeanUtils属性名](#beanutils-property-name)以获取更多信息。 207 | 208 | ## 转换 209 | Bean Query可以用于把排序/过滤过的Bean(集合)转换成一种其他格式的Bean(集合)。当前提供了两种转换方式。 210 | 211 | ### 转换成特定的Java类型 212 | ```java 213 | List sortResult=select(Book.class).executeFrom(bookCollection); 214 | ``` 215 | 上面的代码把bookCollection转换成一个子项为`Book`类型的列表。对于bookCollection中非`Book`及其子类的对象,其转换结果为null。 216 | 217 | 如果你不想改变子项的类型,只是对对象集合进行过滤、排序的话,那么你可以使用`Object.class`来创建BeanQuery实例。代码如下所示: 218 | ```java 219 | BeanQuery beanQuery=select(Object.class); 220 | ``` 221 | ### 转换成Map对象 222 | 使用转换成Map对象这个功能,你可以抽取对象(集合中)对象的(嵌套的)属性形成Map对象(列表)。 223 | ```java 224 | List> result=select("price,name,mainAuthor.name as mainAuthorName").from(bookCollection).execute(); 225 | ``` 226 | 执行完上述代码之后,`result`列表中的每个Map都是`java.util.LinkedHashMap`实例,每个Map的都由下面的这三个Entry组成: 227 | 228 | * key=price, value=book.getPrice() 229 | * key=name, value=book.getName() 230 | * key=mainAuthorName, value=book.getMainAuthor().getName() 231 | 232 | 把一个对象转换成一个Map的代码如下所示: 233 | ```java 234 | Map result=select("price,name,mainAuthor.name as mainAuthorName").executeFrom(book); 235 | ``` 236 | #### 基于Java类信息把对象转换成Map 237 | ```java 238 | List> result = select(allOf(Book.class)).from(bookCollection).execute(); 239 | ``` 240 | 假设除了`getClass()`方法之外,类`Book`还有三个`public`的读方法:`public String getName()`,`public Double getPrice()`和`public Author getMainAuthor()`。在执行完上面的这块代码之后,`result`列表中的每个Map都是`java.util.LinkedHashMap`实例,每个Map的都由下面的这三个Entry组成: 241 | 242 | * key=name, value=book.getName() 243 | * key=price, value=book.getPrice() 244 | * key=mainAuthor, value=book.getMainAuthor() 245 | 246 | 如果你需要在结果Map中排除`price`和`name`,可以在创建BeanQuery实例时候使用`except`方法来排除之,例子代码如下: 247 | ```java 248 | List> result = select(allOf(Book.class).except("name","price")).from(bookCollection).execute(); 249 | ``` 250 | 你也可以使用`add`方法来添加其他的属性,例子代码如下: 251 | ```java 252 | List> result = select(allOf(Book.class).add("paperPrice","digitalPrice")).from(bookCollection).execute(); 253 | ``` 254 | **`except`和`add`方法是设计来用于这种场景的:用于构建BeanQuery的对象类型和用于执行的对象集合中的对象类型不是同一个类型。** 255 | 256 | #### 使用属性和别名把对象转换成Map 257 | ```java 258 | List> result = select("name","price","price as p", "mainAuthor").executeFrom(bookCollection); 259 | List> result = select("name,price,price as p, mainAuthor").executeFrom(bookCollection); 260 | List> result = select(property("name"), property("price"), property("price").as("p"),property("mainAuthor")).executeFrom(bookCollection); 261 | ``` 262 | 上面的三行代码都是一样的效果,执行完其中的任意一行之后,`result`列表中的每个Map都是`java.util.LinkedHashMap`实例,每个Map的都由下面的这四个Entry组成: 263 | 264 | * key=name, value=book.getName() 265 | * key=price, value=book.getPrice() 266 | * key=p, value=book.getPrice() 267 | * key=mainAuthor, value=book.getMainAuthor() 268 | 269 | 270 | 字符串"name","price"和"mainAuthor"是用于获取Java Bean的属性名称,请阅读[BeanUtils属性名](#beanutils-property-name)以获取更多信息。 271 | 272 | 字符"as"是用于隔离属性名称和别名的,必须是全小写的。 273 | 274 | #### 具有同样前缀的属性或者别名合成在一个Map中 275 | ```java 276 | List> result= select("price,name,mainAuthor.name as author.name, mainAuthor.address as author.address").executeFrom(bookCollection); 277 | ``` 278 | 上面这行代码执行完之后`result` 列表中的每个Map都由下面的这四个Entry组成: 279 | 280 | * key=name, value=book.getName() 281 | * key=price, value=book.getPrice() 282 | * key=author.name, value=book.getMainAuthor().getName() 283 | * key=author.address, value=book.getMainAuthor().getAddress() 284 | 285 | 如果我们想把上面的`author.name`和`author.aaddress`放到同一个Map中,我们可以调用`nested()`方法,如下所示: 286 | 287 | ```java 288 | List> result= select("price,name,mainAuthor.name as author.name, mainAuthor.address as author.address").nested().executeFrom(bookCollection); 289 | ``` 290 | 上面这行代码执行完之后`result` 列表中的每个Map都由下面的这三个Entry组成: 291 | 292 | * key=name, value=book.getName() 293 | * key=price, value=book.getPrice() 294 | * key=author, value=一个Map,内容如下: 295 | * key=name, value=book.getMainAuthor().getName() 296 | * key=address, value=book.getMainAuthor().getAddress() 297 | 298 | #### 混合使用Selector把对象转换成Map 299 | 可以混合使用基于Java类型的Selector和属性别名的Selector,比如: 300 | ```java 301 | List> result = select(allOf(Book.class).except("authorList","authorMap","mainAuthor"), 302 | property("price").as("p"), 303 | property("mainAuthor") 304 | ).from(bookCollection).execute(); 305 | ``` 306 | ### 自定义转换 307 | 通过实现接口[`Selector`](.././src/main/java/cn/jimmyshi/beanquery/Selector.java)的一个子类并使用`public static BeanQuery select(Selector selector)`方法来创建BeanQuery实例,就可以实现自定义转换。 例子代码如下: 308 | 309 | ```java 310 | List bookNames=select(new DefaultSelector() { 311 | @Override 312 | public String select(Object item) { 313 | return ((Book)item).getName(); 314 | } 315 | }).executeFrom(bookCollection); 316 | ``` 317 | 318 | 上面代码中的[`DefaultSelector`](.././src/main/java/cn/jimmyshi/beanquery/selectors/DefaultSelector.java)是`Selector`的一个默认实现。 319 | 320 | # 概念 321 | ## Hamcrest matchers 322 | Hamcrest是一个用于编写matcher对象来声明式的定义匹配规则的框架。 323 | 324 | * 教程地址:https://code.google.com/p/hamcrest/wiki/Tutorial 325 | * 代码仓库: https://github.com/hamcrest/JavaHamcrest 326 | 327 | 由于`BeanQuery`继承了`org.hamcrest.Matchers`,当你静态导入BeanQuery之后,所有Hamcrest内置的matcher就都可以直接使用了。 328 | 329 | ### 一些比较有用的matcher 330 | 下面这些内容是拷贝之Hamcrest的教程的。 331 | 332 | Hamcrest comes with a library of useful matchers. Here are some of the most important ones. 333 | 334 | * Core 335 | - anything - always matches, useful if you don't care what the object under test is 336 | - describedAs - decorator to adding custom failure description 337 | - is - decorator to improve readability - see "Sugar", below 338 | * Logical 339 | - allOf - matches if all matchers match, short circuits (like Java &&) 340 | - anyOf - matches if any matchers match, short circuits (like Java ||) 341 | - not - matches if the wrapped matcher doesn't match and vice versa 342 | * Object 343 | - equalTo - test object equality using Object.equals 344 | - hasToString - test Object.toString 345 | - instanceOf, isCompatibleType - test type 346 | - notNullValue, nullValue - test for null 347 | - sameInstance - test object identity 348 | * Beans 349 | - hasProperty - test JavaBeans properties 350 | * Collections 351 | - array - test an array's elements against an array of matchers 352 | - hasEntry, hasKey, hasValue - test a map contains an entry, key or value 353 | - hasItem, hasItems - test a collection contains elements 354 | - hasItemInArray - test an array contains an element 355 | * Number 356 | - closeTo - test floating point values are close to a given value 357 | - greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo - test ordering 358 | * Text 359 | - equalToIgnoringCase - test string equality ignoring case 360 | - equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace 361 | - containsString, endsWith, startsWith - test string matching 362 | 363 | ## BeanUtils 364 | 在这个BeanQuery库中,我们使用`BeanUtils`来获取Java Bean的属性值用于转换、比较和过滤。 365 | 366 | * 官方网址:http://commons.apache.org/proper/commons-beanutils/ 367 | * 使用说明: http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#package_description 368 | 369 | ### BeanUtils属性名 370 | 我们大量的使用了BeanUtils的[`PropertyUtils.getProperty(Object bean, String name)`](http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/PropertyUtils.html#getProperty(java.lang.Object, java.lang.String)) 这个方法。使用这个方法,我们可以很方便在运行时的获取Java Bean基本的、嵌套的、有索引的、映射型的Java Bean的属性值。 371 | 372 | 对于这个方法的官方指南是[2.2 Basic Property Access](http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#standard.basic)和[2.3 Nested Property Access](http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/package-summary.html#standard.nested)这两章。 373 | 374 | 下面的例子代码也说明了针对不同的使用场景的属性名的格式是怎么样的。 375 | * **获取基本属性的值** 376 | 377 | ```java 378 | String authorName=(String)PropertyUtils.getProperty(book,"authorName"); 379 | //上面这行代码和下面这行代码是一样的 380 | String authorName=book.getAuthorName(); 381 | ``` 382 | 383 | * **获取嵌套属性的值** 384 | 385 | ```java 386 | String authorName=(String)PropertyUtils.getProperty(book,"author.name"); 387 | //上面这行代码和下面这行代码是一样的 388 | String authorName=book.getAuthor().getName(); 389 | ``` 390 | 391 | * **获取有索引的属性的值** 392 | 393 | ```java 394 | Author firstAuthor=(Author)PropertyUtils.getProperty(book,"authors[0]"); 395 | //上面这行代码和下面这行代码是一样的 396 | Author firstAuthor=book.getAuthors().get(0); 397 | ``` 398 | 399 | * **获取Map中的Value** 400 | 401 | ```java 402 | String postCode=(String)PropertyUtils.getProperty(book,"author.addresses(home).postCode"); 403 | //上面这行代码和下面这行代码是一样的 404 | Author postCode=book.getAuthor().getAddresses().get("home").getPostCode(); 405 | ``` -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | cn.jimmyshi 4 | bean-query 5 | 1.1.6-SNAPSHOT 6 | jar 7 | Bean Query 8 | Java lib to do query/sorting/converting on a collection of java beans. 9 | https://github.com/Jimmy-Shi/bean-query 10 | 11 | 12 | The Apache License, Version 2.0 13 | http://www.apache.org/licenses/LICENSE-2.0.txt 14 | 15 | 16 | 17 | 18 | Jimmy Shi 19 | code@jimmyshi.cn 20 | 21 | 22 | 23 | scm:git:git@github.com:Jimmy-Shi/bean-query.git 24 | scm:git:git@github.com:Jimmy-Shi/bean-query.git 25 | git@github.com:Jimmy-Shi/bean-query.git 26 | HEAD 27 | 28 | 29 | 30 | release 31 | 32 | 33 | 34 | org.apache.maven.plugins 35 | maven-release-plugin 36 | 2.5 37 | 38 | true 39 | false 40 | release 41 | deploy 42 | 43 | 44 | 45 | 46 | org.apache.maven.plugins 47 | maven-source-plugin 48 | 2.2.1 49 | 50 | 51 | package 52 | 53 | jar-no-fork 54 | 55 | 56 | 57 | 58 | 59 | 60 | org.apache.maven.plugins 61 | maven-javadoc-plugin 62 | 2.9.1 63 | 64 | 65 | package 66 | 67 | jar 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.apache.maven.plugins 75 | maven-gpg-plugin 76 | 1.5 77 | 78 | 79 | verify 80 | 81 | sign 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | sonatype-oss 91 | https://oss.sonatype.org/content/repositories/snapshots/ 92 | 93 | 94 | sonatype-oss 95 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | org.apache.maven.plugins 104 | maven-compiler-plugin 105 | 3.2 106 | 107 | 1.6 108 | 1.6 109 | UTF-8 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | org.hamcrest 118 | hamcrest-all 119 | 1.3 120 | 121 | 122 | org.apache.commons 123 | commons-lang3 124 | 3.3.2 125 | 126 | 127 | org.apache.commons 128 | commons-collections4 129 | 4.0 130 | 131 | 132 | commons-beanutils 133 | commons-beanutils 134 | 1.9.2 135 | 136 | 137 | org.slf4j 138 | slf4j-api 139 | 1.7.6 140 | 141 | 142 | org.slf4j 143 | jcl-over-slf4j 144 | 1.7.6 145 | 146 | 147 | junit 148 | junit 149 | 4.11 150 | 151 | 152 | org.mockito 153 | mockito-core 154 | 1.9.5 155 | 156 | 157 | ch.qos.logback 158 | logback-classic 159 | 1.1.2 160 | 161 | 162 | com.fasterxml.jackson.core 163 | jackson-databind 164 | 2.4.0 165 | 166 | 167 | commons-io 168 | commons-io 169 | 2.4 170 | 171 | 172 | 173 | 174 | 175 | 176 | org.hamcrest 177 | hamcrest-all 178 | 179 | 180 | org.apache.commons 181 | commons-collections4 182 | 183 | 184 | commons-beanutils 185 | commons-beanutils 186 | 187 | 188 | commons-logging 189 | commons-logging 190 | 191 | 192 | 193 | 194 | org.slf4j 195 | jcl-over-slf4j 196 | 197 | 198 | org.apache.commons 199 | commons-lang3 200 | 201 | 202 | org.slf4j 203 | slf4j-api 204 | 205 | 206 | junit 207 | junit 208 | test 209 | 210 | 211 | org.mockito 212 | mockito-core 213 | test 214 | 215 | 216 | ch.qos.logback 217 | logback-classic 218 | test 219 | 220 | 221 | com.fasterxml.jackson.core 222 | jackson-databind 223 | test 224 | 225 | 226 | commons-io 227 | commons-io 228 | test 229 | 230 | 231 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/BeanPropertyMatcher.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import org.apache.commons.lang3.builder.ToStringBuilder; 4 | import org.apache.commons.lang3.builder.ToStringStyle; 5 | import org.hamcrest.BaseMatcher; 6 | import org.hamcrest.Description; 7 | import org.hamcrest.Matcher; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | public class BeanPropertyMatcher extends BaseMatcher { 12 | private transient Logger logger = LoggerFactory.getLogger(BeanPropertyMatcher.class); 13 | private String property; 14 | private Matcher matcher; 15 | 16 | public BeanPropertyMatcher(String property, Matcher matcher) { 17 | this.property = property; 18 | this.matcher = matcher; 19 | } 20 | 21 | 22 | public boolean matches(Object item) { 23 | Object propertyValue = DefaultNullValuePropertyValueGetter.getProperty(item, property); 24 | try { 25 | return matcher.matches(propertyValue); 26 | } catch (Exception ex) { 27 | logger.info("Exception [{}] when matching value [{}] (property [{}] of item [{}]) with matcher [{}]",ex.toString(), propertyValue, 28 | property, item, matcher); 29 | return false; 30 | } 31 | } 32 | 33 | @Override 34 | public String toString() { 35 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE, false); 36 | } 37 | 38 | @Override 39 | public void describeTo(Description description) { 40 | description.appendText(toString()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/BeanQuery.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.Collections; 6 | import java.util.Comparator; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | import org.apache.commons.collections4.CollectionUtils; 11 | import org.apache.commons.collections4.ComparatorUtils; 12 | import org.apache.commons.collections4.Predicate; 13 | import org.apache.commons.collections4.functors.TruePredicate; 14 | import org.hamcrest.Matcher; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | 18 | import cn.jimmyshi.beanquery.comparators.ComparableObjectComparator; 19 | import cn.jimmyshi.beanquery.comparators.DelegatedSortOrderableComparator; 20 | import cn.jimmyshi.beanquery.comparators.PropertyComparator; 21 | import cn.jimmyshi.beanquery.comparators.SortOrderableComparator; 22 | import cn.jimmyshi.beanquery.selectors.BeanSelector; 23 | import cn.jimmyshi.beanquery.selectors.ClassSelector; 24 | import cn.jimmyshi.beanquery.selectors.CompositeSelector; 25 | import cn.jimmyshi.beanquery.selectors.KeyValueMapSelector; 26 | import cn.jimmyshi.beanquery.selectors.NestedKeyValueMapSelector; 27 | import cn.jimmyshi.beanquery.selectors.PropertySelector; 28 | import cn.jimmyshi.beanquery.selectors.StringSelector; 29 | 30 | /** 31 | * Entry of the BeanQuery. Typical usage is as below. 32 | *
 33 |  * import static cn.jimmyshi.beanquery.BeanQuery.*;
 34 |  * List<Map<String,Object>> result=select("name,price,mainAuthor.name as authorName")
 35 |  *                                 .from(collectionOfBooks)
 36 |  *                                 .where(
 37 |  *                                    anyOf(
 38 |  *                                      value("name", startsWith("Book1")),
 39 |  *                                      value("name", is("Book2"))
 40 |  *                                      ),
 41 |  *                                    allOf(
 42 |  *                                      value("price", greaterThan(53d)),
 43 |  *                                      value("price",lessThan(65d))
 44 |  *                                      )
 45 |  *                                 )
 46 |  *                                 .orderBy("name").desc()
 47 |  *                                 .execute();
 48 |  * 
49 | */ 50 | @SuppressWarnings({ "unchecked", "rawtypes" }) 51 | public final class BeanQuery extends BeanQueryCustomizedMatchers { 52 | private transient Logger logger = LoggerFactory.getLogger(BeanQuery.class); 53 | private final Selector selector; 54 | private Collection from; 55 | private Predicate predicate = TruePredicate.truePredicate(); 56 | private SortOrderableComparator comparator; 57 | private boolean descSorting = false; 58 | 59 | private BeanQuery(Selector selector) { 60 | this.selector = selector; 61 | } 62 | 63 | /** 64 | * Convert the select into a NestedKeyValueMapSelector.
65 | * Note
: 66 | * This method is only available for BeanQueries with a KeyValuMapSelector. Calling this method on a BeanQeury with other types of selector will cause a IllegalStateExcewption. 67 | * 68 | */ 69 | public BeanQuery> nested(){ 70 | if(!(this.selector instanceof KeyValueMapSelector)){ 71 | throw new IllegalStateException("This is only for BeanQueries which has a KeyValueMapSelector selector. The current selector is a "+this.selector); 72 | } 73 | BeanQuery> result= new BeanQuery>(new NestedKeyValueMapSelector((KeyValueMapSelector)this.selector)); 74 | result.from=this.from; 75 | result.predicate=this.predicate; 76 | result.comparator=this.comparator; 77 | result.descSorting=this.descSorting; 78 | return result; 79 | } 80 | 81 | /** 82 | * Specify where to query from. 83 | * 84 | * @param from 85 | */ 86 | public BeanQuery from(Collection from) { 87 | this.from = from; 88 | return this; 89 | } 90 | 91 | /** 92 | * Same as from(Collections.singleton(bean)) 93 | */ 94 | public BeanQuery from(Object bean){ 95 | this.from=Collections.singleton(bean); 96 | return this; 97 | } 98 | 99 | /** 100 | * Support the Hamcrest Matcher as the query condition. Only items match this 101 | * matcher will be chosen. 102 | * 103 | * @param matcher 104 | */ 105 | public BeanQuery where(Matcher matcher) { 106 | this.predicate = new MatcherPredicate(matcher); 107 | return this; 108 | } 109 | 110 | /** 111 | * Support multiple Hamcrest Matchers as the query condition. Only items match 112 | * all the matchers will be chosen. 113 | */ 114 | public BeanQuery where(Matcher... matchers) { 115 | this.predicate = new MatcherPredicate(allOf(matchers)); 116 | return this; 117 | } 118 | 119 | /** 120 | * Specify the property of the Beans to be compared when ordering the result. 121 | * When comparing, the property value of the bean must be instance of 122 | * {@link Comparable}, Otherwise it will be treated as a null value. The null 123 | * value is sorted at the top in ASC sorting and at the bottom in DESC 124 | * sorting. The default Order is ASC order. 125 | * 126 | * @param orderByProperty 127 | */ 128 | public BeanQuery orderBy(String orderByProperty) { 129 | this.comparator = new DelegatedSortOrderableComparator(new PropertyComparator(orderByProperty, 130 | new ComparableObjectComparator())); 131 | return this; 132 | } 133 | 134 | /** 135 | * Specify the property of the beans to be compared by the 136 | * propertyValueComparator when sorting the result. If there is not a 137 | * accessible public read method of the property, the value of the property 138 | * passed to the propertyValueComparator will be null. 139 | */ 140 | public BeanQuery orderBy(String orderByProperty, Comparator propertyValueComparator) { 141 | this.comparator = new DelegatedSortOrderableComparator(new PropertyComparator(orderByProperty, 142 | propertyValueComparator)); 143 | return this; 144 | } 145 | 146 | /** 147 | * Specify the comparator used to compare the bean when sorting the result. 148 | */ 149 | public BeanQuery orderBy(Comparator beanComparator) { 150 | this.comparator = new DelegatedSortOrderableComparator(beanComparator); 151 | return this; 152 | } 153 | 154 | /** 155 | * Using an array of Comparators, applied in sequence until one returns not equal or the array is exhausted. 156 | */ 157 | public BeanQuery orderBy(Comparator... beanComparator) { 158 | this.comparator = new DelegatedSortOrderableComparator(ComparatorUtils.chainedComparator(beanComparator)); 159 | return this; 160 | } 161 | 162 | /** 163 | * Sort the result in DESC order. The default ordering is ASC order. If the 164 | * {@link #orderBy(String)} is not specified, calling this method does not 165 | * affect anything. 166 | */ 167 | public BeanQuery desc() { 168 | this.descSorting = true; 169 | return this; 170 | } 171 | 172 | /** 173 | * Sort the result in ASC order. The default ordering is ASC order. If the 174 | * {@link #orderBy(String)} is not specified, calling this method does not 175 | * affect anything. 176 | */ 177 | public BeanQuery asc() { 178 | this.descSorting = false; 179 | return this; 180 | } 181 | 182 | /** 183 | * Create a Comparator base on a property. 184 | */ 185 | public static SortOrderableComparator orderByProperty(String propertyName){ 186 | return new DelegatedSortOrderableComparator(new PropertyComparator(propertyName, 187 | new ComparableObjectComparator())); 188 | } 189 | 190 | /** 191 | * A convenient method of from(from).execute(); 192 | */ 193 | public List executeFrom(Collection from){ 194 | return from(from).execute(); 195 | } 196 | 197 | /** 198 | * Execute from a bean to check does it match the filtering condition and 199 | * convert it. 200 | */ 201 | public T executeFrom(Object bean) { 202 | List executeFromCollectionResult = executeFrom(Collections.singleton(bean)); 203 | if (CollectionUtils.isEmpty(executeFromCollectionResult)) { 204 | return null; 205 | } else { 206 | return executeFromCollectionResult.get(0); 207 | } 208 | } 209 | 210 | /** 211 | * Execute this Query. If query from a null or empty collection, an empty list 212 | * will be returned. 213 | * 214 | * @return 215 | */ 216 | public List execute() { 217 | if (CollectionUtils.isEmpty(from)) { 218 | logger.info("Querying from an empty collection, returning empty list."); 219 | return Collections.emptyList(); 220 | } 221 | 222 | List copied = new ArrayList(this.from); 223 | 224 | logger.info("Start apply predicate [{}] to collection with [{}] items.", predicate, copied.size()); 225 | CollectionUtils.filter(copied, this.predicate); 226 | logger.info("Done filtering collection, filtered result size is [{}]", copied.size()); 227 | 228 | if (null != this.comparator && copied.size()>1) { 229 | Comparator actualComparator = this.descSorting ? comparator.desc() : comparator.asc(); 230 | logger.info("Start to sort the filtered collection with comparator [{}]", actualComparator); 231 | Collections.sort(copied, actualComparator); 232 | logger.info("Done sorting the filtered collection."); 233 | } 234 | 235 | logger.info("Start to slect from filtered collection with selector [{}].", selector); 236 | List select = this.selector.select(copied); 237 | logger.info("Done select from filtered collection."); 238 | return select; 239 | 240 | } 241 | 242 | /** 243 | * Create a BeanQuery instance with multiple Selectors. 244 | * 245 | * @param selectors 246 | */ 247 | public static BeanQuery> select(KeyValueMapSelector... selectors) { 248 | return new BeanQuery>(new CompositeSelector(selectors)); 249 | } 250 | 251 | /** 252 | * Create a BeanQuery instance with select String, the select String is in 253 | * format "propertyName[ as alias][,propertyName[ as alias]]". For example:
254 | * BeanQuery beanQuery=select("name, price as p, address.officeAddress as address"); 255 | * When executing the BeanQuery instance created in above code will 256 | * return a list of map with 3 keys:[name,p,address]. 257 | */ 258 | public static BeanQuery> select(String selectString) { 259 | return new BeanQuery>(new StringSelector(selectString)); 260 | } 261 | 262 | /** 263 | * Create a BeanQuery instance with some propertyString, a property string is 264 | * in format "propertyName[ as alias]". For example:
265 | * BeanQuery beanQuery=select("name","price as p", "address.officeAddress as address"); 266 | *
267 | * When executing the BeanQuery instance created in above code will return a 268 | * list of map with 3 keys:[name,p,address]. 269 | */ 270 | public static BeanQuery> select(String... propertyStrings) { 271 | return new BeanQuery>(new StringSelector(propertyStrings)); 272 | } 273 | 274 | /** 275 | * Create a BeanQuery instance without the function of convert result into Map 276 | * function. If you just want to filter bean collection, sort bean collection 277 | * and want to get the execute result as a list of beans, you should use this 278 | * method to create a BeanQuery instance. 279 | * @deprecated use {@link #select(Class)} method instead 280 | */ 281 | public static BeanQuery selectBean(Class beanClass) { 282 | return new BeanQuery(new BeanSelector(beanClass)); 283 | } 284 | 285 | /** 286 | * Create a BeanQuery instance without the function of convert result into Map 287 | * function. If you just want to filter bean collection, sort bean collection 288 | * and want to get the execute result as a list of beans, you should use this 289 | * method to create a BeanQuery instance. 290 | */ 291 | public static BeanQuery select(Class beanClass) { 292 | return new BeanQuery(new BeanSelector(beanClass)); 293 | } 294 | 295 | /** 296 | * Allow client to create a BeanQuery instance with a customized selector. 297 | */ 298 | public static BeanQuery select(Selector selector){ 299 | return new BeanQuery(selector); 300 | } 301 | 302 | /** 303 | * Create a Selector that will use all the public readable 304 | * propertyNames(except the class property) as the keys. When saying 305 | * "public readable", means a property has a public read method, for example: 306 | *
    307 | *
  • public String getName() for property name.
  • 308 | *
  • public boolean isActive() for property active
  • 309 | *
310 | * Usage sample:
311 | * 312 | * BeanQuery beanQuery=select(allOf(Book.class).except("authorList","authorMap")); 313 | * 314 | */ 315 | public static ClassSelector allOf(Class clazz) { 316 | return new ClassSelector(clazz); 317 | } 318 | 319 | /** 320 | * Create a PropertySelector with the property name. Code sample below:
321 | * 322 | * BeanQuery beanQuery=select(property("name"), property("price"), property("price").as("p")); 323 | * 324 | */ 325 | public static PropertySelector property(String property) { 326 | return new PropertySelector(property); 327 | } 328 | 329 | /** 330 | * Create a matcher to apply on the property of the from items.Code sample 331 | * below:
332 | * 333 | * BeanQuery beanQuery=select(allOf(Book.class)).from(bookList).where(value("name",startsWith("Book1"))); 334 | * 335 | */ 336 | public static BeanPropertyMatcher value(String property, Matcher matcher) { 337 | return new BeanPropertyMatcher(property, matcher); 338 | } 339 | 340 | } 341 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/BeanQueryCustomizedMatchers.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import org.hamcrest.Matchers; 4 | 5 | /** 6 | * Entry of the Bean Query Customized matchers. 7 | */ 8 | public class BeanQueryCustomizedMatchers extends Matchers { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/DefaultNullValuePropertyValueGetter.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import org.apache.commons.beanutils.PropertyUtils; 4 | import org.apache.commons.lang3.StringUtils; 5 | import org.slf4j.LoggerFactory; 6 | 7 | public class DefaultNullValuePropertyValueGetter { 8 | public static Object getProperty(Object from,String propertyName){ 9 | if(null==from || StringUtils.isBlank(propertyName)){ 10 | LoggerFactory.getLogger(DefaultNullValuePropertyValueGetter.class).info("Object is null or the property [{}] is blank, returning null",propertyName); 11 | return null; 12 | } 13 | 14 | try { 15 | return PropertyUtils.getProperty(from, propertyName); 16 | } catch (Exception e) { 17 | LoggerFactory.getLogger(DefaultNullValuePropertyValueGetter.class).info("Exception [{}] when fetching property [{}] from object [{}], returning null as the value.",e.toString(),propertyName,from); 18 | return null; 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/MatcherPredicate.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import org.apache.commons.collections4.Predicate; 4 | import org.hamcrest.Matcher; 5 | 6 | public class MatcherPredicate implements Predicate { 7 | private final Matcher matcher; 8 | 9 | public MatcherPredicate(Matcher matcher) { 10 | this.matcher=matcher; 11 | } 12 | 13 | @Override 14 | public boolean evaluate(Object object) { 15 | return matcher.matches(object); 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return String.format("Predicate for Hamcrest Matcher [%s]", matcher); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/Selector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Selector response to select some properties from a java bean. 7 | * 8 | */ 9 | public interface Selector { 10 | 11 | /** 12 | * Select a list from the list of java bean. 13 | */ 14 | List select(List from); 15 | 16 | /** 17 | * select from the java bean. 18 | */ 19 | T select(Object item); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/comparators/ComparableObjectComparator.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.comparators; 2 | 3 | import java.util.Comparator; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | @SuppressWarnings("rawtypes") 9 | public class ComparableObjectComparator implements Comparator { 10 | private transient Logger logger = LoggerFactory.getLogger(ComparableObjectComparator.class); 11 | 12 | /** 13 | *
    14 | *
  1. First convert the input objects to comparable instances(comparable1, 15 | * comparable2). If they are null or not instance of comparable, the converted 16 | * result is null. 17 | *
      18 | *
    • If both converted result are null, return 0.
    • 19 | *
    • If comparable1 is null and comparable2 is not null, return -1
    • 20 | *
    • If comparable1 is not null and comparable2 is null, return 1
    • 21 | *
    22 | *
  2. 23 | *
  3. Then return comparable1.compareTo(comparable2)
  4. 24 | *
  5. If there is an exception in the above step, return 0 as the result
  6. 25 | *
26 | */ 27 | @SuppressWarnings("unchecked") 28 | @Override 29 | public int compare(Object o1, Object o2) { 30 | logger.debug("Comparing [{}] and [{}]", o1, o2); 31 | int result = 0; 32 | Comparable comparable1 = asNullIfNotComparable(o1); 33 | Comparable comparable2 = asNullIfNotComparable(o2); 34 | 35 | if (comparable1 == null && comparable2 == null) { 36 | logger.debug("Both items are null, result is 0"); 37 | result=0; 38 | } else if (comparable1 == null && comparable2 != null) { 39 | logger.debug("comparable1 is null & comparable2 [{}] is not null, result is -1", comparable2); 40 | result = -1; 41 | } else if (comparable1 != null && comparable2 == null) { 42 | logger.debug("comparable1 [{}] is not null & comparable2 is null, result is 1", comparable1); 43 | result = 1; 44 | } else { 45 | try { 46 | result = comparable1.compareTo(comparable2); 47 | logger.debug("comparable1 [{}] compareTo comparable2 [{}] result is [{}]", comparable1, comparable2, result); 48 | } catch (Exception ex) { 49 | logger.debug("Get exception [{}] when comparable1 [{}] compareTo comparable2 [{}], set result as 0", 50 | ex.toString(), comparable1, comparable2); 51 | result = 0; 52 | } 53 | } 54 | logger.debug("Compared result is [{}]", result); 55 | return result; 56 | } 57 | 58 | private Comparable asNullIfNotComparable(Object value) { 59 | if (value == null) { 60 | return null; 61 | } 62 | if (!(value instanceof Comparable)) { 63 | return null; 64 | } 65 | return (Comparable) value; 66 | 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/comparators/DefaultSortOrderableComparator.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.comparators; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | public abstract class DefaultSortOrderableComparator implements SortOrderableComparator { 7 | private transient Logger logger = LoggerFactory.getLogger(DefaultSortOrderableComparator.class); 8 | private boolean desc = false; 9 | 10 | @Override 11 | public int compare(T o1, T o2) { 12 | int ascResult = ascCompare(o1, o2); 13 | int finalResult = desc ? 0 - ascResult : ascResult; 14 | logger.debug("desc [{}], ascResult [{}], finalResult [{}]", desc, ascResult, finalResult); 15 | return finalResult; 16 | } 17 | 18 | protected abstract int ascCompare(T o1, T o2); 19 | 20 | @Override 21 | public SortOrderableComparator desc() { 22 | desc = true; 23 | return this; 24 | } 25 | 26 | @Override 27 | public SortOrderableComparator asc() { 28 | desc = false; 29 | return this; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/comparators/DelegatedSortOrderableComparator.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.comparators; 2 | 3 | import java.util.Comparator; 4 | 5 | import org.apache.commons.lang3.builder.ToStringBuilder; 6 | import org.apache.commons.lang3.builder.ToStringStyle; 7 | 8 | public class DelegatedSortOrderableComparator extends DefaultSortOrderableComparator { 9 | private Comparator delegated; 10 | 11 | public DelegatedSortOrderableComparator(Comparator delegated) { 12 | this.delegated = delegated; 13 | } 14 | 15 | @Override 16 | protected int ascCompare(T o1, T o2) { 17 | return delegated.compare(o1, o2); 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE,false); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/comparators/PropertyComparator.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.comparators; 2 | 3 | import java.util.Comparator; 4 | 5 | import org.apache.commons.lang3.builder.ToStringBuilder; 6 | import org.apache.commons.lang3.builder.ToStringStyle; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import cn.jimmyshi.beanquery.DefaultNullValuePropertyValueGetter; 11 | 12 | @SuppressWarnings("rawtypes") 13 | public class PropertyComparator implements Comparator { 14 | private transient Logger logger = LoggerFactory.getLogger(PropertyComparator.class); 15 | private final String propertyName; 16 | private final Comparator comparator; 17 | 18 | public PropertyComparator(String propertyName, Comparator propertyValueComparator) { 19 | this.propertyName = propertyName; 20 | this.comparator = propertyValueComparator; 21 | } 22 | 23 | public PropertyComparator(String propertyName) { 24 | this(propertyName, new ComparableObjectComparator()); 25 | } 26 | 27 | @SuppressWarnings("unchecked") 28 | @Override 29 | public int compare(Object o1, Object o2) { 30 | logger.debug("comparing [{}] and [{}] with comparator [{}].", o1, o2,this); 31 | int result = 0; 32 | Object property1 = DefaultNullValuePropertyValueGetter.getProperty(o1, propertyName); 33 | Object property2 = DefaultNullValuePropertyValueGetter.getProperty(o2, propertyName); 34 | result=comparator.compare(property1, property2); 35 | logger.debug("Compare result is [{}]", result); 36 | return result; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE,false); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/comparators/SortOrderableComparator.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.comparators; 2 | 3 | import java.util.Comparator; 4 | 5 | public interface SortOrderableComparator extends Comparator { 6 | SortOrderableComparator desc(); 7 | 8 | SortOrderableComparator asc(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/selectors/BeanSelector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import org.apache.commons.lang3.builder.ToStringBuilder; 4 | import org.apache.commons.lang3.builder.ToStringStyle; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | /** 9 | * Selector that cast the item to the type used to construct the BeanSelector 10 | * instance. 11 | * 12 | */ 13 | public class BeanSelector extends DefaultSelector { 14 | private transient Logger logger = LoggerFactory.getLogger(BeanSelector.class); 15 | private Class itemClass; 16 | 17 | public BeanSelector(Class itemClass) { 18 | this.itemClass = itemClass; 19 | } 20 | 21 | /** 22 | * If the item is null, return null. If the item is instance of the 23 | * constructor parameter itemClass, return the type cast result, otherwise, 24 | * return null. 25 | */ 26 | @Override 27 | public T select(Object item) { 28 | if (item == null) { 29 | return null; 30 | } 31 | 32 | if (itemClass.isInstance(item)) { 33 | return itemClass.cast(item); 34 | } 35 | logger.debug("item [{}] is not assignable to class [{}], returning null", item, itemClass); 36 | return null; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE,false); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/selectors/ClassSelector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import java.beans.PropertyDescriptor; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.apache.commons.beanutils.PropertyUtils; 9 | import org.apache.commons.lang3.ArrayUtils; 10 | import org.apache.commons.lang3.StringUtils; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | /** 15 | * Selector that use the bean properties as the key and the property values as 16 | * the value. Because every object has a "class" property which is not required 17 | * in most scenario, it will be excluded from the result. If you really want it, 18 | * you can use the {@link #add(String...)} method to add it in the result map. 19 | */ 20 | public class ClassSelector extends KeyValueMapSelector { 21 | private transient Logger logger = LoggerFactory.getLogger(ClassSelector.class); 22 | private List propertySelectors = new LinkedList(); 23 | private CompositeSelector compositeSelector = new CompositeSelector(); 24 | 25 | /** 26 | * @param clazz 27 | * null will cause the select methods returning an empty Map or a 28 | * list of Empty map as the result. 29 | */ 30 | public ClassSelector(Class clazz) { 31 | if (null == clazz) { 32 | logger.warn("Input class is null"); 33 | return; 34 | } 35 | PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(clazz); 36 | for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { 37 | boolean propertyReadable = propertyDescriptor.getReadMethod() != null; 38 | String propertyName = propertyDescriptor.getName(); 39 | // ignore the class property 40 | if ("class".equals(propertyName)) { 41 | continue; 42 | } 43 | 44 | if (propertyReadable) { 45 | PropertySelector propertySelector = new PropertySelector(propertyDescriptor.getName()); 46 | propertySelectors.add(propertySelector); 47 | compositeSelector.addSubSelector(propertySelector); 48 | } 49 | } 50 | } 51 | 52 | /** 53 | * Exclude properties from the result map. 54 | */ 55 | public ClassSelector except(String... propertyNames) { 56 | if(ArrayUtils.isEmpty(propertyNames)){ 57 | return this; 58 | } 59 | 60 | boolean updated = false; 61 | for (String propertyToRemove : propertyNames) { 62 | if (removePropertySelector(propertyToRemove)) { 63 | updated = true; 64 | } 65 | } 66 | 67 | if (updated) { 68 | compositeSelector = new CompositeSelector(this.propertySelectors); 69 | } 70 | return this; 71 | } 72 | 73 | private boolean removePropertySelector(String propertyName) { 74 | if (StringUtils.isBlank(propertyName)) { 75 | return false; 76 | } 77 | 78 | for (PropertySelector selector : propertySelectors) { 79 | if (selector.getProperty().equals(propertyName)) { 80 | propertySelectors.remove(selector); 81 | return true; 82 | } 83 | } 84 | return false; 85 | } 86 | 87 | /** 88 | * Include properties in the result map. 89 | */ 90 | public ClassSelector add(String... propertyNames) { 91 | if (ArrayUtils.isNotEmpty(propertyNames)) { 92 | for (String propertyNameToAdd : propertyNames) { 93 | addPropertySelector(propertyNameToAdd); 94 | } 95 | } 96 | return this; 97 | } 98 | 99 | private void addPropertySelector(String propertyNameToAdd) { 100 | if (StringUtils.isBlank(propertyNameToAdd)) { 101 | return; 102 | } 103 | 104 | for (PropertySelector propertySelector : propertySelectors) { 105 | if (propertySelector.getProperty().equals(propertyNameToAdd)) { 106 | return; 107 | } 108 | } 109 | 110 | PropertySelector newPropertySelector = new PropertySelector(propertyNameToAdd); 111 | propertySelectors.add(newPropertySelector); 112 | compositeSelector.addSubSelector(newPropertySelector); 113 | } 114 | 115 | @Override 116 | protected Map doSelect(Object item) { 117 | return this.compositeSelector.select(item); 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/selectors/CompositeSelector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.LinkedHashMap; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | import org.apache.commons.collections4.CollectionUtils; 12 | import org.apache.commons.collections4.ListUtils; 13 | import org.apache.commons.lang3.ArrayUtils; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | 17 | public class CompositeSelector extends KeyValueMapSelector{ 18 | private transient Logger logger = LoggerFactory.getLogger(CompositeSelector.class); 19 | private static final List SINGLETON_NULL_LIST = Collections.singletonList(null); 20 | private final List selectors; 21 | 22 | public CompositeSelector(KeyValueMapSelector... selectors) { 23 | if (ArrayUtils.isEmpty(selectors)) { 24 | this.selectors = new LinkedList(); 25 | } else { 26 | this.selectors = new LinkedList(Arrays.asList(selectors)); 27 | removeNullSubSelectors(); 28 | } 29 | } 30 | 31 | CompositeSelector() { 32 | this.selectors = new LinkedList(); 33 | } 34 | 35 | CompositeSelector(List selectors) { 36 | this.selectors = new ArrayList(ListUtils.emptyIfNull(selectors)); 37 | removeNullSubSelectors(); 38 | } 39 | 40 | private void removeNullSubSelectors() { 41 | this.selectors.removeAll(SINGLETON_NULL_LIST); 42 | } 43 | 44 | CompositeSelector addSubSelector(KeyValueMapSelector subSelector) { 45 | if (null != subSelector) { 46 | this.selectors.add(subSelector); 47 | } 48 | return this; 49 | } 50 | 51 | @Override 52 | protected Map doSelect(Object item) { 53 | if (CollectionUtils.isEmpty(selectors)) { 54 | logger.debug("Not any subSelectors found, returning emptyMap"); 55 | return Collections.emptyMap(); 56 | } 57 | 58 | Map result = new LinkedHashMap(); 59 | for (KeyValueMapSelector selector : selectors) { 60 | result.putAll(selector.select(item)); 61 | } 62 | return result; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/selectors/DefaultSelector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | import org.apache.commons.collections4.CollectionUtils; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import cn.jimmyshi.beanquery.Selector; 12 | 13 | /** 14 | * Selector that implemented the select(List<?> from) methods. 15 | */ 16 | public abstract class DefaultSelector implements Selector { 17 | private transient Logger logger = LoggerFactory.getLogger(DefaultSelector.class); 18 | 19 | @Override 20 | public List select(List from) { 21 | if (CollectionUtils.isEmpty(from)) { 22 | logger.info("The from collection is empty, returning empty List"); 23 | return Collections.emptyList(); 24 | } 25 | 26 | return doSelect(from); 27 | } 28 | 29 | protected List doSelect(List notEmptyFrom) { 30 | List result = new ArrayList(notEmptyFrom.size()); 31 | for (Object item : notEmptyFrom) { 32 | result.add(select(item)); 33 | } 34 | return result; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/selectors/KeyValueMapSelector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import java.util.Map; 4 | 5 | import org.apache.commons.lang3.builder.ToStringBuilder; 6 | import org.apache.commons.lang3.builder.ToStringStyle; 7 | 8 | public abstract class KeyValueMapSelector extends DefaultSelector> { 9 | 10 | @Override 11 | public Map select(Object item) { 12 | return doSelect(item); 13 | } 14 | 15 | protected abstract Map doSelect(Object item) ; 16 | 17 | @Override 18 | public String toString() { 19 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE,false); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/selectors/NestedKeyValueMapSelector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.Map.Entry; 6 | 7 | import org.apache.commons.collections4.MapUtils; 8 | import org.apache.commons.lang3.StringUtils; 9 | 10 | /** 11 | * A selector that sorted some of the result key-value pairs into a map which has the same prefix ended with ".". 12 | * For example, 13 | *
    14 | *
  • Without this: result of select("a1, a2.b, a2.c") is a list of map with 3 keys: a1, a2.b, a2.c.
  • 15 | *
  • With this, result of select("a1, a2.b, a2.c") will be a list of map with 2 keys: a1, a2. and the value of a2 is a map with keys: b and c
  • 16 | *
17 | * 18 | * This class is created to fulfill requirement: https://github.com/Jimmy-Shi/bean-query/issues/9 19 | * 20 | */ 21 | public class NestedKeyValueMapSelector extends KeyValueMapSelector { 22 | private KeyValueMapSelector selector; 23 | 24 | public NestedKeyValueMapSelector(KeyValueMapSelector sourceSelector) { 25 | this.selector=sourceSelector; 26 | } 27 | 28 | @Override 29 | protected Map doSelect(Object item) { 30 | Map originalResult = this.selector.select(item); 31 | if(MapUtils.isEmpty(originalResult)){ 32 | return originalResult; 33 | } 34 | 35 | Map result=new LinkedHashMap(); 36 | for (Entry originalItem : originalResult.entrySet()) { 37 | String key = originalItem.getKey(); 38 | Object value = originalItem.getValue(); 39 | 40 | if(StringUtils.isBlank(key) || (!key.contains("."))){ 41 | result.put(key, value); 42 | continue; 43 | } 44 | addNestedKeyValue(key, value, result); 45 | } 46 | 47 | return result; 48 | } 49 | 50 | private void addNestedKeyValue(String key,Object value, Map container){ 51 | if(!key.contains(".")){ 52 | container.put(key, value); 53 | return; 54 | } 55 | 56 | String firstKey=StringUtils.substringBefore(key, "."); 57 | Map subContainer=new LinkedHashMap(); 58 | if(container.containsKey(firstKey)){ 59 | Object originalValue = container.get(firstKey); 60 | if(subContainer.getClass().isAssignableFrom(originalValue.getClass())){ 61 | subContainer=(Map) originalValue; 62 | }else{ 63 | subContainer.put("", originalValue); 64 | container.put(firstKey, subContainer); 65 | } 66 | }else{ 67 | container.put(firstKey, subContainer); 68 | } 69 | addNestedKeyValue(StringUtils.substringAfter(key, "."), value, subContainer); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/selectors/PropertySelector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import java.util.Map; 4 | 5 | import org.apache.commons.collections4.map.SingletonMap; 6 | 7 | import cn.jimmyshi.beanquery.DefaultNullValuePropertyValueGetter; 8 | 9 | public class PropertySelector extends KeyValueMapSelector { 10 | private String property; 11 | private String alias; 12 | 13 | String getProperty() { 14 | return property; 15 | } 16 | 17 | /** 18 | * @param property name of the property name used to fetch value from the bean. 19 | * @param alias the key in the result map 20 | */ 21 | public PropertySelector(String property, String alias) { 22 | this.property = property; 23 | this.alias = alias; 24 | } 25 | 26 | public PropertySelector(String property) { 27 | this.property = property; 28 | this.alias = property; 29 | } 30 | 31 | /** 32 | * Use the alias as the key in the result map. 33 | */ 34 | public PropertySelector as(String alias) { 35 | this.alias = alias; 36 | return this; 37 | } 38 | 39 | @Override 40 | protected Map doSelect(Object item) { 41 | Object value = DefaultNullValuePropertyValueGetter.getProperty(item, property); 42 | return new SingletonMap(alias, value); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/cn/jimmyshi/beanquery/selectors/StringSelector.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import java.util.Map; 4 | 5 | import org.apache.commons.lang3.ArrayUtils; 6 | import org.apache.commons.lang3.StringUtils; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | /** 11 | * Selector to support create property selector via String parameter. 12 | */ 13 | public class StringSelector extends KeyValueMapSelector { 14 | private transient Logger logger = LoggerFactory.getLogger(StringSelector.class); 15 | private CompositeSelector compositeSelector = new CompositeSelector(); 16 | 17 | /** 18 | * Create selectors with String. 19 | * 20 | * @param selectString 21 | * String in format "propertyName as alias[,propertyName as alias]" 22 | */ 23 | public StringSelector(String selectString) { 24 | logger.info("Constructing StringSelector with String [{}]", selectString); 25 | if (StringUtils.isBlank(selectString)) { 26 | logger.info("Constructing StringSelector with blank selectString"); 27 | return; 28 | } 29 | String[] propertyStrings = StringUtils.split(selectString, ','); 30 | initCompositeSelector(propertyStrings); 31 | } 32 | 33 | /** 34 | * Create selectors with property string 35 | * 36 | * @param propertyStrings 37 | * Strings in format "propertyName[as alias]" 38 | */ 39 | public StringSelector(String... propertyStrings) { 40 | logger.info("Construct StringSelector with propertyStrings [{}]", (Object) propertyStrings); 41 | initCompositeSelector(propertyStrings); 42 | } 43 | 44 | private void initCompositeSelector(String[] propertyStrings) { 45 | if (ArrayUtils.isEmpty(propertyStrings)) { 46 | logger.debug("Initing StringSelector with empty property String."); 47 | return; 48 | } 49 | 50 | for (String propertyString : propertyStrings) { 51 | if (StringUtils.isNotBlank(propertyString)) { 52 | final PropertySelector propertySelector = createPropertySelector(propertyString); 53 | compositeSelector.addSubSelector(propertySelector); 54 | } 55 | } 56 | logger.info("StringSelector [{}] initilized.", this); 57 | } 58 | 59 | private PropertySelector createPropertySelector(String propertyString) { 60 | String[] propertyTokens = StringUtils.splitByWholeSeparator(propertyString, " as ", 2); 61 | final PropertySelector propertySelector; 62 | String propertySelectorPropertyName = propertyTokens[0].trim(); 63 | if (propertyTokens.length == 2) { 64 | String propertySelectorAlias = propertyTokens[1].trim(); 65 | propertySelector = new PropertySelector(propertySelectorPropertyName, propertySelectorAlias); 66 | } else { 67 | propertySelector = new PropertySelector(propertySelectorPropertyName); 68 | } 69 | return propertySelector; 70 | } 71 | 72 | @Override 73 | protected Map doSelect(Object item) { 74 | return compositeSelector.select(item); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/BeanPropertyMatcherTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import static org.hamcrest.Matchers.startsWith; 4 | import static org.junit.Assert.*; 5 | import static org.mockito.Matchers.any; 6 | import static org.mockito.Mockito.verify; 7 | import static org.mockito.Mockito.when; 8 | 9 | import org.hamcrest.Matcher; 10 | import org.junit.Test; 11 | import org.mockito.Mockito; 12 | 13 | import cn.jimmyshi.beanquery.example.Address; 14 | import cn.jimmyshi.beanquery.example.Book; 15 | 16 | public class BeanPropertyMatcherTest { 17 | 18 | @SuppressWarnings({ "rawtypes", "unchecked" }) 19 | @Test 20 | public void shouldReturnFalseWhenExceptionWhileMatching() { 21 | //given 22 | Matcher delegatedMatcher=Mockito.mock(Matcher.class); 23 | when(delegatedMatcher.matches(any())).thenThrow(NullPointerException.class); 24 | BeanPropertyMatcher beanPropertyMatcher=new BeanPropertyMatcher("propertyName", delegatedMatcher); 25 | //when 26 | boolean result=beanPropertyMatcher.matches(new Book()); 27 | assertFalse(result); 28 | verify(delegatedMatcher).matches(any()); 29 | } 30 | 31 | @Test 32 | public void testMatches(){ 33 | //given 34 | BeanPropertyMatcher postCodeStartedWith000Matcher=new BeanPropertyMatcher("postCode", startsWith("000")); 35 | Address postCodeStartedWith000=new Address(); 36 | postCodeStartedWith000.setPostCode("000111"); 37 | 38 | Address postCodeStartedWith777=new Address(); 39 | postCodeStartedWith777.setPostCode("777666"); 40 | 41 | //when, then 42 | assertTrue(postCodeStartedWith000Matcher.matches(postCodeStartedWith000)); 43 | assertFalse(postCodeStartedWith000Matcher.matches(postCodeStartedWith777)); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/DataLoader.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.List; 5 | 6 | import org.junit.Assert; 7 | 8 | import cn.jimmyshi.beanquery.example.Book; 9 | 10 | import com.fasterxml.jackson.core.type.TypeReference; 11 | import com.fasterxml.jackson.databind.ObjectMapper; 12 | import com.fasterxml.jackson.databind.SerializationFeature; 13 | 14 | public class DataLoader { 15 | private static ObjectMapper mapper = new ObjectMapper(); 16 | static { 17 | mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")); 18 | mapper.enable(SerializationFeature.INDENT_OUTPUT); 19 | } 20 | 21 | public List loadSourceData(String fileName) { 22 | final String fullFileName = "jsonData/source/" + fileName; 23 | try { 24 | return mapper.readValue(ClassLoader.getSystemResource(fullFileName), new TypeReference>() { 25 | }); 26 | } catch (Exception e) { 27 | final String errorMessage = String.format("Exception while loading file [%s] as a list of Book", fullFileName); 28 | throw new IllegalStateException(errorMessage, e); 29 | } 30 | } 31 | 32 | public List loadMainSourcetData() { 33 | return loadSourceData("main.json"); 34 | } 35 | 36 | public void assertDataToJsonEqualsExpectedFileContent(String fileName, Object data) { 37 | final String fullFileName = "jsonData/expected/" + fileName; 38 | try { 39 | Object fileContentAsListOfMap = mapper.readValue(ClassLoader.getSystemResource(fullFileName), List.class); 40 | // transfer to list of map to avoid assert failure caused by class field order 41 | Object dataValueAsListOfMap = mapper.readValue(mapper.writer().writeValueAsString(data), List.class); 42 | Assert.assertEquals(fileContentAsListOfMap, dataValueAsListOfMap); 43 | } catch (Exception ex) { 44 | throw new IllegalStateException(String.format("Exception while comparing file [%s] with object [%s]", fullFileName, 45 | data), ex); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/DefaultNullValuePropertyValueGetterTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | import cn.jimmyshi.beanquery.example.Book; 8 | 9 | public class DefaultNullValuePropertyValueGetterTest { 10 | 11 | @Test 12 | public void testFromNullBean() { 13 | Object result = DefaultNullValuePropertyValueGetter.getProperty(null, "abc"); 14 | assertNull(result); 15 | } 16 | 17 | @Test 18 | public void testNullPropertyName() { 19 | Object result = DefaultNullValuePropertyValueGetter.getProperty(new Book(), null); 20 | assertNull(result); 21 | } 22 | 23 | @Test 24 | public void testEmptyPropertyName() { 25 | Object result = DefaultNullValuePropertyValueGetter.getProperty(new Book(), ""); 26 | assertNull(result); 27 | } 28 | 29 | @Test 30 | public void testBlankPropertyName() { 31 | Object result = DefaultNullValuePropertyValueGetter.getProperty(new Book(), " "); 32 | assertNull(result); 33 | } 34 | 35 | @Test 36 | public void testGetProperty() { 37 | // given 38 | Book book = new Book(); 39 | book.setName("bookName"); 40 | // when 41 | Object result = DefaultNullValuePropertyValueGetter.getProperty(book, "name"); 42 | // then 43 | assertEquals("bookName", result); 44 | } 45 | 46 | @Test 47 | public void testGetNotExistingProperty() { 48 | Object result = DefaultNullValuePropertyValueGetter.getProperty(new Book(), "abc"); 49 | assertNull(result); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/comparators/ComparableObjectComparatorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.comparators; 2 | 3 | import static org.junit.Assert.*; 4 | import static org.mockito.Matchers.any; 5 | import static org.mockito.Mockito.mock; 6 | import static org.mockito.Mockito.only; 7 | import static org.mockito.Mockito.verify; 8 | import static org.mockito.Mockito.when; 9 | 10 | import org.junit.Test; 11 | 12 | public class ComparableObjectComparatorTest { 13 | ComparableObjectComparator comparator=new ComparableObjectComparator(); 14 | 15 | @Test 16 | public void shouldGet0IfCompareing2nulls() { 17 | assertEquals(0,comparator.compare(null, null)); 18 | } 19 | 20 | @Test 21 | public void shouldGet1IfArg1NotNullAndArg2Null(){ 22 | assertEquals(1,comparator.compare(mock(Comparable.class), null)); 23 | } 24 | 25 | @Test 26 | public void shouldGet1IfArgComprableAndArg2NotComparable(){ 27 | assertEquals(1,comparator.compare(mock(Comparable.class), new Object())); 28 | } 29 | 30 | @Test 31 | public void shouldGetNegotiveIfArg1NullAndArg2NotNull(){ 32 | assertEquals(-1,comparator.compare(null, mock(Comparable.class))); 33 | } 34 | 35 | @Test 36 | public void shouldGetNegotiveIfArg1NotComprableAndArg2Comparable(){ 37 | assertEquals(-1,comparator.compare(new Object(), mock(Comparable.class))); 38 | } 39 | 40 | @SuppressWarnings({ "rawtypes", "unchecked" }) 41 | @Test 42 | public void shouldGet0WhenExceptionWhileComparing(){ 43 | //given 44 | Comparable o1=mock(Comparable.class); 45 | when(o1.compareTo(any())).thenThrow(IllegalAccessException.class); 46 | //when 47 | int result=comparator.compare(o1, mock(Comparable.class)); 48 | //then 49 | assertEquals(0,result); 50 | verify(o1,only()).compareTo(any()); 51 | 52 | } 53 | 54 | @Test 55 | public void testCompare(){ 56 | assertEquals(0,comparator.compare("ABC", "ABC")); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/comparators/DefaultSortOrderableComparatorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.comparators; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import java.util.Comparator; 6 | 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | public class DefaultSortOrderableComparatorTest { 11 | DefaultSortOrderableComparator return99Comparator; 12 | @Before 13 | public void setup(){ 14 | return99Comparator = new DefaultSortOrderableComparator() { 15 | 16 | @Override 17 | protected int ascCompare(Object o1, Object o2) { 18 | return 99; 19 | } 20 | }; 21 | } 22 | 23 | 24 | @Test 25 | public void shouldGetAscCompareResultInDefault() { 26 | //when 27 | int result=return99Comparator.compare(null, null); 28 | //then 29 | assertEquals(99,result); 30 | } 31 | 32 | @Test 33 | public void shouldGetDescresultWhenDescCalled(){ 34 | //given 35 | Comparator comparator=return99Comparator.desc(); 36 | //when 37 | int result=comparator.compare(null, null); 38 | //then 39 | assertEquals(-99,result); 40 | } 41 | 42 | @Test 43 | public void shouldGetAscResultWhenAscCalled(){ 44 | //given 45 | Comparator comparator=return99Comparator.asc(); 46 | //when 47 | int result=comparator.compare(null, null); 48 | //then 49 | assertEquals(99,result); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/comparators/PropertyComparatorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.comparators; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.mockito.Matchers.any; 5 | import static org.mockito.Mockito.when; 6 | 7 | import java.util.Comparator; 8 | 9 | import org.junit.Test; 10 | import org.mockito.Mockito; 11 | 12 | import cn.jimmyshi.beanquery.comparators.PropertyComparator; 13 | 14 | @SuppressWarnings({ "unchecked", "rawtypes" }) 15 | public class PropertyComparatorTest { 16 | 17 | public static class TestComparingClass { 18 | private String name = null; 19 | private Object notComparable; 20 | private int intValue = 0; 21 | private Comparable comparable; 22 | 23 | public TestComparingClass(Comparable comparable) { 24 | super(); 25 | this.comparable = comparable; 26 | } 27 | 28 | public Comparable getComparable() { 29 | return comparable; 30 | } 31 | 32 | public TestComparingClass(int intValue) { 33 | super(); 34 | this.intValue = intValue; 35 | } 36 | 37 | public int getIntValue() { 38 | return intValue; 39 | } 40 | 41 | public TestComparingClass(Object notComparable) { 42 | super(); 43 | this.notComparable = notComparable; 44 | } 45 | 46 | public Object getNotComparable() { 47 | return notComparable; 48 | } 49 | 50 | public String getName() { 51 | return name; 52 | } 53 | 54 | public TestComparingClass(String name) { 55 | super(); 56 | this.name = name; 57 | } 58 | 59 | public TestComparingClass() { 60 | } 61 | 62 | } 63 | 64 | @Test 65 | public void shouldGet0WhenBothObjectIsNull() { 66 | assertEquals(0, new PropertyComparator("abc").compare(null, null)); 67 | } 68 | 69 | @Test 70 | public void shouldGet0WhenBothPropertyIsNull() { 71 | assertEquals(0, new PropertyComparator("name").compare(new TestComparingClass(), new TestComparingClass())); 72 | } 73 | 74 | @Test 75 | public void shouldGetNegativeResultWhenOnlyProperty1IsNull() { 76 | assertEquals(-1, 77 | new PropertyComparator("name").compare(new TestComparingClass(), new TestComparingClass("notNull"))); 78 | 79 | } 80 | 81 | @Test 82 | public void shouldGetPostiveResultWhenOnlyProperty2IsNull() { 83 | assertEquals(1, new PropertyComparator("name").compare(new TestComparingClass("notNull"), new TestComparingClass())); 84 | 85 | } 86 | 87 | @Test 88 | public void shouldGetNullPropertyWhenIsNotComparable() { 89 | assertEquals(0, new PropertyComparator("notComparable").compare(new TestComparingClass(new Object()), 90 | new TestComparingClass(new Object()))); 91 | } 92 | 93 | @Test 94 | public void shouldWorkForPrimitiveType() { 95 | Comparator p = new PropertyComparator("intValue"); 96 | assertEquals(0, p.compare(new TestComparingClass(1), new TestComparingClass(1))); 97 | assertEquals(1, p.compare(new TestComparingClass(2), new TestComparingClass(1))); 98 | assertEquals(-1, p.compare(new TestComparingClass(2), new TestComparingClass(3))); 99 | } 100 | 101 | @Test 102 | public void shouldGet0WhenGetExceptionComparing() { 103 | TestComparingClass obj1 = new TestComparingClass(new Comparable() { 104 | 105 | @Override 106 | public int compareTo(Object o) { 107 | throw new IllegalStateException("Exception!!!!!!!!!!!!"); 108 | } 109 | }); 110 | TestComparingClass obj2 = new TestComparingClass(Mockito.mock(Comparable.class)); 111 | 112 | Comparator p = new PropertyComparator("comparable"); 113 | assertEquals(0, p.compare(obj1, obj2)); 114 | 115 | } 116 | 117 | @Test 118 | public void shouldCallCompareToWhenComparable() { 119 | // given 120 | Comparable comparable = Mockito.mock(Comparable.class); 121 | when(comparable.compareTo(any())).thenReturn(1).thenReturn(-1).thenReturn(0); 122 | TestComparingClass obj1 = new TestComparingClass(comparable); 123 | TestComparingClass obj2 = new TestComparingClass(Mockito.mock(Comparable.class)); 124 | Comparator p = new PropertyComparator("comparable"); 125 | 126 | // when & then 127 | assertEquals(1, p.compare(obj1, obj2)); 128 | assertEquals(-1, p.compare(obj1, obj2)); 129 | assertEquals(0, p.compare(obj1, obj2)); 130 | 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/example/Address.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.example; 2 | 3 | import org.apache.commons.lang3.builder.ToStringBuilder; 4 | import org.apache.commons.lang3.builder.ToStringStyle; 5 | 6 | public class Address { 7 | private String address; 8 | private String postCode; 9 | 10 | public String getAddress() { 11 | return address; 12 | } 13 | 14 | public String getPostCode() { 15 | return postCode; 16 | } 17 | 18 | public void setAddress(String address) { 19 | this.address = address; 20 | } 21 | 22 | public void setPostCode(String postCode) { 23 | this.postCode = postCode; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/example/Author.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.example; 2 | 3 | import java.util.Date; 4 | 5 | import org.apache.commons.lang3.builder.ToStringBuilder; 6 | import org.apache.commons.lang3.builder.ToStringStyle; 7 | 8 | public class Author { 9 | private Address address; 10 | private Date birthDate; 11 | 12 | private String name; 13 | 14 | public Address getAddress() { 15 | return address; 16 | } 17 | 18 | public Date getBirthDate() { 19 | return birthDate; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setAddress(Address address) { 27 | this.address = address; 28 | } 29 | 30 | public void setBirthDate(Date birthDate) { 31 | this.birthDate = birthDate; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/example/BeanQueryExample.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.example; 2 | 3 | import static cn.jimmyshi.beanquery.BeanQuery.*; 4 | import static org.junit.Assert.assertThat; 5 | 6 | import java.util.Collections; 7 | import java.util.Comparator; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | import org.junit.Before; 12 | import org.junit.Test; 13 | 14 | import cn.jimmyshi.beanquery.DataLoader; 15 | import cn.jimmyshi.beanquery.selectors.DefaultSelector; 16 | 17 | public class BeanQueryExample { 18 | private DataLoader dataLoader = new DataLoader(); 19 | private List mainData; 20 | 21 | @Before 22 | public void setup() { 23 | mainData = dataLoader.loadMainSourcetData(); 24 | } 25 | 26 | @SuppressWarnings({ "unchecked", "rawtypes" }) 27 | @Test 28 | public void shouldReturnAllFields() { 29 | List> result = select(allOf(Book.class)).from(mainData).execute(); 30 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldReturnAllFields.json", result); 31 | assertThat(result, hasSize(3)); 32 | assertThat(result.get(0).keySet(), hasSize(5)); 33 | assertThat(result.get(1).keySet(), hasSize(5)); 34 | assertThat(result.get(2).keySet(), hasSize(5)); 35 | assertThat((String) result.get(0).get("name"), allOf(notNullValue(), isA(String.class))); 36 | assertThat((Double) result.get(0).get("price"), allOf(notNullValue(), isA(Double.class))); 37 | assertThat((Author) result.get(0).get("mainAuthor"), allOf(notNullValue(), isA(Author.class))); 38 | assertThat((List) result.get(0).get("authorList"), 39 | allOf(notNullValue(), isA((Class>) (Class) List.class))); 40 | assertThat((Map) result.get(0).get("authorMap"), allOf(notNullValue(), isA(Map.class))); 41 | } 42 | 43 | @Test 44 | public void shouldBooksShortedByNameDesc(){ 45 | List sortedBooks = select(Book.class).from(mainData).orderBy("name").desc().execute(); 46 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldBooksShortedByName.json", sortedBooks); 47 | } 48 | 49 | @Test 50 | public void shouldExecuteFromMethodsWorking(){ 51 | List sortedBooks = select(Book.class).orderBy("name").desc().executeFrom(mainData); 52 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldBooksShortedByName.json", sortedBooks); 53 | } 54 | 55 | @Test 56 | public void shouldExcecuteFromBeanMethodWorksWithWhereCondition(){ 57 | Book book=new Book(); 58 | book.setName("abc123"); 59 | Map result=select("name,price").where(value("name",startsWith("abc"))).executeFrom(book); 60 | assertThat((String)result.get("name"),is("abc123")); 61 | } 62 | 63 | @Test 64 | public void shouldExecuteFromBeanMethodWorking(){ 65 | Map executeFromResult=select("name,price").where(notNullValue()).executeFrom(new Object()); 66 | assertThat(executeFromResult.keySet(),hasSize(2)); 67 | assertThat(executeFromResult.keySet(),containsInAnyOrder("name","price")); 68 | } 69 | 70 | @Test 71 | public void shouldFromBeanMethodWorking(){ 72 | List> executeFromResult=select("name,price").where(notNullValue()).from(new Object()).execute(); 73 | assertThat(executeFromResult, hasSize(1)); 74 | assertThat(executeFromResult.get(0).keySet(),containsInAnyOrder("name","price")); 75 | } 76 | 77 | @Test 78 | public void shouldExecuteFromBeanMethodGetNullWhenNotFilteredResult(){ 79 | Map executeFromResult=select("name,price").where(startsWith("abc")).executeFrom(new Object()); 80 | assertThat(executeFromResult, nullValue()); 81 | } 82 | 83 | @Test 84 | public void shouldOnlyBook1InResult(){ 85 | List result=select(Book.class).from(mainData).where(value("name", is("Book1"))).execute(); 86 | assertThat(result,hasSize(1)); 87 | assertThat(result.get(0).getName(),is("Book1")); 88 | } 89 | 90 | @Test 91 | public void shouldReturnFieldsOnly() { 92 | List> result = select("name,price,price as p, mainAuthor").from(mainData).execute(); 93 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldReturnFieldsOnly.json", result); 94 | } 95 | 96 | @Test 97 | public void shouldWorkWithMixedSelectors(){ 98 | List> result = select(allOf(Book.class).except("authorList","authorMap","mainAuthor"),property("price").as("p"),property("mainAuthor")).from(mainData).execute(); 99 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldReturnFieldsOnly.json", result); 100 | } 101 | 102 | @Test 103 | public void shouldReturnEmptyListWhenQueryFromEmptyList(){ 104 | List> result=select("abc").from(Collections.emptyList()).execute(); 105 | assertThat(result, empty()); 106 | } 107 | @Test 108 | public void shouldReturnFieldsOnlyWithAllOfAndExcept() { 109 | List> result = select(allOf(Book.class).except("authorList","authorMap")).from(mainData).execute(); 110 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldReturnFieldsOnlyWithAllOfAndExcept.json", result); 111 | } 112 | 113 | @Test 114 | public void shouldReturnFieldsOnlyWithMultiplePropertyStrings() { 115 | List> result = select("name","price","price as p", "mainAuthor").from(mainData).execute(); 116 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldReturnFieldsOnly.json", result); 117 | } 118 | 119 | @Test 120 | public void shouldReturnFieldsOnlyWithPropertys() { 121 | List> result = select(property("name"), property("price"), property("price").as("p"), 122 | property("mainAuthor")).from(mainData).execute(); 123 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldReturnFieldsOnly.json", result); 124 | } 125 | 126 | @Test 127 | public void shouldNotChangeOrder() { 128 | List> result = select("name,price,mainAuthor") 129 | .from(dataLoader.loadSourceData("forOrders.json")).execute(); 130 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldNotChangeOrder.json", result); 131 | } 132 | 133 | @Test 134 | public void shouldInPriceAscOrder() { 135 | List> result = select("name,price,mainAuthor") 136 | .from(dataLoader.loadSourceData("forOrders.json")).orderBy("price").asc().execute(); 137 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldInPriceAscOrder.json", result); 138 | 139 | } 140 | 141 | @Test 142 | public void shouldIncludeNullValueWhenSortingDesc(){ 143 | List> result=select("name").from(dataLoader.loadSourceData("forOrdersWithNullValue.json")).orderBy("name").desc().execute(); 144 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldIncludeNullValueWhenSortingDesc.json", result); 145 | } 146 | 147 | @Test 148 | public void shouldIncludeNullValueWhenSortingAsc(){ 149 | List> result=select("name").from(dataLoader.loadSourceData("forOrdersWithNullValue.json")).orderBy("name").asc().execute(); 150 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldIncludeNullValueWhenSortingAsc.json", result); 151 | } 152 | 153 | @Test 154 | public void testSortingWithNotExistProperty(){ 155 | List> result = select("name,price,mainAuthor") 156 | .from(dataLoader.loadSourceData("forOrders.json")).orderBy("notExistingProperty").execute(); 157 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldNotChangeOrder.json", result); 158 | } 159 | 160 | @Test 161 | public void shouldInPriceDescOrder() { 162 | List> result = select("name,price,mainAuthor") 163 | .from(dataLoader.loadSourceData("forOrders.json")).orderBy("price").desc().execute(); 164 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldInPriceDescOrder.json", result); 165 | } 166 | 167 | @Test 168 | public void testOrderByBeanComparator(){ 169 | Comparator priceBeanComparator = new Comparator() { 170 | @Override 171 | public int compare(Book o1, Book o2) { 172 | return Double.compare(o1.getPrice(), o2.getPrice()); 173 | } 174 | }; 175 | 176 | List> result = select("name,price,mainAuthor") 177 | .from(dataLoader.loadSourceData("forOrders.json")).orderBy(priceBeanComparator).desc().execute(); 178 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldInPriceDescOrder.json", result); 179 | } 180 | 181 | @Test 182 | public void testOrderByProvidedPropertyComparator(){ 183 | Comparator doubleComparator=new Comparator() { 184 | 185 | @Override 186 | public int compare(Double o1, Double o2) { 187 | return o1.compareTo(o2); 188 | } 189 | }; 190 | 191 | List> result = select("name,price,mainAuthor") 192 | .from(dataLoader.loadSourceData("forOrders.json")).orderBy("price",doubleComparator).desc().execute(); 193 | dataLoader.assertDataToJsonEqualsExpectedFileContent("shouldInPriceDescOrder.json", result); 194 | } 195 | 196 | @Test 197 | public void testChainedOrderByProperties(){ 198 | List> result = select("name,price,mainAuthor") 199 | .from(dataLoader.loadSourceData("forChainedOrder.json")).orderBy(orderByProperty("price"),orderByProperty("name").desc()).execute(); 200 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testChainedOrderByProperties.json", result); 201 | } 202 | 203 | @Test 204 | public void testChainedOrderByPropertiesDesc(){ 205 | List> result = select("name,price,mainAuthor") 206 | .from(dataLoader.loadSourceData("forChainedOrder.json")).orderBy(orderByProperty("price"),orderByProperty("name").desc()).desc().execute(); 207 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testChainedOrderByPropertiesDesc.json", result); 208 | } 209 | 210 | @Test 211 | public void testSelectNullProperties() { 212 | List> result = select("name,price,mainAuthor,authorList").from( 213 | dataLoader.loadSourceData("withoutAuthorMapAndList.json")).execute(); 214 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testSelectNullProperties.json", result); 215 | } 216 | 217 | @Test 218 | public void testNotExistingProperties() { 219 | List> result = select("a,b,mainAuthor").from( 220 | dataLoader.loadSourceData("withoutAuthorMapAndList.json")).execute(); 221 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testNotExistingProperties.json", result); 222 | } 223 | 224 | @Test 225 | public void testSelectNestedProperties() { 226 | List> result = select("name,price,mainAuthor.name as authorName").from(mainData).execute(); 227 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testSelectNestedProperties.json", result); 228 | } 229 | 230 | @Test 231 | public void testSelectListNestedProperties() { 232 | List> result = select("name,price,authorList[0].name as firstAuthorName").from(mainData) 233 | .execute(); 234 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testSelectListNestedProperties.json", result); 235 | } 236 | 237 | @Test 238 | public void testSelectMapNestedProperties() { 239 | List> result = select("name,price,authorMap(Book1-Author-1).address as book1AuthorAddress") 240 | .from(mainData).execute(); 241 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testSelectMapNestedProperties.json", result); 242 | } 243 | 244 | @Test 245 | public void testCustomizedSelector(){ 246 | List bookNames=select(new DefaultSelector() { 247 | @Override 248 | public String select(Object item) { 249 | return ((Book)item).getName(); 250 | } 251 | }).executeFrom(mainData); 252 | 253 | assertThat(bookNames,containsInAnyOrder("Book1","Book2","Book3")); 254 | } 255 | 256 | @Test 257 | public void testUsingMapHamcrestMatchers() { 258 | List> result = select(allOf(Book.class)).from(mainData) 259 | .where(value("authorMap", hasKey("Book1-Author-1"))).execute(); 260 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testUsingMapHamcrestMatchers.json", result); 261 | } 262 | 263 | @Test 264 | public void testUsingCollectionHamcestMatchers() { 265 | Author firstAuthorOfBook1AuthorList = mainData.get(0).getAuthorList().get(0); 266 | List> result = select(allOf(Book.class)).from(mainData) 267 | .where(value("authorList", hasItem(firstAuthorOfBook1AuthorList))).execute(); 268 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testUsingCollectionHamcestMatchers.json", result); 269 | 270 | } 271 | 272 | @SuppressWarnings("unchecked") 273 | @Test 274 | public void testUsingMultipleWhereConditions() { 275 | List> result = select("price,name,mainAuthor.name as mainAuthorName") 276 | .from(dataLoader.loadSourceData("forMultipleWhereConditions.json")) 277 | .where( 278 | //for books name is Book2 or starts with Book1 279 | anyOf(value("name", startsWith("Book1")), value("name", is("Book2"))), 280 | //for books price between (53,65) 281 | allOf(value("price", greaterThan(53d)),value("price",lessThan(65d))) 282 | ).orderBy("name").desc() 283 | .execute(); 284 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testUsingMultipleWhereConditions.json", result); 285 | } 286 | 287 | @SuppressWarnings("unchecked") 288 | @Test 289 | public void testUsingMapMatchersOnNormalProperty() { 290 | List> result = select("price,name,mainAuthor.name as mainAuthorName") 291 | .from(dataLoader.loadSourceData("forMultipleWhereConditions.json")) 292 | .where( 293 | //for books name is Book2 or starts with Book1 294 | anyOf(value("name", startsWith("Book1")), value("name", is("Book2")),value("name",hasEntry("abc", "edf"))), 295 | //for books price between (53,65) 296 | allOf(value("price", greaterThan(53d)),value("price",lessThan(65d))) 297 | ).orderBy("name").desc() 298 | .execute(); 299 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testUsingMultipleWhereConditions.json", result); 300 | } 301 | 302 | @Test 303 | public void testNestedResultFeature() { 304 | List> result = select( 305 | "name,price,authorMap(Book1-Author-1).address.address as author.address, authorMap(Book1-Author-1).address.postCode as author.postCode") 306 | .nested().from(mainData).execute(); 307 | dataLoader.assertDataToJsonEqualsExpectedFileContent("testNestedResultFeature.json", result); 308 | 309 | } 310 | } 311 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/example/Book.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.example; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.apache.commons.lang3.builder.ToStringBuilder; 7 | import org.apache.commons.lang3.builder.ToStringStyle; 8 | 9 | public class Book { 10 | private List authorList; 11 | private Map authorMap; 12 | private Author mainAuthor; 13 | private String name; 14 | private double price; 15 | 16 | public List getAuthorList() { 17 | return authorList; 18 | } 19 | 20 | public Map getAuthorMap() { 21 | return authorMap; 22 | } 23 | 24 | public Author getMainAuthor() { 25 | return mainAuthor; 26 | } 27 | 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | public double getPrice() { 33 | return price; 34 | } 35 | 36 | public void setAuthorList(List authorList) { 37 | this.authorList = authorList; 38 | } 39 | 40 | public void setAuthorMap(Map authorMap) { 41 | this.authorMap = authorMap; 42 | } 43 | 44 | public void setMainAuthor(Author mainAuthor) { 45 | this.mainAuthor = mainAuthor; 46 | } 47 | 48 | public void setName(String name) { 49 | this.name = name; 50 | } 51 | 52 | public void setPrice(double price) { 53 | this.price = price; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/selectors/BeanSelectorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import static org.hamcrest.Matchers.contains; 4 | import static org.hamcrest.Matchers.empty; 5 | import static org.junit.Assert.assertNull; 6 | import static org.junit.Assert.assertSame; 7 | import static org.junit.Assert.assertThat; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Arrays; 11 | import java.util.HashSet; 12 | import java.util.List; 13 | import java.util.Set; 14 | 15 | import org.junit.Test; 16 | 17 | public class BeanSelectorTest { 18 | @Test 19 | public void shouldGetNullWhenSelectNull(){ 20 | //given 21 | BeanSelector stringBeanSelector=new BeanSelector(String.class); 22 | //when 23 | String result=stringBeanSelector.select((Object)null); 24 | //then 25 | assertNull(result); 26 | } 27 | 28 | @Test 29 | public void shouldGetNullWhenIsNotInstance(){ 30 | //given 31 | BeanSelector stringBeanSelector=new BeanSelector(String.class); 32 | //when 33 | String result=stringBeanSelector.select(new Integer(2)); 34 | //then 35 | assertNull(result); 36 | } 37 | 38 | @Test 39 | @SuppressWarnings("rawtypes") 40 | public void shouldGetItselfWhenSelectCastable(){ 41 | //given 42 | BeanSelector setBeanSelector=new BeanSelector(Set.class); 43 | Set item=new HashSet(); 44 | //when 45 | Set result=setBeanSelector.select(item); 46 | //then 47 | assertSame(item, result); 48 | } 49 | 50 | @Test 51 | @SuppressWarnings("rawtypes") 52 | public void shouldGetEmptyListWhenSelectFromNullList(){ 53 | BeanSelector stringBeanSelector=new BeanSelector(String.class); 54 | List result=stringBeanSelector.select((List)null); 55 | assertThat(result, empty()); 56 | } 57 | 58 | @Test 59 | public void shouldGetEmptyListWhenSelectFromEmptyList(){ 60 | BeanSelector stringBeanSelector=new BeanSelector(String.class); 61 | List result=stringBeanSelector.select(new ArrayList()); 62 | assertThat(result, empty()); 63 | } 64 | 65 | @Test 66 | public void shouldGetBeanList(){ 67 | BeanSelector stringBeanSelector=new BeanSelector(String.class); 68 | List result=stringBeanSelector.select(Arrays.asList("ABC","EDF")); 69 | assertThat(result, contains("ABC","EDF")); 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/selectors/ClassSelectorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import static org.hamcrest.Matchers.contains; 4 | import static org.hamcrest.Matchers.containsInAnyOrder; 5 | import static org.hamcrest.Matchers.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | import java.util.Map; 9 | 10 | import org.apache.commons.lang3.ArrayUtils; 11 | import org.junit.Test; 12 | 13 | import cn.jimmyshi.beanquery.example.Address; 14 | import cn.jimmyshi.beanquery.selectors.ClassSelector; 15 | 16 | public class ClassSelectorTest { 17 | String[] defaultPropertyNamesOfAddress = new String[] { "address", "postCode" }; 18 | 19 | @Test 20 | public void testConstructWithNull() { 21 | // given 22 | ClassSelector selector = new ClassSelector(null); 23 | // when 24 | Map result = selector.select(new Address()); 25 | // then 26 | assertThat(result.keySet().size(), is(0)); 27 | } 28 | 29 | @Test 30 | public void testConstructWithClassWithoutReadableProperty() { 31 | // given 32 | ClassSelector selector = new ClassSelector(ClassWithNotReadableProperty.class); 33 | // when 34 | Map result = selector.select(new ClassWithNotReadableProperty()); 35 | // then 36 | assertThat(result.keySet(), contains("name")); 37 | } 38 | 39 | public static class ClassWithNotReadableProperty { 40 | private String name; 41 | private String notReadable; 42 | 43 | public String getName() { 44 | return name; 45 | } 46 | 47 | public void setName(String name) { 48 | this.name = name; 49 | } 50 | 51 | public void setNotReadable(String notReadable) { 52 | this.notReadable = notReadable; 53 | } 54 | } 55 | 56 | @Test 57 | public void testExceptEmptyArray() { 58 | // given 59 | ClassSelector selector = new ClassSelector(Address.class); 60 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 61 | // when 62 | selector.except(); 63 | // then 64 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 65 | } 66 | 67 | @Test 68 | public void testExceptNull() { 69 | // given 70 | ClassSelector selector = new ClassSelector(Address.class); 71 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 72 | // when 73 | selector.except(null); 74 | // then 75 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 76 | } 77 | 78 | @Test 79 | public void testExceptNullAndBlanks() { 80 | // given 81 | ClassSelector selector = new ClassSelector(Address.class); 82 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 83 | // when 84 | selector.except(null, "", " "); 85 | // then 86 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 87 | } 88 | 89 | @Test 90 | public void testExcept() { 91 | // given 92 | ClassSelector selector = new ClassSelector(Address.class); 93 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 94 | // when 95 | selector.except("address", "officeAddress"); 96 | // then 97 | assertThat(selector.select(new Address()).keySet(), 98 | containsInAnyOrder(ArrayUtils.removeElements(defaultPropertyNamesOfAddress, "address","officeAddress"))); 99 | 100 | } 101 | 102 | @Test 103 | public void testAddEmptyArray() { 104 | // given 105 | ClassSelector selector = new ClassSelector(Address.class); 106 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 107 | // when 108 | selector.add(); 109 | // then 110 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 111 | } 112 | 113 | @Test 114 | public void testAddNull() { 115 | // given 116 | ClassSelector selector = new ClassSelector(Address.class); 117 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 118 | // when 119 | selector.add(null); 120 | // then 121 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 122 | } 123 | 124 | @Test 125 | public void testAddNullAndBlanks() { 126 | // given 127 | ClassSelector selector = new ClassSelector(Address.class); 128 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 129 | // when 130 | selector.add(null, "", " "); 131 | // then 132 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 133 | } 134 | 135 | @Test 136 | public void testAdd() { 137 | // given 138 | ClassSelector selector = new ClassSelector(Address.class); 139 | assertThat(selector.select(new Address()).keySet(), containsInAnyOrder(defaultPropertyNamesOfAddress)); 140 | // when 141 | selector.add("address", "officeAddress"); 142 | // then 143 | assertThat(selector.select(new Address()).keySet(), 144 | containsInAnyOrder(ArrayUtils.add(defaultPropertyNamesOfAddress, "officeAddress"))); 145 | 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/selectors/CompositeSelectorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import static org.hamcrest.Matchers.hasKey; 4 | import static org.hamcrest.Matchers.hasSize; 5 | import static org.hamcrest.Matchers.not; 6 | import static org.junit.Assert.assertThat; 7 | 8 | import java.util.Arrays; 9 | import java.util.Collections; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | import org.junit.Test; 14 | 15 | import cn.jimmyshi.beanquery.example.Book; 16 | 17 | public class CompositeSelectorTest extends SelectorTestBase{ 18 | 19 | @Test 20 | public void testConstructWithNull(){ 21 | KeyValueMapSelector subSelector=null; 22 | CompositeSelector selector=new CompositeSelector(subSelector); 23 | assertSelectResultKeySizeIsZero(selector); 24 | } 25 | 26 | @Test 27 | public void testConstructWithNullArray(){ 28 | CompositeSelector selector=new CompositeSelector((KeyValueMapSelector[])null); 29 | assertSelectResultKeySizeIsZero(selector); 30 | } 31 | 32 | @Test 33 | public void testConstructWithSelectorArray(){ 34 | CompositeSelector selector=new CompositeSelector(new PropertySelector("abc"),new PropertySelector("edf")); 35 | assertSelectResultKeys(selector,"abc","edf"); 36 | } 37 | 38 | @Test 39 | public void testDefaultConstructor(){ 40 | CompositeSelector selector=new CompositeSelector(); 41 | assertSelectResultKeySizeIsZero(selector); 42 | } 43 | 44 | 45 | 46 | @Test 47 | public void testConstructWithNullList(){ 48 | List subSelectors=null; 49 | CompositeSelector selector=new CompositeSelector(subSelectors); 50 | assertSelectResultKeySizeIsZero(selector); 51 | } 52 | 53 | @Test 54 | public void testConstructWithEmptyList(){ 55 | List subSelectors=Collections.emptyList(); 56 | CompositeSelector selector=new CompositeSelector(subSelectors); 57 | assertSelectResultKeySizeIsZero(selector); 58 | } 59 | 60 | @Test 61 | public void testConstructWithSelectorList(){ 62 | CompositeSelector selector=new CompositeSelector(Arrays.asList(new PropertySelector("abc"),null,new PropertySelector("edf"))); 63 | assertSelectResultKeys(selector,"abc","edf"); 64 | } 65 | 66 | @Test 67 | public void testAddSubSelector(){ 68 | //given 69 | CompositeSelector selector=new CompositeSelector(new ClassSelector(Book.class)); 70 | Map result = selector.select(new Book()); 71 | int resultKeySizeBeforeAddSubSelector=result.size(); 72 | assertThat(result,not(hasKey("abc"))); 73 | //when 74 | selector.addSubSelector(new PropertySelector("abc")); 75 | //then 76 | result = selector.select(new Book()); 77 | assertThat(result.keySet(),hasSize(resultKeySizeBeforeAddSubSelector+1)); 78 | assertThat(result,hasKey("abc")); 79 | } 80 | 81 | @Test 82 | public void testAddNullSubSelector(){ 83 | //given 84 | CompositeSelector selector=new CompositeSelector(new ClassSelector(Book.class)); 85 | Map result = selector.select(new Book()); 86 | int resultKeySizeBeforeAddSubSelector=result.size(); 87 | 88 | //when 89 | selector.addSubSelector(null); 90 | //then 91 | result = selector.select(new Book()); 92 | assertThat(result.keySet(),hasSize(resultKeySizeBeforeAddSubSelector)); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/selectors/KeyValueMapSelectorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import static org.hamcrest.Matchers.empty; 4 | import static org.junit.Assert.*; 5 | 6 | import java.util.Collections; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | import org.junit.Test; 11 | 12 | public class KeyValueMapSelectorTest { 13 | 14 | @Test 15 | public void testSelectoFromNullList() { 16 | //given 17 | KeyValueMapSelector selector=new KeyValueMapSelector() { 18 | @Override 19 | protected Map doSelect(Object item) { 20 | return Collections.emptyMap(); 21 | } 22 | }; 23 | //when 24 | List> result = selector.select((List)null); 25 | //then 26 | assertThat(result, empty()); 27 | } 28 | 29 | @Test 30 | public void testSelectFromEmptyList(){ 31 | //given 32 | KeyValueMapSelector selector=new KeyValueMapSelector() { 33 | @Override 34 | protected Map doSelect(Object item) { 35 | return Collections.emptyMap(); 36 | } 37 | }; 38 | //when 39 | List> result = selector.select(Collections.emptyList()); 40 | //then 41 | assertThat(result, empty()); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/selectors/NestedKeyValueMapSelectorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import org.junit.Test; 4 | 5 | public class NestedKeyValueMapSelectorTest extends SelectorTestBase{ 6 | 7 | @Test 8 | public void test() { 9 | //given 10 | NestedKeyValueMapSelector selector=new NestedKeyValueMapSelector(new StringSelector("a, b.b1,b.b2, b.c.d.e.f,c,d")); 11 | 12 | //then 13 | assertSelectResultKeys(selector,"a","b","c","d"); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/selectors/PropertySelectorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import org.junit.Test; 6 | 7 | public class PropertySelectorTest extends SelectorTestBase{ 8 | 9 | @Test 10 | public void testUpdateAlias() { 11 | //given 12 | PropertySelector selector=new PropertySelector("propertyName","firstAlias"); 13 | assertSelectResultKeys(selector, "firstAlias"); 14 | //when 15 | selector.as("laterAlias"); 16 | //then 17 | assertSelectResultKeys(selector, "laterAlias"); 18 | } 19 | 20 | @Test 21 | public void testConstructWithoutAlias(){ 22 | PropertySelector selector=new PropertySelector("keyName"); 23 | assertEquals("keyName",selector.getProperty()); 24 | assertSelectResultKeys(selector, "keyName"); 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/selectors/SelectorTestBase.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import static org.hamcrest.Matchers.contains; 4 | import static org.hamcrest.Matchers.empty; 5 | import static org.junit.Assert.assertThat; 6 | 7 | import java.util.Map; 8 | 9 | import cn.jimmyshi.beanquery.example.Book; 10 | 11 | /** 12 | * Provide some methods to verify Selector behavior. 13 | * 14 | */ 15 | public class SelectorTestBase { 16 | void assertSelectResultKeySizeIsZero(KeyValueMapSelector selector) { 17 | Map result = selector.select(new Book()); 18 | assertThat(result.keySet(), empty()); 19 | } 20 | void assertSelectResultKeys(KeyValueMapSelector selector,String... keys){ 21 | Map result = selector.select(new Book()); 22 | assertThat(result.keySet(), contains(keys)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/cn/jimmyshi/beanquery/selectors/StringSelectorTest.java: -------------------------------------------------------------------------------- 1 | package cn.jimmyshi.beanquery.selectors; 2 | 3 | import org.junit.Test; 4 | 5 | public class StringSelectorTest extends SelectorTestBase{ 6 | 7 | @Test 8 | public void testStringConstructor(){ 9 | StringSelector selector=new StringSelector("abc"); 10 | assertSelectResultKeys(selector, "abc"); 11 | } 12 | 13 | @Test 14 | public void testStringConstructorWithAlias(){ 15 | StringSelector selector=new StringSelector("abc as edf"); 16 | assertSelectResultKeys(selector, "edf"); 17 | } 18 | 19 | @Test 20 | public void testStringContainsAsButItisNotAlias(){ 21 | StringSelector selector=new StringSelector("task,abc"); 22 | assertSelectResultKeys(selector, "task","abc"); 23 | } 24 | 25 | @Test 26 | public void testStringContaningMultipleAs(){ 27 | StringSelector selector=new StringSelector("task as it as m, abc"); 28 | assertSelectResultKeys(selector, "it as m", "abc"); 29 | } 30 | 31 | @Test 32 | public void testStringConstructorWithMultipleProperties(){ 33 | StringSelector selector=new StringSelector("abc,, abc as edf,"); 34 | assertSelectResultKeys(selector, "abc","edf"); 35 | } 36 | 37 | @Test 38 | public void testStringConstructorWithEmptyString(){ 39 | StringSelector selector=new StringSelector(" "); 40 | assertSelectResultKeySizeIsZero(selector); 41 | } 42 | 43 | @Test 44 | public void testStringConstructorWithNull(){ 45 | StringSelector selector=new StringSelector((String)null); 46 | assertSelectResultKeySizeIsZero(selector); 47 | } 48 | 49 | @Test 50 | public void testStringArrayConstructor(){ 51 | StringSelector selector=new StringSelector("abc",null," ", "", " abc as edf"); 52 | assertSelectResultKeys(selector, "abc","edf"); 53 | } 54 | 55 | @Test 56 | public void testStringArraysConstructorWithNull(){ 57 | StringSelector selector=new StringSelector((String[])null); 58 | assertSelectResultKeySizeIsZero(selector); 59 | 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldBooksShortedByName.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":6.66, 4 | "name":"Book3", 5 | "mainAuthor":{ 6 | "name":"Book3-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518005" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | }, 13 | "authorList":[ 14 | { 15 | "name":"Book3-Author-1", 16 | "address":{ 17 | "address":"Shenzhen Guangdong China", 18 | "postCode":"518006" 19 | }, 20 | "birthDate":"1982-01-30T14:52:39" 21 | }, 22 | { 23 | "name":"Book3-Author-2", 24 | "address":{ 25 | "address":"Shenzhen Guangdong China", 26 | "postCode":"518007" 27 | }, 28 | "birthDate":"1983-01-29T14:52:39" 29 | } 30 | ], 31 | "authorMap":{ 32 | "Book3-Author-2":{ 33 | "name":"Book3-Author-2", 34 | "address":{ 35 | "address":"Shenzhen Guangdong China", 36 | "postCode":"518008" 37 | }, 38 | "birthDate":"1983-01-29T14:52:39" 39 | }, 40 | "Book3-Author-1":{ 41 | "name":"Book3-Author-1", 42 | "address":{ 43 | "address":"Shenzhen Guangdong China", 44 | "postCode":"518010" 45 | }, 46 | "birthDate":"1982-01-30T14:52:39" 47 | } 48 | } 49 | }, 50 | { 51 | "price":6.66, 52 | "name":"Book2", 53 | "mainAuthor":{ 54 | "name":"Book2-MainAuthor", 55 | "address":{ 56 | "address":"Shenzhen Guangdong China", 57 | "postCode":"518005" 58 | }, 59 | "birthDate":"1982-01-30T14:52:39" 60 | }, 61 | "authorList":[ 62 | { 63 | "name":"Book2-Author-1", 64 | "address":{ 65 | "address":"Shenzhen Guangdong China", 66 | "postCode":"518006" 67 | }, 68 | "birthDate":"1982-01-30T14:52:39" 69 | }, 70 | { 71 | "name":"Book2-Author-2", 72 | "address":{ 73 | "address":"Shenzhen Guangdong China", 74 | "postCode":"518007" 75 | }, 76 | "birthDate":"1983-01-29T14:52:39" 77 | } 78 | ], 79 | "authorMap":{ 80 | "Book2-Author-2":{ 81 | "name":"Book2-Author-2", 82 | "address":{ 83 | "address":"Shenzhen Guangdong China", 84 | "postCode":"518008" 85 | }, 86 | "birthDate":"1983-01-29T14:52:39" 87 | }, 88 | "Book2-Author-1":{ 89 | "name":"Book2-Author-1", 90 | "address":{ 91 | "address":"Shenzhen Guangdong China", 92 | "postCode":"518010" 93 | }, 94 | "birthDate":"1982-01-30T14:52:39" 95 | } 96 | } 97 | }, 98 | { 99 | "price":50.55, 100 | "name":"Book1", 101 | "mainAuthor":{ 102 | "name":"Book1-MainAuthor", 103 | "address":{ 104 | "address":"Shenzhen Guangdong China", 105 | "postCode":"518000" 106 | }, 107 | "birthDate":"1982-01-30T14:52:39" 108 | }, 109 | "authorList":[ 110 | { 111 | "name":"Book1-Author-1", 112 | "address":{ 113 | "address":"Shenzhen Guangdong China", 114 | "postCode":"518001" 115 | }, 116 | "birthDate":"1982-01-30T14:52:39" 117 | }, 118 | { 119 | "name":"Book1-Author-2", 120 | "address":{ 121 | "address":"Shenzhen Guangdong China", 122 | "postCode":"518002" 123 | }, 124 | "birthDate":"1983-01-29T14:52:39" 125 | } 126 | ], 127 | "authorMap":{ 128 | "Book1-Author-2":{ 129 | "name":"Book1-Author-2", 130 | "address":{ 131 | "address":"Shenzhen Guangdong China", 132 | "postCode":"518003" 133 | }, 134 | "birthDate":"1983-01-29T14:52:39" 135 | }, 136 | "Book1-Author-1":{ 137 | "name":"Book1-Author-1", 138 | "address":{ 139 | "address":"Shenzhen Guangdong China", 140 | "postCode":"518004" 141 | }, 142 | "birthDate":"1982-01-30T14:52:39" 143 | } 144 | } 145 | } 146 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldInPriceAscOrder.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":66.66, 16 | "name":"Book2", 17 | "mainAuthor":{ 18 | "name":"Book2-MainAuthor", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518005" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | }, 26 | { 27 | "price":77.77, 28 | "name":"Book3", 29 | "mainAuthor":{ 30 | "name":"Book3-MainAuthor", 31 | "address":{ 32 | "address":"Shenzhen Guangdong China", 33 | "postCode":"518005" 34 | }, 35 | "birthDate":"1982-01-30T14:52:39" 36 | } 37 | } 38 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldInPriceDescOrder.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":77.77, 4 | "name":"Book3", 5 | "mainAuthor":{ 6 | "name":"Book3-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518005" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | 14 | } 15 | , 16 | { 17 | "price":66.66, 18 | "name":"Book2", 19 | "mainAuthor":{ 20 | "name":"Book2-MainAuthor", 21 | "address":{ 22 | "address":"Shenzhen Guangdong China", 23 | "postCode":"518005" 24 | }, 25 | "birthDate":"1982-01-30T14:52:39" 26 | } 27 | 28 | }, 29 | { 30 | "price":50.55, 31 | "name":"Book1", 32 | "mainAuthor":{ 33 | "name":"Book1-MainAuthor", 34 | "address":{ 35 | "address":"Shenzhen Guangdong China", 36 | "postCode":"518000" 37 | }, 38 | "birthDate":"1982-01-30T14:52:39" 39 | } 40 | 41 | } 42 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldIncludeNullValueWhenSortingAsc.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":null 4 | }, 5 | { 6 | "name":"Book1" 7 | }, 8 | { 9 | "name":"Book2" 10 | } 11 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldIncludeNullValueWhenSortingDesc.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":"Book2" 4 | }, 5 | { 6 | "name":"Book1" 7 | }, 8 | { 9 | "name":null 10 | } 11 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldNotChangeOrder.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":77.77, 16 | "name":"Book3", 17 | "mainAuthor":{ 18 | "name":"Book3-MainAuthor", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518005" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | } 26 | , 27 | { 28 | "price":66.66, 29 | "name":"Book2", 30 | "mainAuthor":{ 31 | "name":"Book2-MainAuthor", 32 | "address":{ 33 | "address":"Shenzhen Guangdong China", 34 | "postCode":"518005" 35 | }, 36 | "birthDate":"1982-01-30T14:52:39" 37 | } 38 | } 39 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldReturnAllFields.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | }, 13 | "authorList":[ 14 | { 15 | "name":"Book1-Author-1", 16 | "address":{ 17 | "address":"Shenzhen Guangdong China", 18 | "postCode":"518001" 19 | }, 20 | "birthDate":"1982-01-30T14:52:39" 21 | }, 22 | { 23 | "name":"Book1-Author-2", 24 | "address":{ 25 | "address":"Shenzhen Guangdong China", 26 | "postCode":"518002" 27 | }, 28 | "birthDate":"1983-01-29T14:52:39" 29 | } 30 | 31 | ], 32 | "authorMap":{ 33 | "Book1-Author-2":{ 34 | "name":"Book1-Author-2", 35 | "address":{ 36 | "address":"Shenzhen Guangdong China", 37 | "postCode":"518003" 38 | }, 39 | "birthDate":"1983-01-29T14:52:39" 40 | }, 41 | "Book1-Author-1":{ 42 | "name":"Book1-Author-1", 43 | "address":{ 44 | "address":"Shenzhen Guangdong China", 45 | "postCode":"518004" 46 | }, 47 | "birthDate":"1982-01-30T14:52:39" 48 | } 49 | 50 | } 51 | 52 | }, 53 | { 54 | "name":"Book2", 55 | "price":6.66, 56 | "mainAuthor":{ 57 | "name":"Book2-MainAuthor", 58 | "address":{ 59 | "address":"Shenzhen Guangdong China", 60 | "postCode":"518005" 61 | }, 62 | "birthDate":"1982-01-30T14:52:39" 63 | }, 64 | "authorList":[ 65 | { 66 | "name":"Book2-Author-1", 67 | "address":{ 68 | "address":"Shenzhen Guangdong China", 69 | "postCode":"518006" 70 | }, 71 | "birthDate":"1982-01-30T14:52:39" 72 | }, 73 | { 74 | "name":"Book2-Author-2", 75 | "address":{ 76 | "address":"Shenzhen Guangdong China", 77 | "postCode":"518007" 78 | }, 79 | "birthDate":"1983-01-29T14:52:39" 80 | } 81 | 82 | ], 83 | "authorMap":{ 84 | "Book2-Author-2":{ 85 | "name":"Book2-Author-2", 86 | "address":{ 87 | "address":"Shenzhen Guangdong China", 88 | "postCode":"518008" 89 | }, 90 | "birthDate":"1983-01-29T14:52:39" 91 | }, 92 | "Book2-Author-1":{ 93 | "name":"Book2-Author-1", 94 | "address":{ 95 | "address":"Shenzhen Guangdong China", 96 | "postCode":"518010" 97 | }, 98 | "birthDate":"1982-01-30T14:52:39" 99 | } 100 | 101 | } 102 | 103 | }, 104 | { 105 | "name":"Book3", 106 | "price":6.66, 107 | "mainAuthor":{ 108 | "name":"Book3-MainAuthor", 109 | "address":{ 110 | "address":"Shenzhen Guangdong China", 111 | "postCode":"518005" 112 | }, 113 | "birthDate":"1982-01-30T14:52:39" 114 | }, 115 | "authorList":[ 116 | { 117 | "name":"Book3-Author-1", 118 | "address":{ 119 | "address":"Shenzhen Guangdong China", 120 | "postCode":"518006" 121 | }, 122 | "birthDate":"1982-01-30T14:52:39" 123 | }, 124 | { 125 | "name":"Book3-Author-2", 126 | "address":{ 127 | "address":"Shenzhen Guangdong China", 128 | "postCode":"518007" 129 | }, 130 | "birthDate":"1983-01-29T14:52:39" 131 | } 132 | 133 | ], 134 | "authorMap":{ 135 | "Book3-Author-1":{ 136 | "name":"Book3-Author-1", 137 | "address":{ 138 | "address":"Shenzhen Guangdong China", 139 | "postCode":"518010" 140 | }, 141 | "birthDate":"1982-01-30T14:52:39" 142 | }, 143 | "Book3-Author-2":{ 144 | "name":"Book3-Author-2", 145 | "address":{ 146 | "address":"Shenzhen Guangdong China", 147 | "postCode":"518008" 148 | }, 149 | "birthDate":"1983-01-29T14:52:39" 150 | } 151 | 152 | } 153 | 154 | } 155 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldReturnFieldsOnly.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":"Book1", 4 | "price":50.55, 5 | "p":50.55, 6 | "mainAuthor":{ 7 | "name":"Book1-MainAuthor", 8 | "address":{ 9 | "address":"Shenzhen Guangdong China", 10 | "postCode":"518000" 11 | }, 12 | "birthDate":"1982-01-30T14:52:39" 13 | } 14 | 15 | }, 16 | { 17 | "name":"Book2", 18 | "price":6.66, 19 | "p":6.66, 20 | "mainAuthor":{ 21 | "name":"Book2-MainAuthor", 22 | "address":{ 23 | "address":"Shenzhen Guangdong China", 24 | "postCode":"518005" 25 | }, 26 | "birthDate":"1982-01-30T14:52:39" 27 | } 28 | 29 | }, 30 | { 31 | "name":"Book3", 32 | "price":6.66, 33 | "p":6.66, 34 | "mainAuthor":{ 35 | "name":"Book3-MainAuthor", 36 | "address":{ 37 | "address":"Shenzhen Guangdong China", 38 | "postCode":"518005" 39 | }, 40 | "birthDate":"1982-01-30T14:52:39" 41 | } 42 | 43 | } 44 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/shouldReturnFieldsOnlyWithAllOfAndExcept.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":"Book1", 4 | "price":50.55, 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | 14 | }, 15 | { 16 | "name":"Book2", 17 | "price":6.66, 18 | "mainAuthor":{ 19 | "name":"Book2-MainAuthor", 20 | "address":{ 21 | "address":"Shenzhen Guangdong China", 22 | "postCode":"518005" 23 | }, 24 | "birthDate":"1982-01-30T14:52:39" 25 | } 26 | 27 | }, 28 | { 29 | "name":"Book3", 30 | "price":6.66, 31 | "mainAuthor":{ 32 | "name":"Book3-MainAuthor", 33 | "address":{ 34 | "address":"Shenzhen Guangdong China", 35 | "postCode":"518005" 36 | }, 37 | "birthDate":"1982-01-30T14:52:39" 38 | } 39 | 40 | } 41 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testChainedOrderByProperties.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":55.55, 4 | "name":"Book2", 5 | "mainAuthor":{ 6 | "name":"Author2", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518005" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":55.55, 16 | "name":"Book1", 17 | "mainAuthor":{ 18 | "name":"Author1", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518000" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | }, 26 | { 27 | "price":66.66, 28 | "name":"Book3", 29 | "mainAuthor":{ 30 | "name":"Author1", 31 | "address":{ 32 | "address":"Shenzhen Guangdong China", 33 | "postCode":"518005" 34 | }, 35 | "birthDate":"1982-01-30T14:52:39" 36 | } 37 | } 38 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testChainedOrderByPropertiesDesc.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":66.66, 4 | "name":"Book3", 5 | "mainAuthor":{ 6 | "name":"Author1", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518005" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":55.55, 16 | "name":"Book1", 17 | "mainAuthor":{ 18 | "name":"Author1", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518000" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | }, 26 | { 27 | "price":55.55, 28 | "name":"Book2", 29 | "mainAuthor":{ 30 | "name":"Author2", 31 | "address":{ 32 | "address":"Shenzhen Guangdong China", 33 | "postCode":"518005" 34 | }, 35 | "birthDate":"1982-01-30T14:52:39" 36 | } 37 | } 38 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testNestedResultFeature.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "author":{ 6 | "address":"Shenzhen Guangdong China", 7 | "postCode":"518004" 8 | } 9 | 10 | }, 11 | { 12 | "name":"Book2", 13 | "price":6.66, 14 | "author":{ 15 | "address":null, 16 | "postCode":null 17 | } 18 | }, 19 | { 20 | "name":"Book3", 21 | "price":6.66, 22 | "author":{ 23 | "address":null, 24 | "postCode":null 25 | } 26 | } 27 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testNotExistingProperties.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "a":null, 4 | "b":null, 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "a":null, 16 | "b":null, 17 | "mainAuthor":{ 18 | "name":"Book3-MainAuthor", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518005" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | } 26 | , 27 | { 28 | "a":null, 29 | "b":null, 30 | "mainAuthor":{ 31 | "name":"Book2-MainAuthor", 32 | "address":{ 33 | "address":"Shenzhen Guangdong China", 34 | "postCode":"518005" 35 | }, 36 | "birthDate":"1982-01-30T14:52:39" 37 | } 38 | } 39 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testSelectListNestedProperties.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "firstAuthorName":"Book1-Author-1" 6 | }, 7 | { 8 | "name":"Book2", 9 | "price":6.66, 10 | "firstAuthorName":"Book2-Author-1" 11 | }, 12 | { 13 | "name":"Book3", 14 | "price":6.66, 15 | "firstAuthorName":"Book3-Author-1" 16 | } 17 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testSelectMapNestedProperties.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "book1AuthorAddress":{ 6 | "address":"Shenzhen Guangdong China", 7 | "postCode":"518004" 8 | } 9 | 10 | }, 11 | { 12 | "name":"Book2", 13 | "price":6.66, 14 | "book1AuthorAddress":null 15 | }, 16 | { 17 | "name":"Book3", 18 | "price":6.66, 19 | "book1AuthorAddress":null 20 | } 21 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testSelectNestedProperties.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "authorName":"Book1-MainAuthor" 6 | }, 7 | { 8 | "name":"Book2", 9 | "price":6.66, 10 | "authorName":"Book2-MainAuthor" 11 | }, 12 | { 13 | "name":"Book3", 14 | "price":6.66, 15 | "authorName":"Book3-MainAuthor" 16 | } 17 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testSelectNullProperties.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "authorList":null, 5 | "name":"Book1", 6 | "mainAuthor":{ 7 | "name":"Book1-MainAuthor", 8 | "address":{ 9 | "address":"Shenzhen Guangdong China", 10 | "postCode":"518000" 11 | }, 12 | "birthDate":"1982-01-30T14:52:39" 13 | } 14 | }, 15 | { 16 | "price":77.77, 17 | "authorList":null, 18 | "name":"Book3", 19 | "mainAuthor":{ 20 | "name":"Book3-MainAuthor", 21 | "address":{ 22 | "address":"Shenzhen Guangdong China", 23 | "postCode":"518005" 24 | }, 25 | "birthDate":"1982-01-30T14:52:39" 26 | } 27 | } 28 | , 29 | { 30 | "price":66.66, 31 | "authorList":null, 32 | "name":"Book2", 33 | "mainAuthor":{ 34 | "name":"Book2-MainAuthor", 35 | "address":{ 36 | "address":"Shenzhen Guangdong China", 37 | "postCode":"518005" 38 | }, 39 | "birthDate":"1982-01-30T14:52:39" 40 | } 41 | } 42 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testUsingCollectionHamcestMatchers.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | }, 13 | "authorList":[ 14 | { 15 | "name":"Book1-Author-1", 16 | "address":{ 17 | "address":"Shenzhen Guangdong China", 18 | "postCode":"518001" 19 | }, 20 | "birthDate":"1982-01-30T14:52:39" 21 | }, 22 | { 23 | "name":"Book1-Author-2", 24 | "address":{ 25 | "address":"Shenzhen Guangdong China", 26 | "postCode":"518002" 27 | }, 28 | "birthDate":"1983-01-29T14:52:39" 29 | } 30 | 31 | ], 32 | "authorMap":{ 33 | "Book1-Author-2":{ 34 | "name":"Book1-Author-2", 35 | "address":{ 36 | "address":"Shenzhen Guangdong China", 37 | "postCode":"518003" 38 | }, 39 | "birthDate":"1983-01-29T14:52:39" 40 | }, 41 | "Book1-Author-1":{ 42 | "name":"Book1-Author-1", 43 | "address":{ 44 | "address":"Shenzhen Guangdong China", 45 | "postCode":"518004" 46 | }, 47 | "birthDate":"1982-01-30T14:52:39" 48 | } 49 | 50 | } 51 | 52 | } 53 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testUsingMapHamcrestMatchers.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | }, 13 | "authorList":[ 14 | { 15 | "name":"Book1-Author-1", 16 | "address":{ 17 | "address":"Shenzhen Guangdong China", 18 | "postCode":"518001" 19 | }, 20 | "birthDate":"1982-01-30T14:52:39" 21 | }, 22 | { 23 | "name":"Book1-Author-2", 24 | "address":{ 25 | "address":"Shenzhen Guangdong China", 26 | "postCode":"518002" 27 | }, 28 | "birthDate":"1983-01-29T14:52:39" 29 | } 30 | 31 | ], 32 | "authorMap":{ 33 | "Book1-Author-2":{ 34 | "name":"Book1-Author-2", 35 | "address":{ 36 | "address":"Shenzhen Guangdong China", 37 | "postCode":"518003" 38 | }, 39 | "birthDate":"1983-01-29T14:52:39" 40 | }, 41 | "Book1-Author-1":{ 42 | "name":"Book1-Author-1", 43 | "address":{ 44 | "address":"Shenzhen Guangdong China", 45 | "postCode":"518004" 46 | }, 47 | "birthDate":"1982-01-30T14:52:39" 48 | } 49 | 50 | } 51 | 52 | } 53 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/expected/testUsingMultipleWhereConditions.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":60.0, 4 | "name":"Book14", 5 | "mainAuthorName":"Book14-MainAuthor" 6 | }, 7 | { 8 | "price":53.55, 9 | "name":"Book13", 10 | "mainAuthorName":"Book13-MainAuthor" 11 | }, 12 | { 13 | "price":55.55, 14 | "name":"Book1", 15 | "mainAuthorName":"Book1-MainAuthor" 16 | } 17 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/source/forChainedOrder.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":55.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Author1", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":55.55, 16 | "name":"Book2", 17 | "mainAuthor":{ 18 | "name":"Author2", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518005" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | } 26 | , 27 | { 28 | "price":66.66, 29 | "name":"Book3", 30 | "mainAuthor":{ 31 | "name":"Author1", 32 | "address":{ 33 | "address":"Shenzhen Guangdong China", 34 | "postCode":"518005" 35 | }, 36 | "birthDate":"1982-01-30T14:52:39" 37 | } 38 | } 39 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/source/forMultipleWhereConditions.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":55.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":52.55, 16 | "name":"Book12", 17 | "mainAuthor":{ 18 | "name":"Book1-MainAuthor", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518000" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | }, 26 | { 27 | "price":53.55, 28 | "name":"Book13", 29 | "mainAuthor":{ 30 | "name":"Book13-MainAuthor", 31 | "address":{ 32 | "address":"Shenzhen Guangdong China", 33 | "postCode":"518000" 34 | }, 35 | "birthDate":"1982-01-30T14:52:39" 36 | } 37 | }, 38 | { 39 | "price":60.0, 40 | "name":"Book14", 41 | "mainAuthor":{ 42 | "name":"Book14-MainAuthor", 43 | "address":{ 44 | "address":"Shenzhen Guangdong China", 45 | "postCode":"518000" 46 | }, 47 | "birthDate":"1982-01-30T14:52:39" 48 | } 49 | }, 50 | { 51 | "price":50.55, 52 | "name":"Book15", 53 | "mainAuthor":{ 54 | "name":"Book1-MainAuthor", 55 | "address":{ 56 | "address":"Shenzhen Guangdong China", 57 | "postCode":"518000" 58 | }, 59 | "birthDate":"1982-01-30T14:52:39" 60 | } 61 | }, 62 | { 63 | "price":77.77, 64 | "name":"Book3", 65 | "mainAuthor":{ 66 | "name":"Book3-MainAuthor", 67 | "address":{ 68 | "address":"Shenzhen Guangdong China", 69 | "postCode":"518005" 70 | }, 71 | "birthDate":"1982-01-30T14:52:39" 72 | } 73 | } 74 | , 75 | { 76 | "price":66.66, 77 | "name":"Book2", 78 | "mainAuthor":{ 79 | "name":"Book2-MainAuthor", 80 | "address":{ 81 | "address":"Shenzhen Guangdong China", 82 | "postCode":"518005" 83 | }, 84 | "birthDate":"1982-01-30T14:52:39" 85 | } 86 | } 87 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/source/forOrders.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":77.77, 16 | "name":"Book3", 17 | "mainAuthor":{ 18 | "name":"Book3-MainAuthor", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518005" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | } 26 | , 27 | { 28 | "price":66.66, 29 | "name":"Book2", 30 | "mainAuthor":{ 31 | "name":"Book2-MainAuthor", 32 | "address":{ 33 | "address":"Shenzhen Guangdong China", 34 | "postCode":"518005" 35 | }, 36 | "birthDate":"1982-01-30T14:52:39" 37 | } 38 | } 39 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/source/forOrdersWithNullValue.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":77.77, 16 | "mainAuthor":{ 17 | "name":"Book3-MainAuthor", 18 | "address":{ 19 | "address":"Shenzhen Guangdong China", 20 | "postCode":"518005" 21 | }, 22 | "birthDate":"1982-01-30T14:52:39" 23 | } 24 | } 25 | , 26 | { 27 | "price":66.66, 28 | "name":"Book2", 29 | "mainAuthor":{ 30 | "name":"Book2-MainAuthor", 31 | "address":{ 32 | "address":"Shenzhen Guangdong China", 33 | "postCode":"518005" 34 | }, 35 | "birthDate":"1982-01-30T14:52:39" 36 | } 37 | } 38 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/source/main.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | }, 13 | "authorList":[ 14 | { 15 | "name":"Book1-Author-1", 16 | "address":{ 17 | "address":"Shenzhen Guangdong China", 18 | "postCode":"518001" 19 | }, 20 | "birthDate":"1982-01-30T14:52:39" 21 | }, 22 | { 23 | "name":"Book1-Author-2", 24 | "address":{ 25 | "address":"Shenzhen Guangdong China", 26 | "postCode":"518002" 27 | }, 28 | "birthDate":"1983-01-29T14:52:39" 29 | } 30 | 31 | ], 32 | "authorMap":{ 33 | "Book1-Author-2":{ 34 | "name":"Book1-Author-2", 35 | "address":{ 36 | "address":"Shenzhen Guangdong China", 37 | "postCode":"518003" 38 | }, 39 | "birthDate":"1983-01-29T14:52:39" 40 | }, 41 | "Book1-Author-1":{ 42 | "name":"Book1-Author-1", 43 | "address":{ 44 | "address":"Shenzhen Guangdong China", 45 | "postCode":"518004" 46 | }, 47 | "birthDate":"1982-01-30T14:52:39" 48 | } 49 | 50 | } 51 | 52 | }, 53 | { 54 | "price":6.66, 55 | "name":"Book2", 56 | "mainAuthor":{ 57 | "name":"Book2-MainAuthor", 58 | "address":{ 59 | "address":"Shenzhen Guangdong China", 60 | "postCode":"518005" 61 | }, 62 | "birthDate":"1982-01-30T14:52:39" 63 | }, 64 | "authorList":[ 65 | { 66 | "name":"Book2-Author-1", 67 | "address":{ 68 | "address":"Shenzhen Guangdong China", 69 | "postCode":"518006" 70 | }, 71 | "birthDate":"1982-01-30T14:52:39" 72 | }, 73 | { 74 | "name":"Book2-Author-2", 75 | "address":{ 76 | "address":"Shenzhen Guangdong China", 77 | "postCode":"518007" 78 | }, 79 | "birthDate":"1983-01-29T14:52:39" 80 | } 81 | 82 | ], 83 | "authorMap":{ 84 | "Book2-Author-2":{ 85 | "name":"Book2-Author-2", 86 | "address":{ 87 | "address":"Shenzhen Guangdong China", 88 | "postCode":"518008" 89 | }, 90 | "birthDate":"1983-01-29T14:52:39" 91 | }, 92 | "Book2-Author-1":{ 93 | "name":"Book2-Author-1", 94 | "address":{ 95 | "address":"Shenzhen Guangdong China", 96 | "postCode":"518010" 97 | }, 98 | "birthDate":"1982-01-30T14:52:39" 99 | } 100 | 101 | } 102 | 103 | }, 104 | { 105 | "price":6.66, 106 | "name":"Book3", 107 | "mainAuthor":{ 108 | "name":"Book3-MainAuthor", 109 | "address":{ 110 | "address":"Shenzhen Guangdong China", 111 | "postCode":"518005" 112 | }, 113 | "birthDate":"1982-01-30T14:52:39" 114 | }, 115 | "authorList":[ 116 | { 117 | "name":"Book3-Author-1", 118 | "address":{ 119 | "address":"Shenzhen Guangdong China", 120 | "postCode":"518006" 121 | }, 122 | "birthDate":"1982-01-30T14:52:39" 123 | }, 124 | { 125 | "name":"Book3-Author-2", 126 | "address":{ 127 | "address":"Shenzhen Guangdong China", 128 | "postCode":"518007" 129 | }, 130 | "birthDate":"1983-01-29T14:52:39" 131 | } 132 | 133 | ], 134 | "authorMap":{ 135 | "Book3-Author-2":{ 136 | "name":"Book3-Author-2", 137 | "address":{ 138 | "address":"Shenzhen Guangdong China", 139 | "postCode":"518008" 140 | }, 141 | "birthDate":"1983-01-29T14:52:39" 142 | }, 143 | "Book3-Author-1":{ 144 | "name":"Book3-Author-1", 145 | "address":{ 146 | "address":"Shenzhen Guangdong China", 147 | "postCode":"518010" 148 | }, 149 | "birthDate":"1982-01-30T14:52:39" 150 | } 151 | 152 | } 153 | 154 | } 155 | ] -------------------------------------------------------------------------------- /src/test/resources/jsonData/source/withoutAuthorMapAndList.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "price":50.55, 4 | "name":"Book1", 5 | "mainAuthor":{ 6 | "name":"Book1-MainAuthor", 7 | "address":{ 8 | "address":"Shenzhen Guangdong China", 9 | "postCode":"518000" 10 | }, 11 | "birthDate":"1982-01-30T14:52:39" 12 | } 13 | }, 14 | { 15 | "price":77.77, 16 | "name":"Book3", 17 | "mainAuthor":{ 18 | "name":"Book3-MainAuthor", 19 | "address":{ 20 | "address":"Shenzhen Guangdong China", 21 | "postCode":"518005" 22 | }, 23 | "birthDate":"1982-01-30T14:52:39" 24 | } 25 | } 26 | , 27 | { 28 | "price":66.66, 29 | "name":"Book2", 30 | "mainAuthor":{ 31 | "name":"Book2-MainAuthor", 32 | "address":{ 33 | "address":"Shenzhen Guangdong China", 34 | "postCode":"518005" 35 | }, 36 | "birthDate":"1982-01-30T14:52:39" 37 | } 38 | } 39 | ] --------------------------------------------------------------------------------