├── .classpath
├── .gitignore
├── .project
├── .settings
└── .gitignore
├── LICENSE
├── README.md
├── pom.xml
├── reference
├── rule-mysql.sql
├── rule-oracle.sql
├── table-1.png
└── table-2.png
└── src
└── main
├── java
└── tech
│ └── kiwa
│ └── engine
│ ├── EngineService.java
│ ├── component
│ ├── AbstractCommand.java
│ ├── AbstractComparisonOperator.java
│ ├── AbstractResultLogRecorder.java
│ ├── AbstractRuleItem.java
│ ├── AbstractRuleReader.java
│ ├── drools
│ │ ├── ConstraintCreator.java
│ │ ├── DeclareCreator.java
│ │ ├── DeclareInterface.java
│ │ ├── DroolsBuilder.java
│ │ ├── DroolsPartsCreator.java
│ │ ├── DroolsPartsObject.java
│ │ ├── FunctionCreator.java
│ │ ├── GlobalCreator.java
│ │ ├── ImportCreator.java
│ │ ├── LocalCreator.java
│ │ ├── PackageCreator.java
│ │ ├── QueryCreator.java
│ │ └── RuleCreator.java
│ └── impl
│ │ ├── ComplexRuleExecutor.java
│ │ ├── DBRuleReader.java
│ │ ├── DefaultRuleExecutor.java
│ │ ├── DroolsRuleExecutor.java
│ │ ├── DroolsRuleReader.java
│ │ └── XMLRuleReader.java
│ ├── entity
│ ├── EngineRunResult.java
│ ├── ItemExecutedResult.java
│ ├── RESULT.java
│ └── RuleItem.java
│ ├── exception
│ ├── EmptyResultSetException.java
│ └── RuleEngineException.java
│ ├── framework
│ ├── Component.java
│ ├── DBAccesser.java
│ ├── FactoryMethod.java
│ ├── OperatorFactory.java
│ └── ResultLogFactory.java
│ ├── sample
│ ├── BlackListShow.java
│ └── Student.java
│ └── utility
│ ├── DirectDBAccesser.java
│ ├── JavaStringCompiler.java
│ ├── MemoryClassLoader.java
│ ├── MemoryJavaFileManager.java
│ ├── PropertyUtil.java
│ ├── SpringContextHelper.java
│ └── SpringDBAccesser.java
└── resources
├── druid.properties
├── ruleEngine.properties
├── ruleconfig.xml
├── sample.drl
└── studentrule.xml
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | /.setttings/
3 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | RuleEngine
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.wst.common.project.facet.core.builder
10 |
11 |
12 |
13 |
14 | org.eclipse.jdt.core.javabuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.wst.validation.validationbuilder
20 |
21 |
22 |
23 |
24 | org.eclipse.m2e.core.maven2Builder
25 |
26 |
27 |
28 |
29 |
30 | org.eclipse.jem.workbench.JavaEMFNature
31 | org.eclipse.wst.common.modulecore.ModuleCoreNature
32 | org.eclipse.jdt.core.javanature
33 | org.eclipse.m2e.core.maven2Nature
34 | org.eclipse.wst.common.project.facet.core.nature
35 |
36 |
37 |
--------------------------------------------------------------------------------
/.settings/.gitignore:
--------------------------------------------------------------------------------
1 | /org.eclipse.core.resources.prefs
2 | /org.eclipse.jdt.core.prefs
3 | /org.eclipse.m2e.core.prefs
4 | /org.eclipse.wst.common.component
5 | /org.eclipse.wst.common.project.facet.core.xml
6 | /org.eclipse.wst.validation.prefs
7 |
--------------------------------------------------------------------------------
/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 [Hale.Li] [hale2000@163.com]
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### RuleEngine
2 | one of the best simple rule engine, easy to use, can define different format of the rule, such as xml, drools, database.
3 |
4 | ###使用方法
5 |
6 | #1, 在POM.XML文件中添加下面的内容.
7 |
8 |
9 | com.github.hale-lee
10 | RuleEngine
11 | 0.2.0
12 |
13 |
14 |
15 | #2, 配置ruleEngine.properties文件
16 |
17 | rule.reader=xml/drools/database
18 |
19 | -2.1 若选择xml格式的规则文件,那么rule.reader=xml,此时需要设置xml.rule.filename=ruleconfig.xml
20 |
21 | -2.2 若选择将规则文件定义存放在数据库中,那么设置rule.reader=database,此时需要设置db.rule.table=表名 (存放规则定义的表格,其格式可以参考SQL文件夹下的rule-mysql.sql或rule-oracle.sql)同时需要配置或者引用现有框架的jdbc配置, RuleEngine支持直接的jdbc数据库,也支持druid的数据库连接池,还可以直接引用外部框架的的数据库链接,比如spring-mvc的数据库链接。
22 |
23 | -2.3 若选择使用drools格式的规则文件,则设置rule.reader=drools,同时需要设置drools.rule.filename=sample.drl
24 |
25 |
26 | #3,引用调用
27 |
28 | 直接import EngineService类,生成EngineService对象,同时将需要校验的bean作为Object传入给EngineService对象的Start方法。
29 | 如下所示:
30 |
31 | EngineService service = new EngineService();
32 |
33 | try {
34 |
35 | Student st = new Student();
36 | st.setAge(5);
37 | st.name = "tom";
38 | st.sex = 1;
39 |
40 | EngineRunResult result = service.start(st);
41 | System.out.println(result.getResult().getName());
42 |
43 | System.out.println(st.getAge());
44 | } catch (RuleEngineException e) {
45 |
46 | e.printStackTrace();
47 | }
48 |
49 |
50 | #4,编写规则
51 |
52 |
53 |
54 | -4.1 若2.1选择了xml格式的规则,则需要配置xml.rule.filename项目,这个地方填写规则的文件名,需要指定为xml文件格式。
55 | 典型的规则项目为:
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 | -4.2 若2.2选择了drools格式的规则,则需要配置drools.rule.filename项目,这个地方填写规则的文件名,需要指定为drl文件格式。
66 | 典型的规则项目为:
67 |
68 |
69 | rule "ageUp12"
70 | salience 400
71 | when
72 | $student: Student(age < 8)
73 | /* antoher rule */
74 | then
75 | System.out.println("I was called, my name is : " + $student.name);
76 | ageUp($student,12);
77 | //callOver($student);
78 | end
79 |
80 |
81 | -4.3 若2.3选择database格式的规则,则需要配置db.rule.table项目,这个地方填写规则的数据库表结构,其表生成的结构可以参考SQL目录下的2个文件。典型 的规则描述如下:
82 |
83 |
84 | item_no|content|exe_sql|exe_class|param_name|param_type|comparison_code|comparison_value|baseline|result|executor|priority|continue_flag|parent_item_no|group_express|remark|comments|enable_flag|create_time|update_time
85 | 11|黑名单|select count(1) as cnt from tl_blacklist where customer_no = ? and delete_flag = 1|customer_no|java.lang.String|01|==|0|PASSED|100|1|1|2018-02-26 12:40:15.000000|2018-02-26 12:40:18.000000
86 |
87 |
88 | 数据库连接方式时,需要同时设置db.accesser,如果是直接使用druid的数据库连接池,可以设置成db.accesser=tech.kiwa.engine.utility.DirectDBAccesser,DirectDBAccesser提供了开关变量UseDruid,如果设置成true就是使用了druid连接池,如果设置成false则是直接地jdbc。
89 |
如果使用Spring的数据库连接,可以设置成db.accesser=tech.kiwa.engine.utility.SpringDBAccesser.
90 |
91 |
92 |
93 |
94 |
95 |
96 | https://github.com/Hale-Lee/RuleEngine/wiki
97 |
98 | 微信: woyishixinghren
99 |
100 | 加微信请注明:规则引擎
101 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.github.hale-lee
5 | RuleEngine
6 | 0.2.0
7 | Hale
8 |
9 | org.sonatype.oss
10 | oss-parent
11 | 8
12 |
13 |
14 |
15 |
16 | The Apache Software License, Version 2.0
17 | http://www.apache.org/licenses/LICENSE-2.0.txt
18 | repo
19 |
20 |
21 |
22 |
23 | https://github.com/Hale-Lee/RuleEngine
24 | https://github.com/Hale-Lee/RuleEngine.git
25 | https://www.kiwa.tech
26 |
27 |
28 |
29 |
30 | hale
31 | hale2000@163.com
32 | http://www.kiwa.tech
33 |
34 |
35 |
36 |
37 | UTF-8
38 | 1.2.3
39 | 1.7.25
40 | 4.3.1.RELEASE
41 |
42 |
43 |
44 |
52 |
53 |
59 |
60 |
61 | org.springframework
62 | spring-context
63 | ${spring.version}
64 |
65 |
66 |
72 |
73 |
74 | ch.qos.logback
75 | logback-classic
76 | ${logback.version}
77 |
78 |
79 | ch.qos.logback
80 | logback-access
81 | ${logback.version}
82 |
83 |
84 | org.slf4j
85 | jcl-over-slf4j
86 | ${org.slf4j.version}
87 |
88 |
89 |
90 |
91 | com.alibaba
92 | druid
93 | 1.1.22
94 |
95 |
96 |
97 | commons-lang
98 | commons-lang
99 | 2.5
100 |
101 |
102 |
109 |
110 |
111 | ojdbc
112 | ojdbc
113 | 14
114 |
115 |
116 |
117 | mysql
118 | mysql-connector-java
119 | 8.0.20
120 |
121 |
122 |
123 |
124 |
125 |
126 | src/main/resources
127 | true
128 |
136 |
137 |
138 | RuleEngine
139 |
140 |
141 |
142 | maven-compiler-plugin
143 | 3.6.0
144 |
145 | 1.8
146 | 1.8
147 |
148 |
149 |
150 | org.apache.maven.plugins
151 | maven-dependency-plugin
152 | 2.10
153 |
154 |
155 | copy-dependencies
156 | package
157 |
158 | copy-dependencies
159 |
160 |
161 | /target
162 |
163 |
164 |
165 |
166 |
167 |
168 | org.apache.maven.plugins
169 | maven-jar-plugin
170 | 2.4
171 |
172 |
173 |
174 | true
175 |
176 |
177 |
178 |
179 |
180 | org.apache.maven.plugins
181 | maven-gpg-plugin
182 | 1.6
183 |
184 |
185 | sign-artifacts
186 | verify
187 |
188 | sign
189 |
190 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 | www.kiwa.tech
202 |
203 |
204 |
205 |
206 |
--------------------------------------------------------------------------------
/reference/rule-mysql.sql:
--------------------------------------------------------------------------------
1 |
2 |
3 | SET FOREIGN_KEY_CHECKS=0;
4 |
5 | -- ----------------------------
6 | -- Table structure for TL_RULE_DEFINE
7 | -- ----------------------------
8 | DROP TABLE IF EXISTS `TL_RULE_DEFINE`;
9 | CREATE TABLE `TL_RULE_DEFINE` (
10 | `item_no` varchar(32) NOT NULL,
11 | `content` varchar(128) DEFAULT NULL COMMENT '中文的内容说明',
12 | `exe_sql` varchar(512) DEFAULT NULL COMMENT '执行检查的SQL语句',
13 | `exe_class` varchar(128) DEFAULT NULL COMMENT '执行检查的java类名, 与exe_sql二者只填写一项',
14 | `param_name` varchar(128) DEFAULT NULL COMMENT 'exe_sql或者exe_class的参数,多个参数用逗号(,)分割。',
15 | `param_type` varchar(255) DEFAULT NULL COMMENT 'exe_sql或者exe_class的参数类型,多个类型用逗号(,)分割,与param_name需一一对应。',
16 | `comparison_code` varchar(32) DEFAULT NULL COMMENT '01: == , 02: > , 03 : < , 04 != , 05 >= , 06: <= , 07 include , 08 exclude , 09: included by 10: excluded by 11: equal , 12 : not equal 13: euqalIngoreCase',
17 | `comparison_value` varchar(64) DEFAULT NULL COMMENT ' =,>,<,>=,<=, !=, include, exclude等内容。' ,
18 | `baseline` varchar(64) DEFAULT NULL COMMENT '参数值,比较目标值',
19 | `result` varchar(6) DEFAULT NULL COMMENT '1 - 通过 2 - 关注 3 -拒绝 逻辑运算满足目标值的时候读取改内容。',
20 | `executor` varchar(128) DEFAULT NULL COMMENT '结果执行后的被执行体,从AbstractCommand中继承下来。',
21 | `priority` varchar(32) DEFAULT NULL COMMENT '执行的优先顺序,值大的优先执行.',
22 | `continue_flag` varchar(2) DEFAULT NULL COMMENT '1: 继续执行下一条 其他:中断执行',
23 | `parent_item_no` varchar(32) DEFAULT NULL COMMENT '如果是子规则,那么需要填写父规则的item_no',
24 | `group_express` varchar(256) DEFAULT NULL COMMENT '同一PARENT_ITEM的各个ITEM的运算表达式。 ( A AND B OR C)',
25 | `remark` varchar(128) DEFAULT NULL,
26 | `comments` varchar(128) DEFAULT NULL,
27 | `enable_flag` varchar(2) DEFAULT NULL COMMENT '是否有效,enable_flag = 1表示有效,其余: 无效',
28 | `create_time` datetime(6) DEFAULT NULL,
29 | `update_time` datetime(6) DEFAULT NULL,
30 | PRIMARY KEY (`item_no`)
31 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
32 |
--------------------------------------------------------------------------------
/reference/rule-oracle.sql:
--------------------------------------------------------------------------------
1 |
2 |
3 | -- ----------------------------
4 | -- Table structure for TL_RULE_DEFINE
5 | -- ----------------------------
6 | DROP TABLE "TL_RULE_DEFINE";
7 | CREATE TABLE "TL_RULE_DEFINE" (
8 | "ITEM_NO" NVARCHAR2(32) NOT NULL ,
9 | "CONTENT" NVARCHAR2(256) NULL ,
10 | "EXE_SQL" NVARCHAR2(512) NULL ,
11 | "EXE_CLASS" NVARCHAR2(128) NULL ,
12 | "PARAM_NAME" NVARCHAR2(128) NULL ,
13 | "PARAM_TYPE" NVARCHAR2(128) NULL ,
14 | "COMPARISON_CODE" NVARCHAR2(32) NULL ,
15 | "COMPARISON_VALUE" NVARCHAR2(64) NULL ,
16 | "BASELINE" NVARCHAR2(64) NULL ,
17 | "RESULT" NVARCHAR2(6) NULL ,
18 | "PRIORITY" NVARCHAR2(32) NULL ,
19 | "CONTINUE_FLAG" NVARCHAR2(2) NULL ,
20 | "PARENT_ITEM_NO" NVARCHAR2(2) NULL ,
21 | "PARENT_EXPRESS" NVARCHAR2(256) NULL ,
22 | "EXECUTOR" NVARCHAR2(64) NULL ,
23 | "REMARK" NVARCHAR2(64) NULL ,
24 | "COMMENTS" NVARCHAR2(64) NULL ,
25 | "ENABLE_FLAG" NVARCHAR2(2) NULL ,
26 | "CREATE_TIME" TIMESTAMP(6) NULL ,
27 | "UPDATE_TIME" TIMESTAMP(6) NULL
28 | )
29 | LOGGING
30 | NOCOMPRESS
31 | NOCACHE
32 |
33 | ;
34 | COMMENT ON TABLE "TL_RULE_DEFINE" IS '规则引擎定义表';
35 | COMMENT ON COLUMN "TL_RULE_DEFINE"."ITEM_NO" IS '主key';
36 | COMMENT ON COLUMN "TL_RULE_DEFINE"."CONTENT" IS '中文的内容说明';
37 | COMMENT ON COLUMN "TL_RULE_DEFINE"."EXE_SQL" IS '执行的SQL语句';
38 | COMMENT ON COLUMN "TL_RULE_DEFINE"."EXE_CLASS" IS '执行检查的java类名, 与exe_sql二者只填写一项';
39 | COMMENT ON COLUMN "TL_RULE_DEFINE"."PARAM_NAME" IS 'SQL语句的参数,多个参数用,分割,读值时需要完成和继承DefaultCustomerCheck类。';
40 | COMMENT ON COLUMN "TL_RULE_DEFINE"."PARAM_TYPE" IS 'exe_sql或者exe_class的参数类型,多个类型用逗号(,)分割,与param_name需一一对应。';
41 | COMMENT ON COLUMN "TL_RULE_DEFINE"."COMPARISON_CODE" IS '01: = , 02: > , 03 : < , 04 != , 05 >= , 06: <= , 07 include , 08 exclude , 09: included by 10: excluded by 11: equal , 12 : not equal 13: euqalIngoreCase 15: matches 16: NOT MATCHES';
42 | COMMENT ON COLUMN "TL_RULE_DEFINE"."COMPARISON_VALUE" IS '=,>,<,>=,<=, !=, include, exclude等内容。';
43 | COMMENT ON COLUMN "TL_RULE_DEFINE"."BASELINE" IS '参数值,比较目标值';
44 | COMMENT ON COLUMN "TL_RULE_DEFINE"."RESULT" IS '1 - 通过 2 - 关注 3 -拒绝 逻辑运算满足目标值的时候读取改内容。';
45 | COMMENT ON COLUMN "TL_RULE_DEFINE"."PRIORITY" IS '执行的优先顺序,值大的优先执行.';
46 | COMMENT ON COLUMN "TL_RULE_DEFINE"."CONTINUE_FLAG" IS '是否继续执行下一条,如果某条规则满足中断的话,那么就设置为 2. 1 -- 继续 2 -- 中断';
47 | COMMENT ON COLUMN "TL_RULE_DEFINE"."PARENT_ITEM_NO" IS '如果是子规则,那么需要填写父规则的item_no';
48 | COMMENT ON COLUMN "TL_RULE_DEFINE"."PARENT_EXPRESS" IS '同一PARENT_ITEM的各个ITEM的运算表达式。 ( A AND B OR C)';
49 | COMMENT ON COLUMN "TL_RULE_DEFINE"."EXECUTOR" IS '结果执行后的被执行体,从AbstractCommand中继承下来。';
50 | COMMENT ON COLUMN "TL_RULE_DEFINE"."ENABLE_FLAG" IS '是否使用 1 - 有效 2 - 失效';
51 |
52 | -- ----------------------------
53 | -- Checks structure for table TL_RULE_DEFINE
54 | -- ----------------------------
55 | ALTER TABLE "TL_RULE_DEFINE" ADD CHECK ("ITEM_NO" IS NOT NULL);
56 |
--------------------------------------------------------------------------------
/reference/table-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hale-Lee/RuleEngine/bb9d019dd52bb45a8ceb2ae178f378a8322aad85/reference/table-1.png
--------------------------------------------------------------------------------
/reference/table-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hale-Lee/RuleEngine/bb9d019dd52bb45a8ceb2ae178f378a8322aad85/reference/table-2.png
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/EngineService.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine;
16 |
17 | import java.util.List;
18 | import java.util.Map;
19 | import java.util.Random;
20 |
21 | import org.apache.commons.lang.StringUtils;
22 | import org.slf4j.Logger;
23 | import org.slf4j.LoggerFactory;
24 |
25 | import tech.kiwa.engine.component.AbstractRuleItem;
26 | import tech.kiwa.engine.component.AbstractRuleReader;
27 | import tech.kiwa.engine.component.impl.ComplexRuleExecutor;
28 | import tech.kiwa.engine.component.impl.DBRuleReader;
29 | import tech.kiwa.engine.component.impl.DefaultRuleExecutor;
30 | import tech.kiwa.engine.component.impl.DroolsRuleReader;
31 | import tech.kiwa.engine.component.impl.XMLRuleReader;
32 | import tech.kiwa.engine.entity.EngineRunResult;
33 | import tech.kiwa.engine.entity.ItemExecutedResult;
34 | import tech.kiwa.engine.entity.RESULT;
35 | import tech.kiwa.engine.entity.RuleItem;
36 | import tech.kiwa.engine.exception.RuleEngineException;
37 | import tech.kiwa.engine.framework.ResultLogFactory;
38 | import tech.kiwa.engine.sample.Student;
39 | import tech.kiwa.engine.utility.PropertyUtil;
40 |
41 | /**
42 | * 入口类,所有的执行,必须从该类中开始。
43 | * @author Hale.Li
44 | * @since 2018-01-28
45 | * @version 0.1
46 | */
47 | public class EngineService {
48 |
49 |
50 | private AbstractRuleReader itemService = loadService();
51 |
52 | private Logger log = LoggerFactory.getLogger(EngineService.class);
53 |
54 | private String seq = null;
55 |
56 | @SuppressWarnings("unchecked")
57 | private AbstractRuleReader loadService(){
58 |
59 | if(itemService != null){
60 | return itemService;
61 | }
62 |
63 | AbstractRuleReader reader = null;
64 |
65 | String serviceName = PropertyUtil.getProperty("rule.reader");
66 | switch(serviceName.toLowerCase()){
67 | case "database":
68 | reader = new DBRuleReader();
69 | break;
70 | case "xml":
71 | reader = new XMLRuleReader();
72 | break;
73 | case "drools":
74 | reader = new DroolsRuleReader();
75 | break;
76 | default:
77 | Class ServiceClass;
78 | try {
79 | ServiceClass = (Class) Class.forName(serviceName);
80 | reader = ServiceClass.newInstance();
81 | } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
82 | log.debug(e.getMessage());
83 | }
84 |
85 | break;
86 | }
87 |
88 | itemService = reader;
89 | return reader;
90 | }
91 |
92 | /**
93 | * 启动函数,传入一个对象进来就可以比较了。
94 | * @param object
95 | * @return
96 | * @throws RuleEngineException
97 | */
98 | public EngineRunResult start(Object object ) throws RuleEngineException{
99 | return this.start(object, null);
100 | }
101 |
102 | public EngineRunResult start(Map object ) throws RuleEngineException{
103 | return this.start((String)object.get("Id"), null);
104 | }
105 |
106 | /**
107 | * 启动函数,传入对象和系列号作比较。
108 | * @param object
109 | * @param sequence
110 | * @return
111 | * @throws RuleEngineException
112 | */
113 | @SuppressWarnings("unchecked")
114 | public EngineRunResult start(Object object , String sequence) throws RuleEngineException{
115 |
116 | List itemList = itemService.readRuleItemList();
117 |
118 | itemList = itemService.filterItem(itemList, null);
119 | itemList = itemService.sortItem(itemList, null);
120 |
121 | this.seq = sequence;
122 |
123 | EngineRunResult ret_Result = new EngineRunResult();
124 | ret_Result.setResult(RESULT.PASSED);
125 | ret_Result.setResult_desc("PASSED");
126 |
127 | for(RuleItem item : itemList){
128 |
129 | log.debug("started to execute the rule item check. item = {}, ObjectId ={}", item.getItemNo(), object);
130 |
131 | if(StringUtils.isNotEmpty(item.getGroupExpress())){
132 |
133 | ComplexRuleExecutor executor = new ComplexRuleExecutor();
134 | executor.setObject(object);
135 | ItemExecutedResult result = null;
136 | //如果是重复执行.
137 | do{
138 | result = executor.doCheck(item);
139 | if(result == null) break;
140 |
141 | seq = this.writeExecutedLog(object,item, result);
142 | if(result.getResult().compare(ret_Result.getResult()) > 0 ){
143 | ret_Result.setResult(result.getResult());
144 | ret_Result.setResult_desc(result.getRemark());
145 | }
146 | ret_Result.setSequence(seq);
147 | if(!result.canBeContinue()){
148 | break;
149 | }
150 |
151 | }while(result != null && result.shouldLoop());
152 |
153 | if(!result.canBeContinue()){
154 | break;
155 | }
156 |
157 |
158 | }else{
159 |
160 | String className= item.getExeClass();
161 |
162 | Class auditClass = null;
163 | AbstractRuleItem auditInstance = null;
164 |
165 | if(StringUtils.isNotEmpty(className)){
166 | try {
167 | //auditInstance = CglibCaller.newInstance(AbstractRuleItem.class);
168 |
169 | auditClass = (Class) Class.forName(className);
170 | if(null != auditClass){
171 | auditInstance = auditClass.newInstance();
172 | }
173 | } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
174 | throw new RuleEngineException(e.getMessage());
175 | }
176 | }
177 |
178 | if(null == auditInstance){
179 | auditInstance = new DefaultRuleExecutor();
180 | }
181 |
182 | //直接地调用doCheck的函数。
183 | auditInstance.setObject(object);
184 |
185 | ItemExecutedResult result = null;
186 | //如果是重复执行.
187 | do{
188 |
189 | //CglibCaller caller = new CglibCaller();
190 |
191 | //caller.intercept(caller, method, args, caller);
192 |
193 | result = auditInstance.doCheck(item);
194 | if(result == null){
195 | break;
196 | }
197 | seq = this.writeExecutedLog(object,item, result);
198 | if(result.getResult().compare(ret_Result.getResult()) > 0 ){
199 | ret_Result.setResult(result.getResult());
200 | ret_Result.setResult_desc(result.getRemark());
201 | }
202 | ret_Result.setSequence(seq);
203 |
204 | if(!result.canBeContinue()){
205 | break;
206 | }
207 | } while(result != null && result.shouldLoop());
208 |
209 | if(!result.canBeContinue()){
210 | break;
211 | }
212 |
213 | }
214 | }
215 |
216 | this.afterExecuted(ret_Result);
217 |
218 | return ret_Result;
219 | }
220 |
221 | protected void afterExecuted(EngineRunResult result){
222 |
223 | }
224 |
225 | protected String writeExecutedLog(Object object, RuleItem item , ItemExecutedResult result ) throws RuleEngineException{
226 |
227 |
228 | if(StringUtils.isEmpty(seq)){
229 | seq = String.valueOf(System.currentTimeMillis());
230 | seq = seq + String.valueOf(new Random(1000).nextInt());
231 | }
232 |
233 | try {
234 | ResultLogFactory.getInstance().writeLog(object, item, result);
235 | } catch (RuleEngineException e) {
236 | log.debug("write log error.");
237 | throw e;
238 | }
239 |
240 | return seq;
241 | }
242 |
243 |
244 | /**
245 | * 这是一个例子,通过Student类来说明规则引擎的实际应用。Student定义在TL_STUDENT中(参考数据库)
246 | * 在本例子中,我们构建了一组student对象, 同时配置一个简单的规则,如果学生年龄>7岁,或者学生年龄<3岁,则认为不可以读幼儿园, 这个时候在显示出来。
247 | * 规则配置文件时studentrule.xml,这个文件需要在ruleEngine.properties中配置。
248 | * @param args
249 | */
250 | public static void main(String[] args){
251 |
252 | EngineService service = new EngineService();
253 |
254 | try {
255 |
256 | Random rand = new Random (1);
257 |
258 | for(int id =2 ; id <=4; id++){
259 | // Student st = new Student();
260 | // st.setAge(rand.nextInt(10));
261 | // st.name = "tom";
262 | // st.sex = rand.nextInt(1);
263 |
264 | EngineRunResult result = service.start(id);
265 |
266 | System.out.println(result.getResult().getName());
267 | if(result.getResult() == RESULT.PASSED) {
268 | service.log.error("学生{} 不能入读本幼儿园,年龄不符合要求。",id);
269 | }else {
270 | service.log.info("学生{} 没有年龄不符合条件的情况。",id);
271 | }
272 | }
273 | } catch (RuleEngineException e) {
274 |
275 | e.printStackTrace();
276 | }
277 |
278 | }
279 | }
280 |
281 |
282 |
283 |
284 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/AbstractCommand.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component;
16 |
17 | import tech.kiwa.engine.entity.ItemExecutedResult;
18 | import tech.kiwa.engine.entity.RuleItem;
19 | /**
20 | * 命令接口,如果需要自定义Rule地执行部分,那么该部分必须从这个父类继承。
21 | * @author Hale.Li
22 | * @since 2018-01-28
23 | * @version 0.1
24 | */
25 | public abstract class AbstractCommand {
26 |
27 | public abstract void execute(RuleItem item, ItemExecutedResult result);
28 |
29 | public abstract void SetObject(Object obj);
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/AbstractComparisonOperator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component;
16 |
17 | import tech.kiwa.engine.exception.RuleEngineException;
18 | import tech.kiwa.engine.framework.Component;
19 | import tech.kiwa.engine.framework.OperatorFactory;
20 |
21 | /**
22 | * @author Hale.Li
23 | * @since 2018-01-28
24 | * @version 0.1
25 | */
26 | public abstract class AbstractComparisonOperator implements Component {
27 |
28 | private String comparisonCode ;
29 |
30 | // auto register.
31 | public AbstractComparisonOperator( String comparison_code) throws Exception{
32 |
33 |
34 | comparisonCode = comparison_code;
35 | this.register();
36 |
37 | }
38 |
39 | public void register() throws RuleEngineException{
40 |
41 | OperatorFactory optMgr = OperatorFactory.getInstance();
42 |
43 | if(OperatorFactory.OPR_CODE.isReserved(comparisonCode) ){
44 | throw new RuleEngineException("cannot use reserved logic key.");
45 | }
46 |
47 | optMgr.acceptRegister(this);
48 | }
49 |
50 | public abstract boolean run(String subject, String baseline);
51 |
52 | public String getComparisonCode(){
53 | return comparisonCode;
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/AbstractResultLogRecorder.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component;
16 |
17 | import tech.kiwa.engine.entity.ItemExecutedResult;
18 | import tech.kiwa.engine.entity.RuleItem;
19 | import tech.kiwa.engine.exception.RuleEngineException;
20 | import tech.kiwa.engine.framework.Component;
21 | import tech.kiwa.engine.framework.ResultLogFactory;
22 |
23 | /**
24 | * @author Hale.Li
25 | * @since 2018-01-28
26 | * @version 0.1
27 | */
28 | public abstract class AbstractResultLogRecorder implements Component {
29 |
30 | public AbstractResultLogRecorder( ) {
31 | }
32 |
33 | // explicit register.
34 | public void register() throws RuleEngineException{
35 |
36 | ResultLogFactory optMgr = ResultLogFactory.getInstance();
37 | optMgr.acceptRegister(this);
38 | }
39 |
40 | public abstract boolean writeLog(Object object, RuleItem item , ItemExecutedResult result );
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/AbstractRuleItem.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component;
16 |
17 | import java.math.BigDecimal;
18 | import java.util.Map;
19 | import java.util.Set;
20 |
21 | import org.springframework.beans.BeansException;
22 |
23 | import tech.kiwa.engine.entity.ItemExecutedResult;
24 | import tech.kiwa.engine.entity.RuleItem;
25 | import tech.kiwa.engine.exception.EmptyResultSetException;
26 | import tech.kiwa.engine.exception.RuleEngineException;
27 | import tech.kiwa.engine.framework.OperatorFactory;
28 | import tech.kiwa.engine.utility.SpringContextHelper;
29 |
30 | /**
31 | * @author Hale.Li
32 | * @since 2018-01-28
33 | * @version 0.1
34 | */
35 | public abstract class AbstractRuleItem {
36 |
37 | protected Object object;
38 |
39 | public void setObject(Object object) {
40 | this.object = object;
41 | }
42 |
43 | /**
44 | * 获取SpringMVC中的Service对象,如果未使用SpringMVC,则返回null.
45 | *
46 | * @param seriveName
47 | * Service名称,
48 | * @return 返回的Serivce对象。
49 | */
50 | protected Object getService(String seriveName) {
51 |
52 | Object objRet = null;
53 |
54 | try {
55 | objRet = SpringContextHelper.getBean(seriveName);
56 | } catch (BeansException e) {
57 |
58 | }
59 |
60 | return objRet;
61 | }
62 |
63 | /**
64 | * 获取SpringMVC中的Service对象。 如果未使用SpringMVC,则返回null.
65 | *
66 | * @param 参数类型的模板类
67 | * @param requiredType
68 | * Serivce的类型,即具体的类。
69 | * @return 返回的Serivce对象。
70 | */
71 | protected T getService(Class requiredType) {
72 |
73 | T objRet = null;
74 | try {
75 | objRet = SpringContextHelper.getBean(requiredType);
76 | } catch (BeansException e) {
77 |
78 | }
79 | return objRet;
80 |
81 | }
82 |
83 | public abstract ItemExecutedResult doCheck(RuleItem item) throws RuleEngineException;
84 |
85 | /**
86 | * analyze the data of when condition.
87 | *
88 | * @param resultSet
89 | * 返回的结果集,从数据库读出来的
90 | * @param item
91 | * 规则定义体
92 | * @return 运行是成功还是失败 true or false.
93 | * @throws EmptyResultSetException
94 | * 结果集是空时的的返回.
95 | * @throws RuleEngineException
96 | * 其他的异常
97 | */
98 | protected boolean analyze(Map resultSet, RuleItem item)
99 | throws EmptyResultSetException, RuleEngineException {
100 |
101 | String retValue = null;
102 |
103 | //
104 | if (resultSet.containsKey("cnt")) {
105 |
106 | retValue = resultSet.get("cnt").toString();
107 |
108 | } else if (resultSet.size() == 1) {
109 |
110 | Set keySet = (Set) resultSet.keySet();
111 | for (String key : keySet) {
112 |
113 | if (null == resultSet.get(key)) {
114 | retValue = null;
115 | } else if (resultSet.get(key) instanceof String) {
116 | retValue = (String) resultSet.get(key);
117 | } else {
118 | retValue = resultSet.get(key).toString();
119 | }
120 |
121 | }
122 |
123 | } else if (resultSet.size() > 1) {
124 | // read the first data.
125 | Set keySet = (Set) resultSet.keySet();
126 | for (String key : keySet) {
127 |
128 | if (null == resultSet.get(key)) {
129 | retValue = null;
130 | } else if (resultSet.get(key) instanceof String) {
131 | retValue = (String) resultSet.get(key);
132 | } else {
133 | retValue = resultSet.get(key).toString();
134 | }
135 | break;
136 | }
137 |
138 | // 如果数据返回为空,那么默认为审核通过
139 | } else if (resultSet.isEmpty()) {
140 |
141 | throw new EmptyResultSetException("resultset is empty.");
142 | // return true;
143 | } else {
144 | throw new RuleEngineException("unknow resultset.");
145 | }
146 |
147 | boolean bRet = false;
148 |
149 | // try {
150 | bRet = comparisonOperate(retValue, item.getComparisonCode(), item.getBaseline());
151 | // } catch (RuleEngineException e) {
152 | // throw e;
153 | // }
154 |
155 | return bRet;
156 | }
157 |
158 | /**
159 | * 比较运算操作,将执行的结果和RuleItem中的baseline作比较。
160 | *
161 | * @param subject
162 | * 比较对象(运行结果)
163 | * @param comparisonCode
164 | * 比较操作符号,在OperationFactory中定义。
165 | * @param baseline
166 | * 比较基线,用于比较的对象。
167 | * @return 根据ComparisonCode运行的结果。 true or flase。
168 | * @throws RuleEngineException
169 | * 参数不合法,或者比较操作符不合法。
170 | */
171 | public static boolean comparisonOperate(String subject, String comparisonCode, String baseline)
172 | throws RuleEngineException {
173 |
174 | boolean bRet = false;
175 |
176 | if (null == subject || null == baseline || null == comparisonCode) {
177 | throw new RuleEngineException("null pointer error of subject or baseline or comparison code.");
178 | }
179 |
180 | BigDecimal bdSubject = null;
181 | BigDecimal object = null;
182 |
183 | switch (comparisonCode) {
184 |
185 | case OperatorFactory.OPR_CODE.EQUAL:
186 | try {
187 | bdSubject = new BigDecimal(subject);
188 | object = new BigDecimal(baseline);
189 | bRet = (bdSubject.compareTo(object) == 0);
190 | } catch (Exception e) {
191 | bRet = subject.equals(baseline);
192 | }
193 | break;
194 | case OperatorFactory.OPR_CODE.GREATER:
195 | try {
196 | bdSubject = new BigDecimal(subject);
197 | object = new BigDecimal(baseline);
198 | bRet = (bdSubject.compareTo(object) > 0);
199 | } catch (Exception e1) {
200 | bRet = (subject.compareTo(baseline) > 0);
201 | }
202 | break;
203 | case OperatorFactory.OPR_CODE.LESS:
204 | try {
205 | bdSubject = new BigDecimal(subject);
206 | object = new BigDecimal(baseline);
207 | bRet = (bdSubject.compareTo(object) < 0);
208 | } catch (Exception e1) {
209 | bRet = (subject.compareTo(baseline) < 0);
210 | }
211 | break;
212 | case OperatorFactory.OPR_CODE.NOT_EQUAL:
213 | try {
214 | bdSubject = new BigDecimal(subject);
215 | object = new BigDecimal(baseline);
216 | bRet = (bdSubject.compareTo(object) != 0);
217 | } catch (Exception e) {
218 | bRet = !subject.equals(baseline);
219 | }
220 | break;
221 | case OperatorFactory.OPR_CODE.GREATER_EQUAL:
222 | try {
223 | bdSubject = new BigDecimal(subject);
224 | object = new BigDecimal(baseline);
225 | bRet = (bdSubject.compareTo(object) >= 0);
226 | } catch (Exception e) {
227 | bRet = (subject.compareTo(baseline) >= 0);
228 | }
229 | break;
230 | case OperatorFactory.OPR_CODE.LESS_EQUAL:
231 | try {
232 | bdSubject = new BigDecimal(subject);
233 | object = new BigDecimal(baseline);
234 | bRet = (bdSubject.compareTo(object) <= 0);
235 | } catch (Exception e) {
236 | bRet = (subject.compareTo(baseline) <= 0);
237 | }
238 | break;
239 | case OperatorFactory.OPR_CODE.INCLUDE:
240 | bRet = subject.contains(baseline);
241 | break;
242 | case OperatorFactory.OPR_CODE.NOT_INCLUDE:
243 | bRet = !subject.contains(baseline);
244 | break;
245 | case OperatorFactory.OPR_CODE.INCLUDED_BY:
246 | bRet = baseline.contains(subject);
247 | break;
248 | case OperatorFactory.OPR_CODE.NOT_INCLUDED_BY:
249 | bRet = !baseline.contains(subject);
250 | break;
251 | case OperatorFactory.OPR_CODE.EQUAL_IGNORE_CASE:
252 | bRet = subject.equalsIgnoreCase(baseline);
253 | break;
254 | case OperatorFactory.OPR_CODE.NOT_EQUAL_IGNORE_CASE:
255 | bRet = !subject.equalsIgnoreCase(baseline);
256 | break;
257 | case OperatorFactory.OPR_CODE.MATCH:
258 | bRet = subject.matches(baseline);
259 | break;
260 | case OperatorFactory.OPR_CODE.UNMATCH:
261 | bRet = !subject.matches(baseline);
262 | break;
263 | default:
264 | bRet = extendComparisonOperate(subject, comparisonCode, baseline);
265 | break;
266 | }
267 |
268 | return bRet;
269 | }
270 |
271 | private static boolean extendComparisonOperate(String subject, String comparisonCode, String baseline)
272 | throws RuleEngineException {
273 |
274 | OperatorFactory optMgr = OperatorFactory.getInstance();
275 | return optMgr.runOperator(subject, comparisonCode, baseline);
276 |
277 | }
278 | }
279 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/AbstractRuleReader.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component;
16 |
17 | import java.util.ArrayList;
18 | import java.util.List;
19 |
20 | import org.apache.commons.lang.StringUtils;
21 | import org.slf4j.Logger;
22 | import org.slf4j.LoggerFactory;
23 |
24 | import tech.kiwa.engine.entity.RESULT;
25 | import tech.kiwa.engine.entity.RuleItem;
26 | import tech.kiwa.engine.exception.RuleEngineException;
27 |
28 |
29 | /**
30 | * @author Hale.Li
31 | * @since 2018-01-28
32 | * @version 0.1
33 | */
34 | public abstract class AbstractRuleReader {
35 |
36 | public abstract List readRuleItemList() throws RuleEngineException ;
37 | public abstract Long getRuleItemCount() throws RuleEngineException;
38 | public abstract RuleItem getRuleItem(String ruleId) throws RuleEngineException;
39 |
40 | protected volatile List ruleItemCache = new ArrayList();
41 |
42 | private static Logger log = LoggerFactory.getLogger(AbstractRuleReader.class);
43 |
44 | /**
45 | * Sort the same level rule item, and filter the items not in the same level.
46 | * @param itemList 排序的对象列表
47 | * @param parentItem 父级规则
48 | * @return 排好序的规则列表
49 | */
50 | public List sortItem(List itemList, String parentItem){
51 |
52 | List retItemList = new ArrayList();
53 | List tempItemList = new ArrayList();
54 |
55 | //同一层级的item,
56 | for(RuleItem item: itemList){
57 | if(StringUtils.isEmpty(parentItem)){
58 |
59 | if(StringUtils.isEmpty(item.getParentItemNo())){
60 | tempItemList.add(item);
61 | }
62 |
63 | }else if(parentItem.equals(item.getParentItemNo())){
64 | tempItemList.add(item);
65 | }
66 | }
67 |
68 | while(!tempItemList.isEmpty()){
69 | /*
70 | int minIndex = queryMiniumPriority(tempItemList);
71 | retItemList.add(tempItemList.get(minIndex));
72 | tempItemList.remove(minIndex);
73 | */
74 | int maxIndex = queryMaxiumPriority(tempItemList);
75 | retItemList.add(tempItemList.get(maxIndex));
76 | tempItemList.remove(maxIndex);
77 | }
78 |
79 | return retItemList;
80 |
81 | }
82 |
83 | /**
84 | * 在规则列表中查找最小的优先级
85 | * @param itemList 查找的对象列表
86 | * @return 最小的优先级
87 | */
88 | @SuppressWarnings("unused")
89 | private int queryMiniumPriority( List itemList){
90 |
91 | int priority = Integer.MAX_VALUE;
92 | int minIndex = Integer.MAX_VALUE;
93 |
94 | for(int iLoop = 0 ;iLoop < itemList.size(); iLoop++){
95 |
96 | try{
97 | int current = Integer.valueOf(itemList.get(iLoop).getPriority());
98 |
99 | if( priority > current ){
100 | priority = current;
101 | minIndex = iLoop;
102 | }
103 | }catch (java.lang.NumberFormatException e){
104 | log.debug(e.getLocalizedMessage());
105 | }
106 | }
107 |
108 | return minIndex;
109 |
110 | }
111 |
112 | /**
113 | * 在规则列表中查找最大的优先级
114 | * @param itemList 查找的对象列表
115 | * @return 最大的优先级
116 | */
117 | private int queryMaxiumPriority( List itemList){
118 |
119 | int priority = Integer.MIN_VALUE;
120 | int minIndex = Integer.MIN_VALUE;
121 |
122 | for(int iLoop = 0 ;iLoop < itemList.size(); iLoop++){
123 |
124 | try{
125 | int current = Integer.valueOf(itemList.get(iLoop).getPriority());
126 |
127 | if( priority < current ){
128 | priority = current;
129 | minIndex = iLoop;
130 | }
131 | }catch (java.lang.NumberFormatException e){
132 | log.debug(e.getLocalizedMessage());
133 | }
134 | }
135 |
136 | return minIndex;
137 |
138 | }
139 |
140 | /**
141 | * 查找同层级的规则列表
142 | * @param itemList 要查找的对象
143 | * @param parentItemNo 父级规则
144 | * @return 同层级的规则列表
145 | */
146 | public List filterItem(List itemList, String parentItemNo){
147 |
148 | List newItemList = new ArrayList();
149 |
150 | for(int iLoop = 0 ;iLoop < itemList.size(); iLoop++){
151 |
152 | RuleItem item= itemList.get(iLoop);
153 | if(StringUtils.isEmpty(parentItemNo)){
154 | if(StringUtils.isEmpty(item.getParentItemNo())){
155 | newItemList.add(item);
156 | }
157 | }else{
158 | if(parentItemNo.equalsIgnoreCase(item.getParentItemNo())){
159 | newItemList.add(item);
160 | }
161 | }
162 | }
163 |
164 | return newItemList;
165 |
166 | }
167 |
168 | /**
169 | * 检查规则的格式是否正确
170 | * @param item 规则定义体
171 | * @return true -- 合法 false -- 不合法
172 | */
173 | public boolean preCompile(RuleItem item){
174 |
175 | boolean bRet = true;
176 | if(StringUtils.isEmpty(item.getItemNo())){
177 | log.debug("ruleId cannot be empty.");
178 | bRet = false;
179 | }
180 |
181 | // single normal item.
182 | if(StringUtils.isEmpty(item.getParentItemNo()) && StringUtils.isEmpty(item.getGroupExpress())){
183 |
184 | if(StringUtils.isEmpty(item.getPriority())){
185 | log.debug("priority cannot be empty and must be numberic if it's free-running rule. ruleid ={}" , item.getItemNo());
186 | bRet = false;
187 | }
188 |
189 | if(!StringUtils.isNumeric(item.getPriority())){
190 | log.debug("priority cannot be empty and must be numberic if it's free-running rule. ruleid ={}" , item.getItemNo());
191 | bRet = false;
192 | }
193 |
194 | if(!StringUtils.isNumeric(item.getContinueFlag())){
195 | log.debug("continue flag cannot be empty and must be numberic if it's free-running rule. ruleid ={}" , item.getItemNo());
196 | bRet = false;
197 | }
198 |
199 | if(!StringUtils.isNumeric(item.getResult())){
200 | RESULT result = RESULT.EMPTY ;
201 | if(!result.parse(item.getResult())){
202 | log.debug("result cannot be empty and must be numberic if it's free-running rule. ruleid ={}" , item.getItemNo());
203 | bRet = false;
204 | }
205 | }
206 |
207 | if(StringUtils.isEmpty(item.getExeClass()) && StringUtils.isEmpty(item.getExeSql())){
208 | log.debug("either exe_class or exe_sql must be inputted. ruleid ={}" , item.getItemNo());
209 | bRet = false;
210 | }
211 |
212 | if(StringUtils.isEmpty(item.getBaseline())){
213 | log.debug("baseline must be inputted. ruleid ={}" , item.getItemNo());
214 | bRet = false;
215 | }
216 |
217 | if(StringUtils.isEmpty(item.getComparisonCode())){
218 | log.debug("comparison code must be inputted. ruleid ={}" , item.getItemNo());
219 | bRet = false;
220 | }
221 |
222 | if(StringUtils.isNotEmpty(item.getExeSql())){
223 | String sql = item.getExeSql();
224 | if(sql.contains("?")){
225 | if(StringUtils.isEmpty(item.getParamName())){
226 |
227 | log.debug("param name must be inputted since your exe_sql has parameters. ruleid ={}" , item.getItemNo());
228 | bRet = false;
229 | }
230 | }
231 | }
232 | }
233 | // group check, parent group.
234 | if( StringUtils.isNotEmpty(item.getGroupExpress()) ){
235 |
236 | if(StringUtils.isEmpty(item.getPriority())){
237 | log.debug("priority cannot be empty and must be numberic if it's free-running rule. ruleid ={}" , item.getItemNo());
238 | bRet = false;
239 | }
240 |
241 | if(!StringUtils.isNumeric(item.getPriority())){
242 | log.debug("priority cannot be empty and must be numberic if it's free-running rule. ruleid ={}" , item.getItemNo());
243 | bRet = false;
244 | }
245 |
246 | if(!StringUtils.isNumeric(item.getContinueFlag())){
247 | log.debug("continue flag cannot be empty and must be numberic if it's free-running rule. ruleid ={}" , item.getItemNo());
248 | bRet = false;
249 | }
250 |
251 | if(!StringUtils.isNumeric(item.getResult())){
252 | RESULT result = RESULT.EMPTY ;
253 | if(!result.parse(item.getResult())){
254 | log.debug("result cannot be empty and must be numberic if it's free-running rule. ruleid ={}" , item.getItemNo());
255 | bRet = false;
256 | }
257 | }
258 |
259 | }
260 |
261 | //sub item check, simple rule , without complex express.
262 | if(StringUtils.isNotEmpty(item.getParentItemNo())){
263 |
264 | if(StringUtils.isEmpty(item.getExeClass()) && StringUtils.isEmpty(item.getExeSql())){
265 | log.debug("either java_class or exe_sql must be inputted. ruleid ={}" , item.getItemNo());
266 | bRet = false;
267 | }
268 |
269 | if(StringUtils.isEmpty(item.getBaseline())){
270 | log.debug("baseline must be inputted. ruleid ={}" , item.getItemNo());
271 | bRet = false;
272 | }
273 |
274 | if(StringUtils.isEmpty(item.getComparisonCode())){
275 | log.debug("comparison code must be inputted. ruleid ={}" , item.getItemNo());
276 | bRet = false;
277 | }
278 |
279 | if(StringUtils.isNotEmpty(item.getExeSql())){
280 | String sql = item.getExeSql();
281 | if(sql.contains("?")){
282 | if(StringUtils.isEmpty(item.getParamName())){
283 |
284 | log.debug("param name must be inputted since your exe_sql has parameters. ruleid ={}" , item.getItemNo());
285 | bRet = false;
286 | }
287 | }
288 | }
289 | }
290 |
291 | return bRet;
292 | }
293 |
294 | /**
295 | * 缓存清除的接口。
296 | */
297 | public void clearRuleItemCache(){
298 |
299 | synchronized(ruleItemCache){
300 | ruleItemCache.clear();
301 | }
302 |
303 | }
304 |
305 | public void updateRuleItem(RuleItem item){
306 |
307 | for(int iLoop =0; iLoop < ruleItemCache.size(); iLoop++){
308 |
309 | RuleItem element = ruleItemCache.get(iLoop);
310 |
311 | if(element.getItemNo().equalsIgnoreCase(item.getItemNo())){
312 | synchronized(ruleItemCache){
313 | ruleItemCache.set(iLoop, item);
314 | }
315 | }
316 | }
317 | }
318 | }
319 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/DeclareCreator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | import java.util.HashMap;
18 | import java.util.Map;
19 | import java.util.Set;
20 |
21 | import com.alibaba.druid.util.StringUtils;
22 |
23 | import tech.kiwa.engine.component.drools.ImportCreator;
24 | /**
25 | * @author Hale.Li
26 | * @since 2018-01-28
27 | * @version 0.1
28 | */
29 | public class DeclareCreator implements DroolsPartsCreator {
30 |
31 | private String name;
32 | private Map attributes;
33 |
34 | public String getName() {
35 | return name;
36 | }
37 |
38 | public Map getAttributes() {
39 | return attributes;
40 | }
41 |
42 | private DroolsBuilder builder = null;
43 |
44 | private DeclareCreator(){
45 |
46 | }
47 | public static DeclareCreator create(String content, DroolsBuilder builder){
48 |
49 |
50 |
51 | if(StringUtils.isEmpty(content)){
52 | return null;
53 | }
54 |
55 | if(!content.startsWith("declare")){
56 | return null;
57 | }
58 |
59 | content = content.trim();
60 |
61 | DeclareCreator creator = new DeclareCreator();
62 | creator.builder = builder;
63 |
64 | String[] lines = content.split("\\n|\\r");
65 | String title = lines[0].trim();
66 |
67 | String[] sections = title.split("\\s+|\\t|\\(|,|\\)");
68 |
69 |
70 | if(sections.length >= 2){
71 |
72 | creator.name = sections[1];
73 |
74 | creator.attributes = new HashMap();
75 | for(int iLoop =1 ; iLoop < lines.length -1 ; iLoop++){
76 |
77 | String line = lines[iLoop];
78 | if(StringUtils.isEmpty(line)){
79 | continue;
80 | }
81 | line = line.trim();
82 | if(line.endsWith(";")){
83 | line = line.substring(0, line.length()-1);
84 | }
85 | sections = line.split(":");
86 | //ASSERT sections.length = 2;
87 | if(creator.attributes == null){
88 | creator.attributes = new HashMap();
89 | }
90 | creator.attributes.put(sections[0].trim(), sections[1].trim());
91 | }
92 | }
93 |
94 | return creator;
95 |
96 | }
97 |
98 | public String toJavaString(){
99 |
100 | StringBuffer javaBuffer = new StringBuffer();
101 | javaBuffer.append(builder.getPackage().toJavaString());
102 | for(ImportCreator impt : builder.getImportList()){
103 | javaBuffer.append(impt.toJavaString());
104 | }
105 |
106 | javaBuffer.append("import tech.kiwa.engine.component.drools.DeclareInterface;\n");
107 |
108 | javaBuffer.append("\n");
109 | javaBuffer.append("public class ").append(name);
110 | javaBuffer.append(" implements DeclareInterface");
111 | javaBuffer.append(" {").append("\n");
112 | javaBuffer.append("\n");
113 |
114 | for(GlobalCreator global : builder.getGlobalList()){
115 | javaBuffer.append(global.toJavaString());
116 | }
117 | javaBuffer.append("\n");
118 |
119 | Set nameSet = attributes.keySet();
120 | for(String name : nameSet){
121 | String type = attributes.get(name);
122 | javaBuffer.append("public ");
123 | javaBuffer.append(type);
124 | javaBuffer.append(" ");
125 | javaBuffer.append(name);
126 | javaBuffer.append(";\n");
127 | }
128 | javaBuffer.append("\n");
129 | //Implement the getValue function.
130 | javaBuffer.append(" public Object getValue(String name){ \n");
131 | javaBuffer.append("\n");
132 | javaBuffer.append(" Object value = null;\n");
133 | for(String name : nameSet){
134 | javaBuffer.append(" if(name.equals(\""+name+"\")){\n");
135 | javaBuffer.append(" value = this."+ name +";\n");
136 | javaBuffer.append(" }\n");
137 | }
138 |
139 | javaBuffer.append("\n");
140 | javaBuffer.append(" return value;\n");
141 |
142 | javaBuffer.append(" }");
143 | javaBuffer.append("\n");
144 |
145 | //Implement the setValue function.
146 | javaBuffer.append(" public void setValue(String name, Object value){ \n");
147 | javaBuffer.append("\n");
148 | for(String name : nameSet){
149 | String type = attributes.get(name);
150 | javaBuffer.append(" if(name.equals(\""+name+"\")){\n");
151 | javaBuffer.append(" this."+ name +" = ("+ type +") value;\n");
152 | javaBuffer.append(" }\n");
153 | }
154 |
155 | javaBuffer.append("\n");
156 | javaBuffer.append(" return ;\n");
157 |
158 | javaBuffer.append(" }");
159 | javaBuffer.append("\n");
160 |
161 | javaBuffer.append("}");
162 |
163 | return javaBuffer.toString();
164 | }
165 |
166 | public DeclareInterface createObject(){
167 |
168 | DeclareInterface declare = (DeclareInterface) builder.createObject(this.name, this.toJavaString());
169 |
170 | return declare;
171 | }
172 |
173 |
174 | }
175 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/DeclareInterface.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | /**
18 | * @author Hale.Li
19 | * @since 2018-01-28
20 | * @version 0.1
21 | */
22 | public interface DeclareInterface extends DroolsPartsObject {
23 |
24 | public Object getValue(String name);
25 |
26 | public void setValue(String name, Object value);
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/DroolsBuilder.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | import java.io.IOException;
18 | import java.util.ArrayList;
19 | import java.util.List;
20 | import java.util.Map;
21 |
22 | import org.slf4j.Logger;
23 | import org.slf4j.LoggerFactory;
24 |
25 | import tech.kiwa.engine.entity.RuleItem;
26 | import tech.kiwa.engine.utility.JavaStringCompiler;
27 | /**
28 | * @author Hale.Li
29 | * @since 2018-01-28
30 | * @version 0.1
31 | */
32 | public class DroolsBuilder {
33 |
34 |
35 | //private static DroolsBuilder instance = new DroolsBuilder();
36 |
37 | public DroolsBuilder(){
38 |
39 | }
40 |
41 | //public static DroolsBuilder getInstance(){
42 | // return instance;
43 | //}
44 |
45 | private Logger log = LoggerFactory.getLogger(DroolsBuilder.class);
46 |
47 | private List functionList = new ArrayList();
48 | private List globalList = new ArrayList();
49 | private List importList = new ArrayList();
50 | private List queryList = new ArrayList();
51 | private List ruleList = new ArrayList();
52 | private List declareList = new ArrayList();
53 |
54 | //private ClassFileManager> fileManager = null;// new ClassFileManager(compiler.getStandardFileManager(null, null, null));
55 | //private List fileList = new ArrayList();
56 | private JavaStringCompiler compiler = new JavaStringCompiler();
57 |
58 | private PackageCreator pack = null;
59 |
60 | public List getImportList(){
61 | return importList;
62 | }
63 |
64 | public PackageCreator getPackage(){
65 | return pack;
66 | }
67 |
68 | public List getFunctionList() {
69 | return functionList;
70 | }
71 |
72 | public List getGlobalList() {
73 | return globalList;
74 | }
75 |
76 | public List getQueryList() {
77 | return queryList;
78 | }
79 |
80 | public List getRuleList() {
81 | return ruleList;
82 | }
83 |
84 | public List getDeclareList() {
85 | return declareList;
86 | }
87 |
88 |
89 |
90 | public void build(List phases) {
91 |
92 | for(String item : phases){
93 |
94 | item = item.trim();
95 | if(item.startsWith("rule")){
96 | ruleList.add(RuleCreator.create(item, this));
97 |
98 | }else if(item.startsWith("function")){
99 |
100 | functionList.add(FunctionCreator.create(item, this));
101 |
102 | }else if(item.startsWith("global")){
103 |
104 | this.globalList.add(GlobalCreator.create(item, this));
105 |
106 | } else if(item.startsWith("import")){
107 |
108 | this.importList.add(ImportCreator.create(item, this));
109 |
110 | }else if(item.startsWith("query")){
111 |
112 | this.queryList.add(QueryCreator.create(item, this));
113 |
114 | }else if(item.startsWith("package")){
115 |
116 | this.pack = PackageCreator.create(item, this);
117 |
118 | }else if(item.startsWith("declare")){
119 | this.declareList.add(DeclareCreator.create(item, this));
120 | }
121 |
122 | }
123 |
124 | }
125 |
126 | // public ClassFileManager> getFileManager(){
127 | // return this.fileManager;
128 | // }
129 |
130 | public List getRuleItemList(){
131 |
132 | List retList = new ArrayList();
133 | for(RuleCreator creator: ruleList){
134 | retList.add(creator.getItem());
135 | }
136 |
137 | return retList;
138 | }
139 | /*
140 | public Class> queryClass(String className) throws ClassNotFoundException{
141 |
142 | return compiler.queryLoadedClass(className);
143 |
144 | //return compiler.loadClass(className, classBytes);
145 | }
146 | */
147 | private boolean compiled = false;
148 |
149 | public boolean compile(){
150 |
151 | if(compiled){
152 | return compiled;
153 | }
154 |
155 | for (DeclareCreator declare : declareList){
156 |
157 | // 生成源代码的JavaFileObject
158 | //SimpleJavaFileObject fileObject = new JavaSourceFromString(declare.getName(), declare.toJavaString());
159 | //fileList.add(fileObject);
160 | try {
161 |
162 | //String clsName = this.getPackage().getName() + "." + declare.getName();
163 | String fileName = declare.getName() + ".java";
164 | compiler.compile(fileName, declare.toJavaString());
165 | } catch (IOException e) {
166 |
167 | }
168 |
169 | }
170 | if(!functionList.isEmpty()){
171 | //String clsName = this.getPackage().getName() + ".DroolsFunctions" ;
172 | String fileName = "DroolsFunctions.java";
173 | //SimpleJavaFileObject fileObject = new JavaSourceFromString(clsName, functionList.get(0).toJavaString());
174 | //fileList.add(fileObject);
175 | try {
176 | compiler.compile(fileName, functionList.get(0).toJavaString());
177 | } catch (IOException e) {
178 | // TODO Auto-generated catch block
179 | log.debug(e.getMessage());
180 | e.printStackTrace();
181 | }
182 | }
183 |
184 | return compiled;
185 |
186 |
187 | }
188 |
189 |
190 | @SuppressWarnings({ "unchecked" })
191 | public DroolsPartsObject createObject(String className, String javaContent) {
192 |
193 | try {
194 | String fileName = "";
195 | int pos = className.lastIndexOf('.');
196 | if(pos > 0){
197 | fileName = className.substring(pos+1) + ".java";
198 | }else{
199 | fileName = className + ".java";
200 | }
201 |
202 | Map clsMap = compiler.compile(fileName, javaContent);
203 |
204 | Class cls = (Class) compiler.loadClass(className, clsMap);
205 | DroolsPartsObject obj = (DroolsPartsObject) cls.newInstance();
206 |
207 | return obj;
208 | } catch (ClassNotFoundException | IOException | InstantiationException | IllegalAccessException e) {
209 | log.debug(e.getMessage());
210 | e.printStackTrace();
211 | }
212 |
213 | return null;
214 |
215 | }
216 |
217 | }
218 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/DroolsPartsCreator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 | /**
17 | * @author Hale.Li
18 | * @since 2018-01-28
19 | * @version 0.1
20 | */
21 | public interface DroolsPartsCreator {
22 |
23 | public String toJavaString();
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/DroolsPartsObject.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 | /**
17 | * @author Hale.Li
18 | * @since 2018-01-28
19 | * @version 0.1
20 | */
21 | public interface DroolsPartsObject {
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/FunctionCreator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | import java.util.ArrayList;
18 | import java.util.HashMap;
19 | import java.util.List;
20 | import java.util.Map;
21 |
22 | import com.alibaba.druid.util.StringUtils;
23 | /**
24 | * @author Hale.Li
25 | * @since 2018-01-28
26 | * @version 0.1
27 | */
28 | public class FunctionCreator implements DroolsPartsCreator {
29 |
30 | private String functionName;
31 | private String reference;
32 | private Map params = new HashMap();
33 | private List paramTypes = new ArrayList();
34 | private List paramNames = new ArrayList();
35 |
36 | private String content;
37 |
38 | public String getFunctionName() {
39 | return functionName;
40 | }
41 |
42 | public String getReference() {
43 | return reference;
44 | }
45 |
46 | public Map getParams() {
47 | return params;
48 | }
49 |
50 | public String getContent() {
51 | return content;
52 | }
53 |
54 | @Override
55 | public String toJavaString() {
56 |
57 | StringBuffer javaBuffer = new StringBuffer();
58 |
59 |
60 | javaBuffer.append(builder.getPackage().toJavaString());
61 | javaBuffer.append("\n");
62 |
63 | for(ImportCreator impt : builder.getImportList()){
64 | javaBuffer.append(impt.toJavaString());
65 | }
66 |
67 | for(DeclareCreator decl : builder.getDeclareList()){
68 | javaBuffer.append("import " + builder.getPackage().getName() +".");
69 | javaBuffer.append(decl.getName());
70 | javaBuffer.append(";\n");
71 | }
72 |
73 | javaBuffer.append("\n");
74 | javaBuffer.append("public class ").append("DroolsFunctions");
75 | javaBuffer.append(" {").append("\n");
76 | javaBuffer.append("\n");
77 |
78 | for(FunctionCreator fun: builder.getFunctionList()){
79 |
80 | javaBuffer.append(" public ");
81 | javaBuffer.append(fun.reference);
82 | javaBuffer.append(" ");
83 | javaBuffer.append(fun.functionName);
84 | javaBuffer.append(" ");
85 | javaBuffer.append(" (");
86 |
87 | //Set nameSet = fun.params.keySet();
88 | for(int iLoop =0; iLoop < fun.paramNames.size(); iLoop++){
89 | String name = fun.paramNames.get(iLoop);
90 | String type = fun.paramTypes.get(iLoop);
91 | javaBuffer.append( type );
92 | javaBuffer.append(" ");
93 | javaBuffer.append(name);
94 | javaBuffer.append(" , ");
95 | }
96 | if(!fun.paramNames.isEmpty()){
97 | int pos = javaBuffer.lastIndexOf(",");
98 | javaBuffer.deleteCharAt(pos);
99 | }
100 |
101 | javaBuffer.append(")");
102 |
103 | javaBuffer.append(fun.content);
104 | javaBuffer.append("\n");
105 | }
106 |
107 | javaBuffer.append("\n");
108 |
109 | javaBuffer.append("}");
110 | return javaBuffer.toString();
111 |
112 | }
113 |
114 | private FunctionCreator(){
115 |
116 | }
117 |
118 | private DroolsBuilder builder = null;
119 |
120 | public static FunctionCreator create(String content,DroolsBuilder builder ){
121 |
122 | if(StringUtils.isEmpty(content)){
123 | return null;
124 | }
125 |
126 | if(!content.startsWith("function")){
127 | return null;
128 | }
129 |
130 | content = content.trim();
131 |
132 | FunctionCreator creator = new FunctionCreator();
133 | creator.builder = builder;
134 |
135 | String[] lines = content.split("\\n|\\r");
136 | String title = lines[0].trim();
137 |
138 | String[] sections = title.split("\\s+|\\t|\\(|,|\\)\\{");
139 |
140 | if(sections.length >= 3){
141 |
142 | creator.reference = sections[1];
143 | creator.functionName = sections[2];
144 |
145 | if(title.endsWith("{")){
146 | title = title.substring(0, title.length()-1);
147 | }
148 |
149 | if(title.endsWith(")")){
150 |
151 | String type = null, name =null;
152 | for(int iLoop = 3; iLoop < sections.length; iLoop ++){
153 | if(StringUtils.isEmpty(sections[iLoop])){
154 | continue;
155 | }
156 | if(type == null){
157 | type = sections[iLoop];
158 | }else{
159 | name = sections[iLoop];
160 | }
161 | if(type != null && name != null){
162 | creator.params.put(name,type);
163 | creator.paramTypes.add(type);
164 | creator.paramNames.add(name);
165 | type = null;
166 | name = null;
167 | }
168 | }
169 | }
170 | int pos = content.indexOf('{');
171 | creator.content = content.substring(pos);
172 | }
173 |
174 | return creator;
175 |
176 | }
177 |
178 | }
179 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/GlobalCreator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | import com.alibaba.druid.util.StringUtils;
18 | /**
19 | * @author Hale.Li
20 | * @since 2018-01-28
21 | * @version 0.1
22 | */
23 | public class GlobalCreator implements DroolsPartsCreator {
24 |
25 | private String name = null;
26 | private String reference = null;
27 |
28 | private Object value = null;
29 |
30 |
31 | public Object getValue() {
32 | return value;
33 | }
34 |
35 | public void setValue(Object value) {
36 | this.value = value;
37 | }
38 |
39 | public String getName() {
40 | return name;
41 | }
42 |
43 | public String getReference() {
44 | return reference;
45 | }
46 |
47 | @Override
48 | public String toJavaString() {
49 | StringBuffer sbf = new StringBuffer();
50 | sbf.append("public static ");
51 | sbf.append(reference);
52 | sbf.append(" ");
53 | sbf.append(name);
54 | sbf.append(" ;\n");
55 |
56 | return sbf.toString();
57 | }
58 |
59 | private GlobalCreator(){
60 |
61 | }
62 |
63 | @SuppressWarnings("unused")
64 | private DroolsBuilder builder = null;
65 |
66 | public static GlobalCreator create(String content, DroolsBuilder builder ){
67 |
68 | if(StringUtils.isEmpty(content)){
69 | return null;
70 | }
71 |
72 | if(!content.startsWith("global")){
73 | return null;
74 | }
75 |
76 | content = content.trim();
77 | GlobalCreator creator = new GlobalCreator();
78 | creator.builder = builder;
79 |
80 | String[] sections = content.split("\\s+|\\t|\\n|\\r");
81 | if(sections.length >=3){
82 |
83 | creator.name = sections[2].trim();
84 | creator.reference = sections[1].trim();
85 | }
86 |
87 | return creator;
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/ImportCreator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | import com.alibaba.druid.util.StringUtils;
18 | /**
19 | * @author Hale.Li
20 | * @since 2018-01-28
21 | * @version 0.1
22 | */
23 | public class ImportCreator implements DroolsPartsCreator {
24 |
25 | String fullName;
26 | String simpleName;
27 |
28 | public String getFullName() {
29 | return fullName;
30 | }
31 |
32 |
33 | public String getSimpleName() {
34 | return simpleName;
35 | }
36 |
37 |
38 | public String toString() {
39 | return "import " + fullName + ";\n";
40 | }
41 |
42 |
43 | @Override
44 | public String toJavaString() {
45 | return "import " + fullName + ";\n";
46 | }
47 |
48 | private ImportCreator(){
49 |
50 | }
51 |
52 | @SuppressWarnings("unused")
53 | private DroolsBuilder builder = null;
54 |
55 | public static ImportCreator create(String content, DroolsBuilder builder){
56 |
57 | if(StringUtils.isEmpty(content)){
58 | return null;
59 | }
60 |
61 | if(!content.startsWith("import")){
62 | return null;
63 | }
64 |
65 | content = content.trim();
66 | ImportCreator creator = new ImportCreator();
67 | creator.builder = builder;
68 |
69 | String[] sections = content.split("\\s+|\\t|\\n|\\r");
70 | if(sections.length >=2){
71 | creator.fullName = sections[1].trim();
72 | if(creator.fullName.endsWith(";")){
73 | creator.fullName = creator.fullName.substring(0,creator.fullName.length()-1);
74 | }
75 |
76 | int pos = creator.fullName.lastIndexOf('.');
77 | if(pos > 0){
78 | creator.simpleName = creator.fullName.substring(pos+1);
79 | }
80 | }
81 |
82 | return creator;
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/LocalCreator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | /**
18 | * @author Hale.Li
19 | * @since 2018-01-28
20 | * @version 0.1
21 | */
22 | public class LocalCreator implements DroolsPartsCreator {
23 |
24 |
25 | private String name = null;
26 | private String reference = null;
27 | private Object value = null;
28 |
29 |
30 | public Object getValue() {
31 | return value;
32 | }
33 |
34 | public void setValue(Object value) {
35 | this.value = value;
36 | }
37 |
38 | public String getName() {
39 | return name;
40 | }
41 |
42 | public String getReference() {
43 | return reference;
44 | }
45 |
46 | public void setName(String name) {
47 | if(null != name){
48 | this.name = name.trim();
49 | }
50 | }
51 |
52 | public void setReference(String reference) {
53 | if(null != reference){
54 | this.reference = reference.trim();
55 | }
56 | }
57 |
58 |
59 | @Override
60 | public String toJavaString() {
61 | StringBuffer sbf = new StringBuffer();
62 | sbf.append("private ");
63 | sbf.append(reference);
64 | sbf.append(" ");
65 | sbf.append(name);
66 | sbf.append(" ;\n");
67 |
68 | return sbf.toString();
69 | }
70 |
71 | public LocalCreator(String name, String reference){
72 | if(null != name){
73 | this.name = name.trim();
74 | }
75 | if(null != reference){
76 | this.reference = reference.trim();
77 | }
78 | }
79 |
80 | public LocalCreator(){
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/PackageCreator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | import com.alibaba.druid.util.StringUtils;
18 |
19 | /**
20 | * @author Hale.Li
21 | * @since 2018-01-28
22 | * @version 0.1
23 | */
24 | public class PackageCreator implements DroolsPartsCreator {
25 |
26 | /* (non-Javadoc)
27 | * @see tech.kiwa.engine.component.drools.DroolsPartsCreator#toJavaString()
28 | */
29 |
30 | private String packageName = null;
31 |
32 | @Override
33 | public String toJavaString() {
34 |
35 | StringBuffer javaBuffer = new StringBuffer();
36 | javaBuffer.append("package ");
37 | javaBuffer.append(packageName);
38 | javaBuffer.append(";\n");
39 |
40 | return javaBuffer.toString();
41 | }
42 |
43 | public String getName(){
44 | return packageName;
45 | }
46 |
47 | private PackageCreator(){
48 |
49 | }
50 |
51 | @SuppressWarnings("unused")
52 | private DroolsBuilder builder = null;
53 |
54 | public static PackageCreator create(String content, DroolsBuilder builder){
55 |
56 | if(StringUtils.isEmpty(content)){
57 | return null;
58 | }
59 |
60 | if(!content.startsWith("package")){
61 | return null;
62 | }
63 |
64 | content = content.trim();
65 |
66 | PackageCreator creator = new PackageCreator();
67 | creator.builder = builder;
68 |
69 | String[] sections = content.split("\\s+|\\t|\\n|\\r");
70 | if(sections.length >=2){
71 |
72 | if(sections[1].endsWith(";")){
73 | sections[1] = sections[1].substring(0, sections[1].length()-1);
74 | }
75 | creator.packageName = sections[1].trim();
76 | }else{
77 |
78 | creator.packageName = null;
79 | }
80 |
81 | return creator;
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/drools/QueryCreator.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.drools;
16 |
17 | import java.lang.reflect.Field;
18 | import java.lang.reflect.InvocationTargetException;
19 | import java.lang.reflect.Method;
20 | import java.util.HashMap;
21 | import java.util.Map;
22 |
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 |
26 | import com.alibaba.druid.util.StringUtils;
27 |
28 | import tech.kiwa.engine.component.AbstractRuleItem;
29 | import tech.kiwa.engine.exception.RuleEngineException;
30 |
31 | /**
32 | * @author Hale.Li
33 | * @since 2018-01-28
34 | * @version 0.1
35 | */
36 | public class QueryCreator implements DroolsPartsCreator {
37 |
38 | private String name;
39 | private String content;
40 | private Map params = null;
41 | private LocalCreator result = null;
42 | private ConstraintCreator condition = null;
43 |
44 | private Logger log = LoggerFactory.getLogger(QueryCreator.class);
45 |
46 | //private Object object = null;
47 | private DroolsBuilder builder = null;
48 |
49 | public ConstraintCreator getCondition() {
50 | return condition;
51 | }
52 |
53 | public DroolsBuilder getBuilder(){
54 | return builder;
55 | }
56 |
57 | public String getName() {
58 | return name;
59 | }
60 |
61 | public String getContent() {
62 | return content;
63 | }
64 |
65 |
66 | public Map getParams() {
67 | return params;
68 | }
69 |
70 | public LocalCreator getResult() {
71 | return result;
72 | }
73 |
74 | private QueryCreator(){
75 |
76 | }
77 |
78 |
79 |
80 | public static QueryCreator create(String content, DroolsBuilder builder){
81 |
82 | if(StringUtils.isEmpty(content)){
83 | return null;
84 | }
85 |
86 | if(!content.startsWith("query")){
87 | return null;
88 | }
89 |
90 | content = content.trim();
91 |
92 | QueryCreator creator = new QueryCreator();
93 | creator.builder = builder;
94 |
95 | String[] lines = content.split("\\n|\\r");
96 | String title = lines[0].trim();
97 |
98 | String[] sections = title.split("\\s+|\\t|\\(|,|\\)");
99 |
100 | if(sections.length >= 2){
101 |
102 | creator.name = sections[1];
103 | if(creator.name.startsWith("\"") && creator.name.endsWith("\"")){
104 | creator.name = creator.name.substring(1, creator.name.length()-1);
105 | }
106 |
107 | if(title.endsWith(")")){
108 | creator.params = new HashMap();
109 |
110 | String type = null, name =null;
111 | for(int iLoop = 2; iLoop < sections.length; iLoop ++){
112 | if(StringUtils.isEmpty(sections[iLoop])){
113 | continue;
114 | }
115 | if(type == null){
116 | type = sections[iLoop];
117 | }else{
118 | name = sections[iLoop];
119 | }
120 | if(type != null && name != null){
121 | creator.params.put(name,type);
122 | type = null;
123 | name = null;
124 | }
125 | }
126 | }
127 |
128 | int pos = title.length() + "\\n".length();
129 |
130 | creator.content = content.substring(pos );
131 | creator.content = creator.content.trim();
132 | if(creator.content.endsWith("end")){
133 | creator.content = creator.content.substring(0, creator.content.length()-"end".length());
134 | creator.content = creator.content.trim();
135 | }
136 |
137 | if(creator.content.contains(":")){
138 | sections = creator.content.split(":");
139 | creator.result = new LocalCreator();
140 | creator.result.setName(sections[0].trim());
141 | pos = sections[1].indexOf("(");
142 | //sections = sections[1].split("\\(");
143 | creator.result.setReference(sections[1].substring(0, pos));
144 |
145 | if( sections[1].endsWith(")")){
146 | sections[1] = sections[1].substring(pos, sections[1].length() );
147 | sections[1] = sections[1].trim();
148 | }
149 | creator.condition = ConstraintCreator.create(sections[1], creator);
150 | }
151 | }
152 |
153 | return creator;
154 |
155 | }
156 |
157 | public boolean run(Object object) throws RuleEngineException {
158 |
159 | boolean bRet = false;
160 |
161 | //this.object = object;
162 |
163 | String className = result.getReference();
164 |
165 | if (object.getClass().getName().equals(className)) {
166 |
167 | try {
168 | bRet = condition.executeExpress(object);
169 | } catch (RuleEngineException e) {
170 | log.debug(e.getMessage());
171 | throw e;
172 | }
173 |
174 | }
175 |
176 | return bRet;
177 | }
178 |
179 | public boolean operateCallback(String leftValue , String comparisonCode ,String baseValue, Object object) throws RuleEngineException{
180 |
181 | boolean bRet = false;
182 |
183 | try {
184 |
185 | Class> retClass = object.getClass();
186 | Field field = retClass.getDeclaredField(leftValue);
187 | Object value = null;
188 | if(field!=null && field.isAccessible()){
189 | value = field.get(object);
190 | }else {
191 | String methodName = "get"+ leftValue.substring(0,1).toUpperCase() + leftValue.substring(1);
192 | Method method = retClass.getMethod(methodName,(Class>[])null);
193 | if(method != null ){
194 | value = method.invoke(object, (Object[]) null);
195 | }
196 | }
197 |
198 | if(value != null){
199 | bRet = AbstractRuleItem.comparisonOperate(value.toString(), comparisonCode, baseValue);
200 | }
201 | } catch (IllegalAccessException | NoSuchFieldException | SecurityException | NoSuchMethodException | IllegalArgumentException | InvocationTargetException e ) {
202 |
203 | throw new RuleEngineException(e.getCause());
204 | }
205 |
206 | return bRet;
207 | }
208 |
209 | @Override
210 | public String toJavaString() {
211 |
212 | StringBuffer java = new StringBuffer();
213 | java.append("boolean bResult = false;\n");
214 | java.append("bResult = (");
215 |
216 | String constraint = condition.toJavaString();
217 | constraint.replace("?", result.getName());
218 |
219 | java.append(constraint);
220 |
221 | java.append(")");
222 |
223 | return java.toString();
224 |
225 | }
226 | }
227 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/impl/DBRuleReader.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.impl;
16 |
17 | import java.sql.Connection;
18 | import java.sql.PreparedStatement;
19 | import java.sql.ResultSet;
20 | import java.sql.SQLException;
21 | import java.sql.Statement;
22 | import java.util.ArrayList;
23 | import java.util.List;
24 |
25 | import org.slf4j.Logger;
26 | import org.slf4j.LoggerFactory;
27 |
28 | import tech.kiwa.engine.component.AbstractRuleReader;
29 | import tech.kiwa.engine.entity.RuleItem;
30 | import tech.kiwa.engine.exception.RuleEngineException;
31 | import tech.kiwa.engine.framework.DBAccesser;
32 | import tech.kiwa.engine.utility.PropertyUtil;
33 |
34 | /**
35 | * @author Hale.Li
36 | * @since 2018-01-28
37 | * @version 0.1
38 | */
39 | public class DBRuleReader extends AbstractRuleReader {
40 |
41 | private static Logger log = LoggerFactory.getLogger(DBRuleReader.class);
42 |
43 | private static volatile DBAccesser accesser = null; //数据库访问类。
44 |
45 | @SuppressWarnings("unchecked")
46 | private DBAccesser loadDBAccesser() throws ClassNotFoundException, InstantiationException, IllegalAccessException{
47 |
48 | if(accesser == null){
49 |
50 | String className = PropertyUtil.getProperty("db.accesser");
51 | Class DBClass = (Class) Class.forName(className);
52 |
53 | synchronized(DBAccesser.class){
54 | if(accesser == null){
55 | accesser = DBClass.newInstance();
56 | }
57 | }
58 | }
59 |
60 | return accesser;
61 | }
62 |
63 | @Override
64 | public List readRuleItemList() throws RuleEngineException {
65 |
66 |
67 | Statement stmt = null;
68 | ResultSet res = null;
69 |
70 | //缓存加载
71 | if(!ruleItemCache.isEmpty()){
72 | return ruleItemCache;
73 | }
74 |
75 | List retList = new ArrayList();
76 |
77 | String sqlStr = " select * from "+ PropertyUtil.getProperty("db.rule.table") +" where ENABLE_FLAG = 1 order by PRIORITY desc ";
78 | try {
79 |
80 | loadDBAccesser();
81 | Connection conn = accesser.getConnection();
82 |
83 | stmt = conn.prepareStatement(sqlStr);
84 | //stmt = conn.createStatement();
85 | res = stmt.executeQuery(sqlStr);
86 | while(res.next())
87 | {
88 | RuleItem rule = new RuleItem();
89 | rule.setItemNo(res.getString("ITEM_NO"));
90 | rule.setContent(res.getString("content"));
91 | rule.setExeSql(res.getString("EXE_SQL"));
92 | rule.setExeClass(res.getString("exe_class"));
93 | rule.setParamType(res.getString("param_type"));
94 | rule.setParamName(res.getString("PARAM_NAME"));
95 | rule.setComparisonCode(res.getString("comparison_code"));
96 | rule.setComparisonValue(res.getString("comparison_value"));
97 | rule.setBaseline(res.getString("BASELINE"));
98 | rule.setResult(res.getString("result"));
99 | rule.setExecutor(res.getString("EXECUTOR"));
100 | rule.setPriority(res.getString("PRIORITY"));
101 | rule.setParentItemNo(res.getString("PARENT_ITEM_NO"));
102 | rule.setGroupExpress(res.getString("group_express"));
103 | rule.setContinueFlag(res.getString("CONTINUE_FLAG"));
104 | rule.setRemark(res.getString("REMARK"));
105 | rule.setComments(res.getString("COMMENTS"));
106 | rule.setEnableFlag(res.getString("ENABLE_FLAG"));
107 | rule.setCreateTime(res.getDate("CREATE_TIME"));
108 | rule.setUpdateTime(res.getDate("UPDATE_TIME"));
109 | if(!preCompile(rule)){
110 | log.debug("database rule format error.");
111 | throw new RuleEngineException("rule format error.");
112 | //return null;
113 | }
114 |
115 | retList.add(rule);
116 | }
117 |
118 | res.close();
119 | stmt.close();
120 |
121 |
122 | //accesser.closeConnection(conn);
123 |
124 | } catch (SQLException e) {
125 | log.debug(e.getMessage());
126 | throw new RuleEngineException(e.getCause());
127 | } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e){
128 | log.debug(e.getMessage());
129 | throw new RuleEngineException(e.getCause());
130 | } catch (Exception e) {
131 | log.debug(e.getMessage());
132 | throw new RuleEngineException(e.getCause());
133 | }
134 |
135 | //添加到缓存中。
136 | synchronized(ruleItemCache){
137 | ruleItemCache.addAll(retList);
138 | }
139 |
140 | return ruleItemCache;
141 |
142 | }
143 |
144 | @Override
145 | public Long getRuleItemCount() throws RuleEngineException {
146 |
147 |
148 | Statement stmt = null;
149 | ResultSet res = null;
150 |
151 | long count = 0;
152 |
153 | String sqlStr = " select count(*) from "+ PropertyUtil.getProperty("db.rule.table") +" where ENABLE_FLAG = 1 ";
154 | try {
155 |
156 | loadDBAccesser();
157 | Connection conn = accesser.getConnection();
158 |
159 | stmt = conn.prepareStatement(sqlStr);
160 | //stmt = conn.createStatement();
161 | res = stmt.executeQuery(sqlStr);
162 | res.next();
163 | count = res.getLong(1);
164 |
165 | res.close();
166 | stmt.close();
167 |
168 | //accesser.closeConnection(conn);
169 |
170 | } catch (SQLException e) {
171 | log.debug(e.getMessage());
172 | throw new RuleEngineException(e.getCause());
173 | } catch (Exception e) {
174 | log.debug(e.getMessage());
175 | throw new RuleEngineException(e.getCause());
176 | }
177 |
178 |
179 | return count;
180 | }
181 |
182 | @Override
183 | public RuleItem getRuleItem(String ruleId) throws RuleEngineException {
184 |
185 |
186 | PreparedStatement stmt = null;
187 | ResultSet res = null;
188 |
189 | List retList = new ArrayList();
190 |
191 | String sqlStr = " select * from "+ PropertyUtil.getProperty("db.rule.table") +" where ENABLE_FLAG = 1 and ITEM_NO = ? ";
192 | try {
193 |
194 | loadDBAccesser();
195 | Connection conn = accesser.getConnection();
196 |
197 | stmt = conn.prepareStatement(sqlStr);
198 | stmt.setString(1, ruleId);
199 | res = stmt.executeQuery();
200 |
201 | while(res.next())
202 | {
203 | RuleItem rule = new RuleItem();
204 | rule.setItemNo(res.getString("ITEM_NO"));
205 | rule.setContent(res.getString("content"));
206 | rule.setExeSql(res.getString("EXE_SQL"));
207 | rule.setExeClass(res.getString("exe_class"));
208 | rule.setParamType(res.getString("param_type"));
209 | rule.setParamName(res.getString("PARAM_NAME"));
210 | rule.setComparisonCode(res.getString("comparison_code"));
211 | rule.setComparisonValue(res.getString("comparison_value"));
212 | rule.setBaseline(res.getString("BASELINE"));
213 | rule.setResult(res.getString("result"));
214 | rule.setExecutor(res.getString("EXECUTOR"));
215 | rule.setPriority(res.getString("PRIORITY"));
216 | rule.setParentItemNo(res.getString("PARENT_ITEM_NO"));
217 | rule.setGroupExpress(res.getString("group_express"));
218 | rule.setContinueFlag(res.getString("CONTINUE_FLAG"));
219 | rule.setRemark(res.getString("REMARK"));
220 | rule.setComments(res.getString("COMMENTS"));
221 | rule.setEnableFlag(res.getString("ENABLE_FLAG"));
222 | rule.setCreateTime(res.getDate("CREATE_TIME"));
223 | rule.setUpdateTime(res.getDate("UPDATE_TIME"));
224 | if(!preCompile(rule)){
225 | log.debug("database rule format error.");
226 | throw new RuleEngineException("rule format error.");
227 | //return null;
228 | }
229 |
230 | retList.add(rule);
231 | //只读一条记录。
232 | break;
233 | }
234 |
235 | res.close();
236 | stmt.close();
237 |
238 | //accesser.closeConnection(conn);
239 |
240 | } catch (SQLException e) {
241 | log.debug(e.getMessage());
242 | throw new RuleEngineException(e.getCause());
243 | } catch (Exception e) {
244 | log.debug(e.getMessage());
245 | throw new RuleEngineException(e.getCause());
246 | }
247 |
248 | if(retList.isEmpty()){
249 | return null;
250 | }
251 |
252 | return retList.get(0);
253 |
254 | }
255 |
256 |
257 |
258 | public static void main(String[] args){
259 | DBRuleReader reader = new DBRuleReader();
260 |
261 | try {
262 | reader.getRuleItem("3");
263 | reader.readRuleItemList();
264 | } catch (RuleEngineException e) {
265 | // TODO Auto-generated catch block
266 | e.printStackTrace();
267 | }
268 |
269 | }
270 |
271 | }
272 |
273 |
--------------------------------------------------------------------------------
/src/main/java/tech/kiwa/engine/component/impl/DefaultRuleExecutor.java:
--------------------------------------------------------------------------------
1 | //Copyright Hale [hale2000@163.com]
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | package tech.kiwa.engine.component.impl;
16 |
17 | import java.math.BigDecimal;
18 | import java.sql.Connection;
19 | import java.sql.PreparedStatement;
20 | import java.sql.ResultSet;
21 | import java.sql.ResultSetMetaData;
22 | import java.sql.SQLException;
23 | import java.text.SimpleDateFormat;
24 | import java.util.ArrayList;
25 | import java.util.Date;
26 | import java.util.HashMap;
27 | import java.util.List;
28 | import java.util.Map;
29 |
30 | import org.apache.commons.lang.StringUtils;
31 | import org.slf4j.Logger;
32 | import org.slf4j.LoggerFactory;
33 |
34 | import tech.kiwa.engine.component.AbstractCommand;
35 | import tech.kiwa.engine.component.AbstractRuleItem;
36 | import tech.kiwa.engine.entity.ItemExecutedResult;
37 | import tech.kiwa.engine.entity.RESULT;
38 | import tech.kiwa.engine.entity.RuleItem;
39 | import tech.kiwa.engine.exception.RuleEngineException;
40 | import tech.kiwa.engine.framework.DBAccesser;
41 | import tech.kiwa.engine.utility.PropertyUtil;
42 |
43 |
44 | /**
45 | * @author Hale.Li
46 | * @since 2018-01-28
47 | * @version 0.1
48 | */
49 | public class DefaultRuleExecutor extends AbstractRuleItem {
50 |
51 | private Logger log = LoggerFactory.getLogger(DefaultRuleExecutor.class);
52 |
53 | private static volatile DBAccesser accesser = null; //数据库访问类。
54 |
55 | @SuppressWarnings("unchecked")
56 | private DBAccesser loadDBAccesser() throws ClassNotFoundException, InstantiationException, IllegalAccessException{
57 |
58 | if(accesser == null){
59 |
60 | String className = PropertyUtil.getProperty("db.accesser");
61 | Class DBClass = (Class) Class.forName(className);
62 | synchronized(DBAccesser.class){
63 | if(null == accesser){
64 | accesser = DBClass.newInstance();
65 | }
66 | }
67 | }
68 |
69 | return accesser;
70 | }
71 |
72 |
73 | @Override
74 | public ItemExecutedResult doCheck(RuleItem item) throws RuleEngineException {
75 |
76 | String sqlStr = item.getExeSql();
77 |
78 | if(StringUtils.isEmpty(sqlStr)){
79 | log.debug("This function must be called when the sql statement is not empty.");
80 | throw new RuleEngineException("This function must be called when the sql statement is not empty.");
81 | }
82 |
83 | // add tailed space.
84 | if(sqlStr.endsWith("?")){
85 | sqlStr = sqlStr + " ";
86 | }
87 |
88 | String paramName = item.getParamName();
89 | List