├── .gitignore ├── LICENSE ├── README.md ├── VERSIONS.md ├── build.gradle.kts ├── buildSrc ├── build.gradle.kts └── src │ └── main │ └── kotlin │ └── io │ └── insource │ └── build │ └── Publishing.kt ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main └── kotlin │ └── io │ └── insource │ └── framework │ └── rule │ └── Rule.kt └── test └── kotlin └── io └── insource └── framework └── rule ├── RuleTest.kt └── RulesEngineTest.kt /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # in-rules-engine 2 | Kotlin rules engine DSL for maintaining rules and business logic in code. 3 | 4 | ## Basic Syntax 5 | 6 | The rule DSL syntax uses Kotlin to implement readable rule expressions using given-when-then specifications. Unfortunately, "when" is a keyword in kotlin that would require escaping to use, so in the most basic examples, "and" is used instead. 7 | 8 | For example, to write the expression: 9 | 10 | Given a string 11 | when it is empty 12 | then print "Empty string" 13 | 14 | The rule in Kotlin would look like: 15 | 16 | ```kotlin 17 | val emptyRule = rule("Empty string") { 18 | given { 19 | anyString() 20 | } and { 21 | it.isEmpty() 22 | } thenDo { 23 | println("Empty string") 24 | } 25 | } 26 | 27 | emptyRule("") // Prints "Empty string" 28 | emptyRule("not empty") // Prints nothing 29 | ``` 30 | 31 | The `rule` helper creates a rule expression, starting with a description and a body called a rule definition. 32 | A rule expression is a Kotlin function that takes `Any` as a parameter, and attempts to evaluate a single rule. 33 | 34 | Inside the rule body (referred to as a "let clause" in the framework), the `given` helper defines the type of parameter expected by the rule, the `and` helper (standing in for `when`) defines the condition, and the `thenDo` defines the outcome of the rule. 35 | 36 | **Note:** The `and` helper is an alias for `expect`, but often reads better as a stand-in for the "when" in given-when-then in Kotlin code. 37 | 38 | You can also add an else condition to the rule that does something when the rule does not match: 39 | 40 | ```kotlin 41 | val emptyRule = rule("Empty string") { 42 | given { 43 | anyString() 44 | } and { 45 | it.isEmpty() 46 | } thenDo { 47 | println("Empty string") 48 | } otherwiseDo { 49 | println("Not an empty string") 50 | } 51 | } 52 | 53 | emptyRule("") // Prints "Empty string" 54 | emptyRule("not empty") // Prints "Not an empty string" 55 | ``` 56 | 57 | ## Rule Matching 58 | 59 | In the previous examples, the rule was being used to do something when it was applied. In the case of `thenDo` as the then expression, the rule expression does not return anything explicitly. In this case, the framework returns `true` when the rule matches or `false` when it fails to match the parameter: 60 | 61 | ```kotlin 62 | println(emptyRule("")) // Prints "true" 63 | println(emptyRule("not empty")) // Prints "false" 64 | ``` 65 | 66 | This allows you to extract the rule expression from some other code (including the outcome of the rule), and simply determine whether it matches or not. 67 | 68 | ```kotlin 69 | if (emptyRule(str)) { 70 | // Do something in your application when the rule matches 71 | } 72 | ``` 73 | 74 | ## Return Values 75 | 76 | In order to always simply return `true` or `false` when evaluating a condition, the given-when-then can be exchanged for a given-return specification: 77 | 78 | ```kotlin 79 | val emptyRule = rule("Empty string") { 80 | given { 81 | anyString() 82 | } alwaysReturn { 83 | it.isEmpty() 84 | } 85 | } 86 | 87 | println(emptyRule("")) // Prints "true" 88 | println(emptyRule("not empty")) // Prints "false" 89 | ``` 90 | 91 | In this case, it may not be obvious but the framework is always evaluating the condition (when part of given-when-then) as `true`, and evaluating and returning the result of the outcome (then part). Since the framework doesn't particularly care whether the rule matches or not, the end result is what you expect, and the rule expression simply returns `true` or `false`. 92 | 93 | In order to return something other than `true` or `false`, you can use a given-when-return specification that is similar to the above example but requires an alternate or default return value: 94 | 95 | ```kotlin 96 | val greetingRule = rule("Hello or Good bye") { 97 | given { 98 | anyString() 99 | } and { 100 | it == "Hi" 101 | } thenReturn { 102 | "Hello" 103 | } otherwiseReturn { 104 | "Good bye" 105 | } 106 | } 107 | 108 | println(greetingRule("Hi")) // Prints "Hello" 109 | println(greetingRule("Do I know you?")) // Prints "Good bye" 110 | ``` 111 | 112 | **Note:** The `thenReturn` and `otherwiseReturn` are aliases for `then` and `otherwise` and can be used interchangeably. 113 | 114 | Since this is just Kotlin code, you can also compact parts of your rule that you prefer to write in code. Here's an example with the same result as above using an if statement as the return value: 115 | 116 | ```kotlin 117 | val greetingRule = rule("Hello or Good bye") { 118 | given { 119 | anyString() 120 | } alwaysReturn { 121 | if (it == "Hi") "Hello" else "Good bye" 122 | } 123 | } 124 | 125 | println(greetingRule("Hi")) // Prints "Hello" 126 | println(greetingRule("Do I know you?")) // Prints "Good bye" 127 | ``` 128 | 129 | ## Type Safety 130 | 131 | The rule expressions start with a `given` that defines the input type. There are numerous ways of defining more interesting and useful input types, and the DSL allows type-safety within the rule expression. For example, to use a `Map` input type with strings: 132 | 133 | ```kotlin 134 | val john = mapOf( 135 | "id" to "123", 136 | "firstName" to "John", 137 | "lastName" to "Smith" 138 | ) 139 | val jane = mapOf( 140 | "id" to "456", 141 | "firstName" to "Jane", 142 | "lastName" to "Doe" 143 | ) 144 | 145 | val firstNameRule = rule("Customer first name is John") { 146 | given { 147 | usingMap().anyString("firstName") 148 | } and { 149 | it == "John" 150 | } thenReturn { 151 | "Hello, John" 152 | } otherwiseReturn { 153 | "Good bye, $it" 154 | } 155 | } 156 | 157 | println(firstNameRule(john)) // Prints "Hello, John" 158 | println(firstNameRule(jane)) // Prints "Good bye, Jane" 159 | ``` 160 | 161 | Types can also be coerced into any primitive, such as an `Int`: 162 | 163 | ```kotlin 164 | val idRule = rule("Customer is John") { 165 | given { 166 | usingMap().anyInt("id") 167 | } and { 168 | it == 123 169 | } thenReturn { 170 | "Hello, John" 171 | } otherwiseReturn { 172 | "Good bye, user $it" 173 | } 174 | } 175 | 176 | println(idRule(john)) // Prints "Hello, John" 177 | println(idRule(jane)) // Prints "Good bye, user 456" 178 | ``` 179 | 180 | **Note:** The same accessor methods such as `anyString`, `anyShort`, `anyInt`, `anyLong`, `anyFloat`, `anyDouble`, and `anyBoolean` work with `usingMap` and `usingJson` as well as by themselves with no parameters. 181 | 182 | ## Complex Types 183 | 184 | Possibly the most useful `given` expression is one that gives you access to an existing class you are using in your application. For example, to use a class called `Request`: 185 | 186 | ```kotlin 187 | data class Request(val path: String) 188 | 189 | val helloRequest = Request("/api/v1/hello") 190 | val userRequest = Request("/api/v1/user") 191 | 192 | val helloRule = rule("Path is hello") { 193 | given { 194 | any(Request::class) 195 | } whose { 196 | path == "/api/v1/hello" 197 | } thenReturn { 198 | "Hello" 199 | } otherwiseReturn { 200 | "Good bye" 201 | } 202 | } 203 | 204 | println(helloRule(helloRequest)) // Prints "Hello" 205 | println(helloRule(userRequest)) // Prints "Good bye" 206 | ``` 207 | 208 | The `any` helper takes a class argument to give the rule expression access to that input parameter. Additionally, the `whose` helper (standing in for `when` in given-when-then) is extremely useful and gives you access to the fields of `Request` directly for more natural expression syntax. 209 | 210 | Using Kotlin's extension functions, we can alias `any(Request::class)` as well: 211 | 212 | ```kotlin 213 | fun GivenExpression.anyRequest() = any(Request::class) 214 | 215 | val helloRule = rule("Path is hello") { 216 | given { 217 | anyRequest() 218 | } whose { 219 | path == "/api/v1/hello" 220 | } thenReturn { 221 | "Hello" 222 | } otherwiseReturn { 223 | "Good bye" 224 | } 225 | } 226 | 227 | println(helloRule(helloRequest)) // Prints "Hello" 228 | println(helloRule(userRequest)) // Prints "Good bye" 229 | ``` 230 | 231 | ## Rule Sets 232 | 233 | You can use the framework to build a list of rules, called a rule set. There's nothing particularly fancy about this, as the framework does not implement complex functionality on top of rule sets. You can use them however you choose. 234 | 235 | To implement a set of rules, use the `rules` helper which is an alias for `arrayOf`. Here's a more complex example: 236 | 237 | ```kotlin 238 | fun GivenExpression.anyRequest() = any(Request::class) 239 | 240 | fun requestFor(path: String, queryString: String? = null): Request { 241 | return Request( 242 | "Cookies: sid=abc123\nSM_USER=johndoe", 243 | "https://www.ecommerce.biz", 244 | path, 245 | queryString 246 | ) 247 | } 248 | 249 | val ruleSet = rules( 250 | rule("request is login") { 251 | given { 252 | anyRequest() 253 | } and { request -> 254 | request.requestPath.contains("/login") 255 | } thenDo { request -> 256 | println("Hello, ${request.requestPath}") 257 | } 258 | }, 259 | rule("request is send order") { 260 | given { 261 | anyRequest() 262 | } alwaysReturn { request -> 263 | request.requestPath.endsWith("/orders") 264 | } 265 | }, 266 | rule("request is logout") { 267 | given { 268 | anyRequest() 269 | } alwaysReturn { request -> 270 | request.requestPath.contains("/logout") 271 | } 272 | }, 273 | rule("request is search") { 274 | given { 275 | anyRequest() 276 | } whose { 277 | requestPath.contains("/search") 278 | } thenDo { 279 | println("printing a message in thenDo") 280 | } 281 | } 282 | ) 283 | 284 | val requests = listOf( 285 | requestFor("/api/v1/login"), 286 | requestFor("/api/v1/user"), 287 | requestFor("/api/v1/messages"), 288 | requestFor("/api/v1/dashboard"), 289 | requestFor("/api/v1/search", "category=Kitchen&q=Kitchen%20Aid%20Mixer"), 290 | requestFor("/api/v1/orders"), 291 | requestFor("/api/v1/orders/123"), 292 | requestFor("/api/v1/logout") 293 | ) 294 | 295 | 296 | for (i in requests.indices) { 297 | val request = requests[i] 298 | println("Processing event ${i + 1} with request path ${request.requestPath}") 299 | 300 | for (rule in ruleSet) { 301 | if (rule(request)) { 302 | println("+Rule \"${rule.description}\" matched") 303 | } 304 | } 305 | } 306 | ``` -------------------------------------------------------------------------------- /VERSIONS.md: -------------------------------------------------------------------------------- 1 | # Release Notes 2 | 3 | ## 0.0.4 4 | 5 | * Updated jackson to 2.11.1 6 | * Fixed import of `assertThat` to use `org.hamcrest.MatcherAssert` 7 | * Updated Kotlin to 1.3.72 8 | * Upgraded gradle to 6.4.1 9 | 10 | ## 0.0.3 11 | 12 | * Initial release (for version parity with in-spring-zeromq) -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import io.insource.build.Publishing 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | 4 | plugins { 5 | id("java") 6 | id("maven") 7 | id("signing") 8 | id("maven-publish") 9 | id("org.jetbrains.kotlin.jvm") version "1.6.0" 10 | id("org.jetbrains.kotlin.plugin.spring") version "1.6.0" 11 | } 12 | 13 | tasks.register("sourcesJar") { 14 | from(sourceSets.main.get().allSource) 15 | archiveClassifier.set("sources") 16 | } 17 | 18 | tasks.register("javadocJar") { 19 | from(tasks.javadoc) 20 | archiveClassifier.set("javadoc") 21 | } 22 | 23 | publishing { 24 | repositories { 25 | maven { 26 | url = uri("https://maven.pkg.github.com/InSourceSoftware/in-rules-engine") 27 | credentials { 28 | username = project.findProperty("servers.github.username")?.toString() ?: System.getenv("GITHUB_USERNAME") 29 | password = project.findProperty("servers.github.password")?.toString() ?: System.getenv("GITHUB_PASSWORD") 30 | } 31 | } 32 | maven { 33 | name = "ossrh" 34 | url = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/") 35 | credentials { 36 | username = project.findProperty("servers.ossrh.username")?.toString() ?: System.getenv("OSSRH_USERNAME") 37 | password = project.findProperty("servers.ossrh.password")?.toString() ?: System.getenv("OSSRH_PASSWORD") 38 | } 39 | } 40 | } 41 | 42 | publications { 43 | create("maven") { 44 | groupId = Publishing.groupId 45 | version = Publishing.version 46 | 47 | from(components["kotlin"]) 48 | artifact(tasks["sourcesJar"]) 49 | artifact(tasks["javadocJar"]) 50 | 51 | pom { 52 | name.set(Publishing.artifactId) 53 | description.set(Publishing.description) 54 | url.set(Publishing.url) 55 | licenses { 56 | license { 57 | name.set(Publishing.license) 58 | url.set(Publishing.licenseUrl) 59 | } 60 | } 61 | developers { 62 | developer { 63 | id.set(Publishing.developerUserName) 64 | name.set(Publishing.developerFullName) 65 | email.set(Publishing.developerEmailAddress) 66 | } 67 | } 68 | scm { 69 | connection.set(Publishing.connectionUrl) 70 | developerConnection.set(Publishing.developerConnectionUrl) 71 | url.set(Publishing.url) 72 | } 73 | } 74 | } 75 | } 76 | } 77 | 78 | signing { 79 | sign(publishing.publications["maven"]) 80 | } 81 | 82 | repositories { 83 | mavenLocal() 84 | mavenCentral() 85 | } 86 | 87 | dependencies { 88 | implementation("org.jetbrains.kotlin:kotlin-reflect") 89 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 90 | implementation("com.fasterxml.jackson.core:jackson-databind:2.13.0") 91 | testImplementation("junit:junit:4.13.2") 92 | testImplementation("org.hamcrest:hamcrest:2.2") 93 | } 94 | 95 | tasks.withType { 96 | kotlinOptions { 97 | freeCompilerArgs = listOf("-Xjsr305=strict") 98 | jvmTarget = "1.8" 99 | } 100 | } -------------------------------------------------------------------------------- /buildSrc/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.jetbrains.kotlin.jvm") version "1.3.72" 5 | id("org.jetbrains.kotlin.plugin.spring") version "1.3.72" 6 | } 7 | 8 | repositories { 9 | mavenLocal() 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation("org.jetbrains.kotlin:kotlin-reflect") 15 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 16 | } 17 | 18 | tasks.withType { 19 | kotlinOptions { 20 | freeCompilerArgs = listOf("-Xjsr305=strict") 21 | jvmTarget = "1.8" 22 | } 23 | } -------------------------------------------------------------------------------- /buildSrc/src/main/kotlin/io/insource/build/Publishing.kt: -------------------------------------------------------------------------------- 1 | package io.insource.build 2 | 3 | object Publishing { 4 | val groupId = "io.insource" 5 | val artifactId = "in-rules-engine" 6 | val version = "0.1.0" 7 | val description = "Kotlin rules engine DSL for maintaining rules and business logic in code." 8 | val url = "https://github.com/InSourceSoftware/in-rules-engine" 9 | val license = "Mozilla Public License Version 2.0" 10 | val licenseUrl = "http://mozilla.org/MPL/2.0/" 11 | val developerUserName = "sjohnr" 12 | val developerFullName = "Stephen Riesenberg" 13 | val developerEmailAddress = "sjohnr@hotmail.com" 14 | val connectionUrl = "scm:git:git://github.com/InSourceSoftware/in-rules-engine.git" 15 | val developerConnectionUrl = "scm:git:ssh://git@github.com:InSourceSoftware/in-rules-engine.git" 16 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | group=io.insource 2 | version=0.1.0 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/InSourceSoftware/in-rules-engine/c9fea5828095893bdc339de6757f0180f93bc5a7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | 88 | @rem Execute Gradle 89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 90 | 91 | :end 92 | @rem End local scope for the variables with windows NT shell 93 | if "%ERRORLEVEL%"=="0" goto mainEnd 94 | 95 | :fail 96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 97 | rem the _cmd.exe /c_ return code! 98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 99 | exit /b 1 100 | 101 | :mainEnd 102 | if "%OS%"=="Windows_NT" endlocal 103 | 104 | :omega 105 | -------------------------------------------------------------------------------- /src/main/kotlin/io/insource/framework/rule/Rule.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("unused") 2 | 3 | package io.insource.framework.rule 4 | 5 | import com.fasterxml.jackson.databind.node.ArrayNode 6 | import com.fasterxml.jackson.databind.node.ObjectNode 7 | import kotlin.reflect.KClass 8 | 9 | /** 10 | * Represents a rule function to be evaluated for a result. 11 | * 12 | * @param description The description of the rule function 13 | * @param ruleDefinition The definition of the rule 14 | * @param T The return type of the rule function 15 | */ 16 | class Rule(val description: String, val ruleDefinition: RuleDefinition) { 17 | /** 18 | * Execute the rule as a function. 19 | * 20 | * @param arg The rule argument, which can be any type the rule expects to handle 21 | */ 22 | operator fun invoke(arg: Any): T = ruleDefinition(arg).let { 23 | if (ruleDefinition.whenClause(it)) { 24 | ruleDefinition.thenClause(it) 25 | } else { 26 | ruleDefinition.elseClause(it) 27 | } 28 | } 29 | } 30 | 31 | /** 32 | * Represents a rule definition (e.g. an if-then expression). 33 | * 34 | * @param whenClause The if-part of a rule expression 35 | * @param thenClause The then-part of a rule expression 36 | */ 37 | class RuleDefinition( 38 | val givenClause: GivenExpression.() -> E, 39 | val whenClause: (E) -> Boolean, 40 | val thenClause: (E) -> T, 41 | val elseClause: (E) -> T 42 | ) { 43 | /** 44 | * Execute the given clause of a rule definition to retrieve a strongly-typed 45 | * rule argument. 46 | * 47 | * @param arg The rule argument, which can be any type the rule expects to handle 48 | */ 49 | internal operator fun invoke(arg: Any): E = GivenExpression(arg).givenClause() 50 | 51 | /** 52 | * Override the else-part of a rule expression with an action. 53 | * 54 | * @param elseClause The else-part of a rule expression 55 | * @return A rule definition 56 | */ 57 | infix fun otherwiseDo(elseClause: (E) -> Unit): RuleDefinition = RuleDefinition(givenClause, whenClause, thenClause, { elseClause(it); this.elseClause(it) }) 58 | } 59 | 60 | /** 61 | * A transparent type representing a rule expression. 62 | */ 63 | class RuleExpression { 64 | /** 65 | * Provide the pre-condition of a rule expression. 66 | * 67 | * @param givenClause The pre-condition of a rule expression 68 | * @return A when expression 69 | */ 70 | infix fun given(givenClause: GivenExpression.() -> E): WhenExpression = WhenExpression(givenClause) 71 | } 72 | 73 | /** 74 | * A transparent type used to extend the capabilities of a rule expression. 75 | * 76 | * @param arg The rule argument, which can be any type the rule expects to handle 77 | */ 78 | class GivenExpression(private val arg: Any) { 79 | companion object { 80 | /** 81 | * Accessor function to retrieve values from a Map. Null values throw a 82 | * `NoSuchElementException`. 83 | */ 84 | val MapAccessStrategy = fun(key: String, arg: Any): Any = (arg as Map<*, *>).let { 85 | if (it.containsKey(key)) it[key]!! else throw NoSuchElementException("Key $key not found") 86 | } 87 | 88 | /** 89 | * Accessor function to retrieve values from a JSON object. Null values throw a 90 | * `NoSuchElementException`. 91 | */ 92 | @Suppress("IMPLICIT_CAST_TO_ANY") 93 | val JsonAccessStrategy = fun(key: String, arg: Any): Any = (arg as ObjectNode).let { obj -> 94 | if (obj.has(key)) obj.get(key).let { 95 | when { 96 | it.isShort -> it.asInt().toShort() 97 | it.isInt -> it.asInt() 98 | it.isLong -> it.asLong() 99 | it.isFloat -> it.asDouble().toFloat() 100 | it.isDouble -> it.asDouble() 101 | it.isBoolean -> it.asBoolean() 102 | it.isTextual -> it.asText() 103 | else -> it 104 | } 105 | } 106 | else throw NoSuchElementException("Key $key not found") 107 | } 108 | 109 | /** 110 | * Default accessor function for rule expressions. 111 | */ 112 | var DefaultAccessStrategy = JsonAccessStrategy 113 | } 114 | 115 | /** 116 | * Apply the desired access strategy to this rule expression in order to 117 | * access a nested field. 118 | * 119 | * @param accessStrategy An accessor function to retrieve values from nested 120 | * objects. 121 | */ 122 | fun using(accessStrategy: (String, Any) -> Any): NestedGivenExpression = NestedGivenExpression(arg, accessStrategy) 123 | 124 | /** 125 | * Apply the `MapAccessStrategy` to this rule expression in order to access 126 | * nested fields in a `Map`. 127 | */ 128 | fun usingMap() = using(MapAccessStrategy) 129 | 130 | /** 131 | * Apply the `JsonAccessStrategy` to this rule expression in order to access 132 | * nested fields in a JSON object. 133 | */ 134 | fun usingJson() = using(JsonAccessStrategy) 135 | 136 | /** 137 | * Coerce the rule argument into a particular type. 138 | * 139 | * @param T The runtime type 140 | * @return The argument, as the desired runtime type 141 | */ 142 | fun any(clazz: KClass): T = clazz.java.cast(arg) 143 | 144 | /** 145 | * Coerce the rule argument into a `Map`. 146 | * 147 | * @return The argument, as a `Map` 148 | */ 149 | fun anyMap(): Map<*, *> = arg as Map<*, *> 150 | 151 | /** 152 | * Coerce the rule argument into a `MutableMap`. 153 | * 154 | * @return The argument, as a `MutableMap` 155 | */ 156 | fun anyMutableMap(): MutableMap<*, *> = arg as MutableMap<*, *> 157 | 158 | /** 159 | * Coerce the rule argument into an `ObjectNode`. 160 | * 161 | * @return The argument, as an `ObjectNode` 162 | */ 163 | fun anyObject(): ObjectNode = arg as ObjectNode 164 | 165 | /** 166 | * Coerce the rule argument into an `ArrayNode`. 167 | * 168 | * @return The argument, as an `ArrayNode` 169 | */ 170 | fun anyArray(): ArrayNode = arg as ArrayNode 171 | 172 | /** 173 | * Coerce the argument into a `String`. 174 | * 175 | * @return The argument, as a `String` 176 | */ 177 | fun anyString(): String = arg.toString() 178 | 179 | /** 180 | * Coerce the argument into a `Short`. 181 | * 182 | * @return The argument, as a `Short` 183 | */ 184 | fun anyShort(): Short = when (arg) { 185 | is Short -> arg 186 | is Number -> arg.toShort() 187 | else -> arg.toString().toShort() 188 | } 189 | 190 | /** 191 | * Coerce the argument into an `Int`. 192 | * 193 | * @return The argument, as an `Int` 194 | */ 195 | fun anyInt(): Int = when (arg) { 196 | is Int -> arg 197 | is Number -> arg.toInt() 198 | else -> arg.toString().toInt() 199 | } 200 | 201 | /** 202 | * Coerce the argument into a `Long`. 203 | * 204 | * @return The argument, as a `Long` 205 | */ 206 | fun anyLong(): Long = when (arg) { 207 | is Long -> arg 208 | is Number -> arg.toLong() 209 | else -> arg.toString().toLong() 210 | } 211 | 212 | /** 213 | * Coerce the argument into a `Float`. 214 | * 215 | * @return The argument, as a `Float` 216 | */ 217 | fun anyFloat(): Float = when (arg) { 218 | is Float -> arg 219 | is Number -> arg.toFloat() 220 | else -> arg.toString().toFloat() 221 | } 222 | 223 | /** 224 | * Coerce the argument into a `Double`. 225 | * 226 | * @return The argument, as a `Double` 227 | */ 228 | fun anyDouble(): Double = when (arg) { 229 | is Double -> arg 230 | is Number -> arg.toDouble() 231 | else -> arg.toString().toDouble() 232 | } 233 | 234 | /** 235 | * Coerce the argument into a `Boolean`. 236 | * 237 | * @return The argument, as a `Boolean` 238 | */ 239 | fun anyBoolean(): Boolean = when (arg) { 240 | is Boolean -> arg 241 | else -> arg.toString().toLowerCase().let { str -> 242 | when (str) { 243 | "t", "true", "y", "yes", "1", "+" -> true 244 | else -> false 245 | } 246 | } 247 | } 248 | 249 | /** 250 | * Coerce a nested field into a `String`. 251 | * 252 | * @param key The key of a nested property to retrieve 253 | * @return The argument, as a `String` 254 | */ 255 | fun anyString(key: String): String = using(DefaultAccessStrategy).anyString(key) 256 | 257 | /** 258 | * Coerce a nested field into a `Short`. 259 | * 260 | * @param key The key of a nested property to retrieve 261 | * @return The argument, as a `Short` 262 | */ 263 | fun anyShort(key: String): Short = using(DefaultAccessStrategy).anyShort(key) 264 | 265 | /** 266 | * Coerce a nested field into an `Int`. 267 | * 268 | * @param key The key of a nested property to retrieve 269 | * @return The argument, as an `Int` 270 | */ 271 | fun anyInt(key: String): Int = using(DefaultAccessStrategy).anyInt(key) 272 | 273 | /** 274 | * Coerce a nested field into a `Long`. 275 | * 276 | * @param key The key of a nested property to retrieve 277 | * @return The argument, as a `Long` 278 | */ 279 | fun anyLong(key: String): Long = using(DefaultAccessStrategy).anyLong(key) 280 | 281 | /** 282 | * Coerce a nested field into a `Float`. 283 | * 284 | * @param key The key of a nested property to retrieve 285 | * @return The argument, as a `Float` 286 | */ 287 | fun anyFloat(key: String): Float = using(DefaultAccessStrategy).anyFloat(key) 288 | 289 | /** 290 | * Coerce a nested field into a `Double`. 291 | * 292 | * @param key The key of a nested property to retrieve 293 | * @return The argument, as a `Double` 294 | */ 295 | fun anyDouble(key: String): Double = using(DefaultAccessStrategy).anyDouble(key) 296 | 297 | /** 298 | * Coerce a nested field into a `Boolean`. 299 | * 300 | * @param key The key of a nested property to retrieve 301 | * @return The argument, as a `Boolean` 302 | */ 303 | fun anyBoolean(key: String): Boolean = using(DefaultAccessStrategy).anyBoolean(key) 304 | } 305 | 306 | /** 307 | * A specialized rule expression for nested values. 308 | * 309 | * @param arg The rule argument, which can be any type the rule expects to handle 310 | * @param accessStrategy Accessor function to retrieve values from nested objects, e.g. an `ObjectNode` or `Map` 311 | */ 312 | class NestedGivenExpression(private val arg: Any, private var accessStrategy: (String, Any) -> Any) { 313 | /** 314 | * Coerce a nested field into a `Map`. 315 | * 316 | * @return The argument, as a `Map` 317 | */ 318 | fun anyMap(key: String): Map<*, *> = accessStrategy(key, arg) as Map<*, *> 319 | 320 | /** 321 | * Coerce a nested field into an `ObjectNode`. 322 | * 323 | * @return The argument, as an `ObjectNode` 324 | */ 325 | fun anyObject(key: String): ObjectNode = accessStrategy(key, arg) as ObjectNode 326 | 327 | /** 328 | * Coerce a nested field into an `ArrayNode`. 329 | * 330 | * @return The argument, as an `ArrayNode` 331 | */ 332 | fun anyArray(key: String): ArrayNode = accessStrategy(key, arg) as ArrayNode 333 | 334 | /** 335 | * Coerce a nested field into a `String`. 336 | * 337 | * @param key The key of a nested property to retrieve 338 | * @return The argument, as a `String` 339 | */ 340 | fun anyString(key: String): String = accessStrategy(key, arg).toString() 341 | 342 | /** 343 | * Coerce a nested field into a `Short`. 344 | * 345 | * @param key The key of a nested property to retrieve 346 | * @return The argument, as a `Short` 347 | */ 348 | fun anyShort(key: String): Short = accessStrategy(key, arg).let { 349 | when (it) { 350 | is Short -> it 351 | is Number -> it.toShort() 352 | else -> it.toString().toShort() 353 | } 354 | } 355 | 356 | /** 357 | * Coerce a nested field into an `Int`. 358 | * 359 | * @param key The key of a nested property to retrieve 360 | * @return The argument, as an `Int` 361 | */ 362 | fun anyInt(key: String): Int = accessStrategy(key, arg).let { 363 | when (it) { 364 | is Int -> it 365 | is Number -> it.toInt() 366 | else -> it.toString().toInt() 367 | } 368 | } 369 | 370 | /** 371 | * Coerce a nested field into a `Long`. 372 | * 373 | * @param key The key of a nested property to retrieve 374 | * @return The argument, as a `Long` 375 | */ 376 | fun anyLong(key: String): Long = accessStrategy(key, arg).let { 377 | when (it) { 378 | is Long -> it 379 | is Number -> it.toLong() 380 | else -> it.toString().toLong() 381 | } 382 | } 383 | 384 | /** 385 | * Coerce a nested field into a `Float`. 386 | * 387 | * @param key The key of a nested property to retrieve 388 | * @return The argument, as a `Float` 389 | */ 390 | fun anyFloat(key: String): Float = accessStrategy(key, arg).let { 391 | when (it) { 392 | is Float -> it 393 | is Number -> it.toFloat() 394 | else -> it.toString().toFloat() 395 | } 396 | } 397 | 398 | /** 399 | * Coerce a nested field into a `Double`. 400 | * 401 | * @param key The key of a nested property to retrieve 402 | * @return The argument, as a `Double` 403 | */ 404 | fun anyDouble(key: String): Double = accessStrategy(key, arg).let { 405 | when (it) { 406 | is Double -> it 407 | is Number -> it.toDouble() 408 | else -> it.toString().toDouble() 409 | } 410 | } 411 | 412 | /** 413 | * Coerce a nested field into a `Boolean`. 414 | * 415 | * @param key The key of a nested property to retrieve 416 | * @return The argument, as a `Boolean` 417 | */ 418 | fun anyBoolean(key: String): Boolean = accessStrategy(key, arg).let { 419 | when (it) { 420 | is Boolean -> it 421 | else -> it.toString().toLowerCase().let { str -> 422 | when (str) { 423 | "t", "true", "y", "yes", "1", "+" -> true 424 | else -> false 425 | } 426 | } 427 | } 428 | } 429 | } 430 | 431 | /** 432 | * A transparent type used to extend the capabilities of a rule expression. 433 | * 434 | * @param givenClause The pre-condition of a rule expression 435 | */ 436 | class WhenExpression(val givenClause: GivenExpression.() -> E) { 437 | /** 438 | * Provide the if-part of a rule expression. 439 | * 440 | * @param whenClause The if-part of a rule expression 441 | * @return A then expression 442 | */ 443 | infix fun expect(whenClause: (E) -> Boolean): ThenExpression = ThenExpression(givenClause, whenClause) 444 | 445 | /** 446 | * Alias for `expect`. 447 | * 448 | * @param whenClause The if-part of a rule expression 449 | * @return A then expression 450 | */ 451 | infix fun and(whenClause: (E) -> Boolean): ThenExpression = expect(whenClause) 452 | 453 | /** 454 | * Provide the if-part of a rule expression, as the argument supplied by the given. 455 | * 456 | * @param whenClause The if-part of a rule expression 457 | * @return A then expression 458 | */ 459 | infix fun whose(whenClause: E.() -> Boolean): ThenExpression = ThenExpression(givenClause, { it.whenClause() }) 460 | 461 | /** 462 | * Always return a value. This has the side effect of the rule always matching. 463 | * 464 | * @param thenClause Then then-part of a rule expression 465 | * @return A rule definition 466 | */ 467 | infix fun alwaysReturn(thenClause: (E) -> T): RuleDefinition = expect { true } thenReturn(thenClause) otherwiseReturn(thenClause) 468 | 469 | /** 470 | * Always perform an action. This has the side effect of the rule always matching. 471 | * 472 | * @param thenClause Then then-part of a rule expression 473 | * @return A rule definition 474 | */ 475 | infix fun alwaysDo(thenClause: (E) -> Unit): RuleDefinition = expect { true } thenDo(thenClause) 476 | } 477 | 478 | /** 479 | * A transparent type used to extend the capabilities of a rule expression. 480 | * 481 | * @param givenClause The pre-condition of a rule expression 482 | * @param whenClause The if-part of a rule expression 483 | */ 484 | class ThenExpression(val givenClause: GivenExpression.() -> E, val whenClause: (E) -> Boolean) { 485 | /** 486 | * Provide an additional if-part of a rule expression, AND'd to the first part. 487 | * 488 | * @param whenClause The if-part of a rule expression 489 | * @return A then expression 490 | */ 491 | infix fun and(whenClause: (E) -> Boolean): ThenExpression = ThenExpression(givenClause, { this.whenClause(it) && whenClause(it) }) 492 | 493 | /** 494 | * Provide an additional if-part of a rule expression, AND'd to the first part. 495 | * 496 | * @param whenClause The if-part of a rule expression 497 | * @return A then expression 498 | */ 499 | infix fun or(whenClause: (E) -> Boolean): ThenExpression = ThenExpression(givenClause, { this.whenClause(it) || whenClause(it) }) 500 | 501 | /** 502 | * Provide the then-part of a rule expression with a return value. 503 | * 504 | * @param thenClause Then then-part of a rule expression 505 | * @return An otherwise expression 506 | */ 507 | infix fun thenReturn(thenClause: (E) -> T): OtherwiseExpression = OtherwiseExpression(givenClause, whenClause, thenClause) 508 | 509 | /** 510 | * Provide the then-part of a rule expression with an action. 511 | * 512 | * @param thenClause Then then-part of a rule expression 513 | * @return A rule definition 514 | */ 515 | infix fun thenDo(thenClause: (E) -> Unit): RuleDefinition = RuleDefinition(givenClause, whenClause, { thenClause(it); true }, { false }) 516 | 517 | /** 518 | * Alias for `thenReturn`. 519 | * 520 | * @param thenClause Then then-part of a rule expression 521 | * @return An otherwise expression 522 | */ 523 | infix fun then(thenClause: (E) -> T): OtherwiseExpression = thenReturn(thenClause) 524 | } 525 | 526 | /** 527 | * A transparent type used to extend the capabilities of a rule expression. 528 | * 529 | * @param givenClause The pre-condition of a rule expression 530 | * @param whenClause The if-part of a rule expression 531 | * @param thenClause The then-part of a rule expression 532 | */ 533 | class OtherwiseExpression(val givenClause: GivenExpression.() -> E, val whenClause: (E) -> Boolean, val thenClause: (E) -> T) { 534 | /** 535 | * Override the else-part of a rule expression with a return value. 536 | * 537 | * @param elseClause The else-part of a rule expression 538 | * @return A rule definition 539 | */ 540 | infix fun otherwiseReturn(elseClause: (E) -> T): RuleDefinition = RuleDefinition(givenClause, whenClause, thenClause, elseClause) 541 | 542 | /** 543 | * Alias for `otherwiseReturn`. 544 | * 545 | * @param elseClause The else-part of a rule expression 546 | * @return A rule definition 547 | */ 548 | infix fun otherwise(elseClause: (E) -> T): RuleDefinition = otherwiseReturn(elseClause) 549 | } 550 | 551 | /** 552 | * Generate a rule function. 553 | * 554 | * @param description The description of the rule function 555 | * @param letClause The definition of the rule, as a function that returns a rule definition 556 | * @param T The return type of the rule function 557 | * @return A rule function 558 | */ 559 | fun rule(description: String, letClause: RuleExpression.() -> RuleDefinition): Rule { 560 | return Rule(description, RuleExpression().letClause()) 561 | } 562 | 563 | /** 564 | * Alias for arrayOf(...). 565 | * 566 | * @param rules 567 | */ 568 | fun rules(vararg rules: Rule): Array> = rules 569 | 570 | /** 571 | * Set the access strategy to retrieve values from a JSON object. 572 | */ 573 | fun useJsonAccessStrategy() { 574 | GivenExpression.DefaultAccessStrategy = GivenExpression.JsonAccessStrategy 575 | } 576 | 577 | /** 578 | * Set the access strategy to retrieve values from a Map. 579 | */ 580 | fun useMapAccessStrategy() { 581 | GivenExpression.DefaultAccessStrategy = GivenExpression.MapAccessStrategy 582 | } 583 | -------------------------------------------------------------------------------- /src/test/kotlin/io/insource/framework/rule/RuleTest.kt: -------------------------------------------------------------------------------- 1 | package io.insource.framework.rule 2 | 3 | import org.hamcrest.MatcherAssert.assertThat 4 | import org.hamcrest.Matchers.equalTo 5 | import org.junit.Before 6 | import org.junit.Test 7 | 8 | class RuleTest { 9 | @Before 10 | fun setUp() { 11 | useMapAccessStrategy() 12 | } 13 | 14 | @Test 15 | fun testRule_Scratch() { 16 | // Request class 17 | data class Request(val path: String) 18 | 19 | // Given accessor 20 | fun GivenExpression.anyRequest() = any(Request::class) 21 | 22 | val r = rule("Test rule with whose") { 23 | given { 24 | any(Request::class) 25 | } whose { 26 | path == "/api/v1/hello" 27 | } thenReturn { 28 | "Hello" 29 | } otherwiseReturn { 30 | "Good bye" 31 | } 32 | } 33 | 34 | val helloRequest = Request("/api/v1/hello") 35 | val userRequest = Request("/api/v1/user") 36 | 37 | assertThat(r(helloRequest), equalTo("Hello")) 38 | assertThat(r(userRequest), equalTo("Good bye")) 39 | } 40 | 41 | @Test 42 | fun testRule_ThenReturn() { 43 | val r = rule("Test rule thenReturn") { 44 | given { 45 | anyString() 46 | } and { 47 | it == "test" 48 | } thenReturn { 49 | "Hello" 50 | } otherwiseReturn { 51 | "Good bye" 52 | } 53 | } 54 | 55 | assertThat(r("test"), equalTo("Hello")) 56 | assertThat(r("nothing"), equalTo("Good bye")) 57 | } 58 | 59 | @Test 60 | fun testRule_ThenDo() { 61 | val r = rule("Test rule thenDo") { 62 | given { 63 | anyString() 64 | } and { 65 | it == "test" 66 | } thenDo { 67 | println("thenDo: Hello") 68 | } 69 | } 70 | 71 | assertThat(r("test"), equalTo(true)) 72 | assertThat(r("nothing"), equalTo(false)) 73 | } 74 | 75 | @Test 76 | fun testRule_MapKeyAsString() { 77 | val r = rule("Test rule with type String") { 78 | given { 79 | anyString("field1") 80 | } and { 81 | it == "x" 82 | } thenReturn { 83 | "Hello" 84 | } otherwiseReturn { 85 | "Good bye" 86 | } 87 | } 88 | 89 | val m = mapOf( 90 | "field1" to "x", 91 | "field2" to "y", 92 | "field3" to "z" 93 | ) 94 | assertThat(r(m), equalTo("Hello")) 95 | } 96 | 97 | @Test 98 | fun testRule_MapKeyAsInt() { 99 | val r = rule("Test rule with type Int") { 100 | given { 101 | anyInt("field1") 102 | } and { 103 | it == 1 104 | } thenReturn { 105 | "Hello" 106 | } otherwiseReturn { 107 | "Good bye" 108 | } 109 | } 110 | 111 | val m = mapOf( 112 | "field1" to 1, 113 | "field2" to 2, 114 | "field3" to 3 115 | ) 116 | assertThat(r(m), equalTo("Hello")) 117 | } 118 | 119 | @Test 120 | fun testRule_MapKeyAsBoolean() { 121 | val r = rule("Test rule with type Boolean") { 122 | given { 123 | anyBoolean("field1") 124 | } and { 125 | it 126 | } thenReturn { 127 | "Hello" 128 | } otherwiseReturn { 129 | "Good bye" 130 | } 131 | } 132 | 133 | val m = mapOf( 134 | "field1" to true, 135 | "field2" to false 136 | ) 137 | 138 | assertThat(r(m), equalTo("Hello")) 139 | } 140 | 141 | @Test(expected = NoSuchElementException::class) 142 | fun testRule_MapValueIsNull() { 143 | val r = rule("Test rule with type String, value is null") { 144 | given { 145 | anyString("field4") 146 | } and { 147 | it == "" 148 | } thenReturn { 149 | "Hello" 150 | } otherwiseReturn { 151 | "Good bye" 152 | } 153 | } 154 | 155 | val m = mapOf( 156 | "field1" to "x", 157 | "field2" to "y", 158 | "field3" to "z" 159 | ) 160 | 161 | r(m) 162 | } 163 | 164 | @Test 165 | fun testRule_AlwaysReturn() { 166 | val r = rule("Test rule with alwaysReturn") { 167 | given { 168 | anyString() 169 | } alwaysReturn { 170 | it == "test" 171 | } 172 | } 173 | 174 | assertThat(r("test"), equalTo(true)) 175 | assertThat(r("nothing"), equalTo(false)) 176 | } 177 | 178 | @Test 179 | fun testRule_AlwaysReturnBooleanInMap() { 180 | val r = rule("Test rule with alwaysReturn, type boolean") { 181 | given { anyBoolean("field3") } alwaysReturn { it } 182 | } 183 | 184 | val m = mapOf( 185 | "field1" to "0", 186 | "field2" to "false", 187 | "field3" to "t" 188 | ) 189 | 190 | assertThat(r(m), equalTo(true)) 191 | } 192 | 193 | @Test 194 | fun testRule_IfStatement() { 195 | val r = rule("Test rule with if-statement") { 196 | given { 197 | anyString() 198 | } alwaysReturn { 199 | if (it == "test") "Hello" else "Good bye" 200 | } 201 | } 202 | 203 | assertThat(r("test"), equalTo("Hello")) 204 | assertThat(r("other"), equalTo("Good bye")) 205 | } 206 | 207 | @Test 208 | fun testRule_CompoundWhen() { 209 | val r = rule("Test rule with compound when") { 210 | given { 211 | anyString() 212 | } and { 213 | it == "test" 214 | } or { 215 | it == "something" 216 | } thenReturn { 217 | "Hello" 218 | } otherwiseReturn { 219 | "Good bye" 220 | } 221 | } 222 | 223 | assertThat(r("test"), equalTo("Hello")) 224 | assertThat(r("something"), equalTo("Hello")) 225 | assertThat(r("nothing"), equalTo("Good bye")) 226 | } 227 | 228 | @Test 229 | fun testRule_Fluent() { 230 | val r = rule("Test rule with fluent syntax") { 231 | val givenClause: GivenExpression.() -> String = { anyString() } 232 | val whenClause = { s: String -> s == "test" } 233 | val thenClause = { s: String -> "Hello" } 234 | val elseClause = { s: String -> "Good bye" } 235 | 236 | given(givenClause) 237 | .and(whenClause) 238 | .thenReturn(thenClause) 239 | .otherwiseReturn(elseClause) 240 | } 241 | 242 | assertThat(r("test"), equalTo("Hello")) 243 | assertThat(r("nothing"), equalTo("Good bye")) 244 | } 245 | 246 | @Test 247 | fun testRule_Whose() { 248 | // Request class 249 | data class Request(val path: String) 250 | 251 | // Given accessor 252 | fun GivenExpression.anyRequest() = any(Request::class) 253 | 254 | val r = rule("Test rule with whose") { 255 | given { 256 | anyRequest() 257 | } whose { 258 | path == "/api/v1/hello" 259 | } thenReturn { 260 | "Hello" 261 | } otherwiseReturn { 262 | "Good bye" 263 | } 264 | } 265 | 266 | val helloRequest = Request("/api/v1/hello") 267 | val userRequest = Request("/api/v1/user") 268 | 269 | assertThat(r(helloRequest), equalTo("Hello")) 270 | assertThat(r(userRequest), equalTo("Good bye")) 271 | } 272 | } -------------------------------------------------------------------------------- /src/test/kotlin/io/insource/framework/rule/RulesEngineTest.kt: -------------------------------------------------------------------------------- 1 | package io.insource.framework.rule 2 | 3 | import org.junit.Before 4 | import org.junit.Test 5 | 6 | class RulesEngineTest { 7 | @Before 8 | fun setUp() { 9 | useMapAccessStrategy() 10 | } 11 | 12 | @Test 13 | fun testRulesEngine_Map() { 14 | val ruleSet = rules( 15 | rule("request is login") { 16 | given { 17 | anyString("requestPath") 18 | } alwaysReturn { 19 | it.contains("/login") 20 | } 21 | }, 22 | rule("request is send order") { 23 | given { 24 | anyString("requestPath") 25 | } alwaysReturn { 26 | it.endsWith("/orders") 27 | } 28 | }, 29 | rule("request is logout") { 30 | given { 31 | anyString("requestPath") 32 | } alwaysReturn { 33 | it.contains("/logout") 34 | } 35 | } 36 | ) 37 | 38 | val events = listOf( 39 | eventFor("/api/v1/login"), 40 | eventFor("/api/v1/user"), 41 | eventFor("/api/v1/messages"), 42 | eventFor("/api/v1/dashboard"), 43 | eventFor("/api/v1/search", "category=Kitchen&q=Kitchen%20Aid%20Mixer"), 44 | eventFor("/api/v1/orders"), 45 | eventFor("/api/v1/orders/123"), 46 | eventFor("/api/v1/logout") 47 | ) 48 | 49 | for (i in events.indices) { 50 | val event = events[i] 51 | println("Processing event ${i + 1} with request path ${event["requestPath"]}") 52 | 53 | for (rule in ruleSet) { 54 | if (rule(event)) { 55 | println("+Rule \"${rule.description}\" matched") 56 | } 57 | } 58 | } 59 | } 60 | 61 | @Test 62 | fun testRulesEngine_Request() { 63 | val ruleSet = rules( 64 | rule("request is login") { 65 | given { 66 | anyRequest() 67 | } and { request -> 68 | request.requestPath.contains("/login") 69 | } thenDo { request -> 70 | println("Hello, ${request.requestPath}") 71 | } 72 | }, 73 | rule("request is send order") { 74 | given { 75 | anyRequest() 76 | } alwaysReturn { request -> 77 | request.requestPath.endsWith("/orders") 78 | } 79 | }, 80 | rule("request is logout") { 81 | given { 82 | anyRequest() 83 | } alwaysReturn { request -> 84 | request.requestPath.contains("/logout") 85 | } 86 | }, 87 | rule("request is search") { 88 | given { 89 | anyRequest() 90 | } whose { 91 | requestPath.contains("/search") 92 | } thenDo { 93 | println("printing a message in thenDo") 94 | } 95 | } 96 | ) 97 | 98 | val requests = listOf( 99 | requestFor("/api/v1/login"), 100 | requestFor("/api/v1/user"), 101 | requestFor("/api/v1/messages"), 102 | requestFor("/api/v1/dashboard"), 103 | requestFor("/api/v1/search", "category=Kitchen&q=Kitchen%20Aid%20Mixer"), 104 | requestFor("/api/v1/orders"), 105 | requestFor("/api/v1/orders/123"), 106 | requestFor("/api/v1/logout") 107 | ) 108 | 109 | 110 | for (i in requests.indices) { 111 | val request = requests[i] 112 | println("Processing event ${i + 1} with request path ${request.requestPath}") 113 | 114 | for (rule in ruleSet) { 115 | if (rule(request)) { 116 | println("+Rule \"${rule.description}\" matched") 117 | } 118 | } 119 | } 120 | } 121 | 122 | private fun GivenExpression.anyRequest() = any(Request::class) 123 | 124 | companion object { 125 | private fun eventFor(path: String, queryString: String? = null): Map { 126 | return mapOf( 127 | "headers" to "Cookies: sid=abc123\nSM_USER=johndoe", 128 | "requestURL" to "https://www.ecommerce.biz", 129 | "requestPath" to path, 130 | "queryString" to queryString 131 | ) 132 | } 133 | 134 | private fun requestFor(path: String, queryString: String? = null): Request { 135 | return Request( 136 | "Cookies: sid=abc123\nSM_USER=johndoe", 137 | "https://www.ecommerce.biz", 138 | path, 139 | queryString 140 | ) 141 | } 142 | } 143 | 144 | data class Request( 145 | val headers: String, 146 | val requestUrl: String, 147 | val requestPath: String, 148 | val queryString: String? 149 | ) 150 | } --------------------------------------------------------------------------------