Can a rules file have a dependency on other rules? - java

I'm using drools rules engine for my new service. I'm looking at cleaning up the rules / making it easier to write. I was hoping to use a rules framework style of coding. I.e. I want a rules file who's sole purpose is to validate the input data (i.e. input list isn't null and contains a specific value). Then when I write new rules files I can just say import this and run the validation before all other rules.
Also, I know I can load multiple rules file into the KieSession. Is it possible to tell it which order to run the rules files in, or which files to skip for each use case? The idea behind this is for performance. Let's say I load up an AWS lambda function with the rules service, I want to have all rules loaded already and have it run the specific one for the use case, instead of loading up a rules file for each call.
Thanks for the help.

You asked
Is it possible to tell it which order to run the rules files in, or which files to skip for each use case?
The answer is yes. The method to do this is called salience. The linked article is a good source to learn about this. This is important because salience can make it possible to change the order of execution of rules.
Hypothetically, let say that you have a program that process transactions based on categories. So, if category == deposit, you want to add to current balance. You have another rule that if category == withdrawal you want to subtract from current balance. BUT, you want to process deposits over withdrawals. Using salience you can guarantee that the deposits rule will fire before the withdrawal rule regardless of order of transaction.
Dependency is kind of related, but not the same. In drools, this is know as Forward or Backward Chaining depending on the order. This is all composed based on a series of facts. For example, if I was to ask a system "is my house on planet Earth?" the conclusion is reached if the following facts exist:
My house is in Fort Worth
Fort Worth is a city in Texas
Texas is a state in the United States
United States is a country on Earth
A direct fact linking the house location to this planet is asserted based on the rules that verify the enumerated facts above. This is done using chaining. Forward or backwards is just how these are processed (top-down or bottom-up). This is in a nutshell to the best of my recollection.

Yes, it is possible by using salience and assigning priorities to some rules so that they execute before other rules. Also, we can make use of inference engine to create facts which can make other rules eligible for execution.

Related

Drools Decision Table Action Execution Order

I have a Drools decision table (see below) whereby Rule 2 has a condition that checks whether a nutrient score is between a certain threshold and executes an action based on this condition. There is an initial rule (RULE 1) that performs a check and performs its action, which updates the overall scores that i want Rule2 to use when executing its conditions.
What i expect/need:
Rule 1 to run, if the condition is met then update the overall score on $model (by executing its action) and then rule 2 run and for it's conditions to use the updated score value that was updated by Rule 1's action running.
What's actually happening
Rule 1 runs it's condition, Rule 2 runs its condition, Rule 1's action is run, Rule 2's action is run. Rule 2 is running it's condition before Rule 1's action has run, and therefore uses an outdated score.
I've proven (i think) by changing the priority/salience value that i can change the order in which the rules run their conditions, but it seems that all rule conditions are running before actions. I expected Rule 1's action to run before the next rule.
Have i fundamentally mis-understood the concept? An obvious mistake? Or if anyone has a suggested workaround that would be great.
To clarify this is a stateless ki session.
Thanks in advance, this is driving me mad!
Drools works by taking all of the rules up front and evaluating whether their conditions are satisfied. Each of these rules is called a "match". When you fire the rules, Drools collects all of the matches, orders them (either naturally or by salience), and then iterates through and executes them one by one.
As the rules are executed, they might change working memory like your example does. Unless you explicitly tell Drools that you're doing so, however, it won't re-evaluate the matches. The match phase has already been completed by the time the rules are executed.
It is possible to tell Drools that you are modifying working memory and that you need it to re-evaluate its rules based on the new data. To do this, you need to use one of the built-in methods:
Method
Explanation
insert
Put a new fact into working memory.
delete or retract
Removes some information (object/s) from working memory.
update
Update/replace a fact in working memory.
modify
Change fields inside of a fact in working memory.
Which one you choose depends on what you're trying to do. Note that calling 'update' will call all matches to be re-evaluated ... it's the equivalent of calling "fire rules" a second time with the new data (so the same rule might hit multiple times, which may or may not be intentional). In comparison, insert will only evaluate subsequent rules to determine if they now match or don't based on the new conditions.
So if your intention is to cause other rules to fire or not by changing the data in working memory, you'll need to use one of these built-in methods to tell Drools that you're making a change that it should re-evaluate its matches for.
I discuss this concept in more detail in this answer specifically about DRL. The same concepts apply to decision tables.

Question about modelling a railway system [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am currently working on a task, where I have to build a railway simulation project in java (university project).
There are three types of rolling stock: wagon, locomotive and multiple unit.
All types of the rolling stock have a name and a length.
In addition, there are also three types of wagons and locomotives.
Here is a simple UML diagram that I created.
Now, I still have to implement this "feature":
"The multiple unit ID is composed according to the same rules as for locomotives. For this reason, locomotives and multiple units share the same ID space. A multiple unit has a special type of coupling and can therefore only be composed with the same series of multiple units"
What is the best way to use the same ID space for locomotives and multiple units?
Is this a good model or should I use interfaces instead? I would appreciate feedback and tips. Thanks in advance!
What is the best way to use the same ID space for locomotives and multiple units?
Doesn't matter, as long as it is unique. Just use a serial number or, if you want to have one that isn't tied to a single counter, use a fully random one (of 128 bits or more). Why not use a standard while you're at it.
One question you should ask yourself is: is this ID going to be used on the wagons? If so, a short, statically serial number (or string) certainly makes more sense. Probably there will be some registration body so in that case you have your centralized counter right there. Never forget to check if your model matches the real world!
It makes some sense to prefix the ID with the type of transport, although in that case I think it is not really using the same space anymore.
Is this a good model or should I use interfaces instead? I would appreciate feedback and tips.
EDIT: WRONG, I ASSUMED ALL ROLLING STOCK WOULD HAVE AN ID!!!
No, this is fine, you have operations on the ID after all. And you're probably going to add other functionality that it similar for all child classes to the rolling stock. Note that many environments have methods to extract an interface and replace the existing references to that interface. Refactoring is not something you want to do, but it is there when you need it.
EDIT:
If you have an ID just for locomotives and rolling stock then there are two options. Probably best is to insert an intermediate abstract class that defines an IdentifyableRollingStock intermediate class. There are other options out there such as creating an optional ID, or using a decorator pattern. It is a bit strange if wagons cannot be identified though, in NL I'm pretty sure that all rolling stock is identifiable.
I'm just left wondering if all rolling stock really has a name. I can see some cargo wagons just having a number. That's another real world check right there.
OT
A multiple unit has a special type of coupling and can therefore only be composed with the same series of multiple units"
The person who wrote that should be shot into orbit. Well be nice and make it the ISS. Going round and round and round...

Checking balance in ERC20 contract using web3j

I want to check user's balance of a couple of ERC20 compliant tokens using web3j.
Is there a generic way of doing that (generic for every ERC20 contract) or should I get ABI for each of the contracts and generate java classes from it?
I have never used web3j, but I have used web3js quite a bit. I will link you to relevant information.
Here is an interface that is already created in the tests of the web3j library, so the best place to start.
Extra notes (which might well be basic for you)
Checking the balance is something that you don't want to generate a transaction for (since it doesn't change the state of the blockchain) and so you should use a 'call', as explained here.
Also, it may be useful to understand how Ethereum creates the ABI in the first place. Every transaction or call can contain data with it, and the network then uses this data to determine which function is being called and it's parameters. The logic for this function is sitting at the address of the first 4 bytes of the kekak hash of the functions name/parameters (some info), which is one reason why it is so important that this hash is collision free (imagine 2 different functions hashing to the same address). But the take home of this is that all erc20 tokens (if they follow the standard) have common ABIs for those functions.
PS. For next time I think this question is better suited for Ethereum Stackexchange.

Which way is it better to extract Account number and Balance from a SMS body?

I am planning a task to read all the Bank related SMS from the users android mobile inbox and extract their account number and balance from it. I am guessing this could be done in 2 ways as,
Using RegEx to extract the data from the SMS body as stated link here. This certainly has the advantage of giving generic representation of any Bank Balance message
Store a template message of every bank in the database and compare it with the read SMS to extract the data
I would like to know which path is efficient or Is there any other way to do it ?
The two approaches have different qualities:
Option 1 might lead to many different, complex regular expressions. Alone glancing into the answer you linked made my head spin. Meaning: maintaining such a list of regular expressions will not be an easy undertaking from the developer perspective.
Whereas for option 2, of course you have to keep track regarding your collection of "templates", but: once your infrastructure is in place, the only work required for you: adding new templates; or adapting them.
So, from a "development" efforts side I would tend to option 2 --- because such "templates" are easier to manage by you. You don't even need much understanding of the Java language in order to deal with such templates. They are just text; containing some defined keywords here and there.
One could even think about telling your users how to define templates themselves! They know how the SMS from their bank looks like; so you could think about some "import" mechanism where your APP pulls the SMS text, and then the user tells the APP (once) where the relevant parts can be found in there!
Regarding runtime efficiency: I wouldn't rely on people making guesses here. Instead: make experiments with real world data; and see if matching SMS text against a larger set of complex regular expressions is cheaper or more expensive than matching them against much simpler "templates".
Storing the template for each bank cost more memory (if you load them on at start up for efficiency) and file system storage, and also as you stated, there is the downside of requiring previous know each bank template and setup the user application properly to it.
Using the regex will not cost file system store neither more memory, however it could create false positives for something which looks like a bank message, but it is not. However there is the facility to not need to know all the banks out there in order to do it properly.

Java formula evaluation library with out-of-order variables feature

I'm currently looking for a java library (or native library with a java API) for formula parsing and evaluation.
Using recommandations from here, I took a look on many libraries :
JFormula
JEval
Symja
JEP
But none of them fulfil my needs, that are :
Multiple formula evaluation with dependency between them (a formula is always an affectation to a variable using other variables or numerical values)
Possibility to change only one formula out of maybe 50, with good performances if only one formule changes
no need to handle by hand variables dependancies
Automatically update other dependant variables if a formula changes
Possibility to listen which variable changed
no need to have a specific format for the variables (the user will directly enter a name and doesn't want to have a complexe notation)
Maybe an exemple will be better. Let's say we have, entered in the system in this order :
a = b + c
c = 2 * d
b = 3
d = 2
I would like to be able to enter those 4 lines in this order, and ask for the result of "a" (or "b", whatever).
Then if in the user interface (basically a table variable <> formula) "b" is changed to "2 * d", the library will automatically change the value of "b" and "a", and return me (or lunch an event, or call a function) a list of changes
The best library would be one just like JEP, but with the out-of-order variables capability and the possibility to auto-evaluate dependant variables
I know that compilers and spreadsheet softwares uses such mechanisms, but I didn't found any java or java compatible libraries directly usable
Does someone know one?
EDIT : Precision : the question is really about a library, or eventually a set of libraries to link together. The question is for a project in a company and the idea is to spend the minimum amount of time. The "do it yourself" solution has already been estimated and is not in the scope of the question
For a project that I also needed a simple formula parser I used the code of the article Lexical analysis, Part 2: Build an application in javaworld.com. It's simple and small (7 classes), and you can adapt it to your needs.
You can downdoad the source form here (search for 'Lexical Analysis Part II' entry).
Don't know of any libraries.
Assuming what you have is a set of equations with a single variable on at least one side of the equation (A+B=C-D is disallowed) and no cycles, (e.g., A=B+1; B=A-2), what you technically need to do is to build a a data flow graph showing how each operator depends on its operands. For side-effect-free equations (e.g., pure math) this is pretty easy; you end up with a directed acyclic graph (a forest with shared subtrees representing shared subexpressions). Then if a value of a variable is changed, or a new formula is introduced, you revise the dag and re-evaluate the changed parts, propagating changes up the dag to the dag roots. So, you need to build trees for the expressions, and then share them (often by hashing on subtrees to find potential equivalent candidates). So, lots of structure manipulation to keep the dag (and is root values)
But if its only 50 variables of the complexity you show, it would act, you could simply reevaluate them all. If you store the expression as trees (or better yet, reverse polish) you can evaluate each tree quite fast, and you don't pay any overhead to keep all those data structures up to date.
If you have hundreds of equations, the dag scheme is likely a lot better.
If you have constraint equations (e.g., you aren't restricted as to what can be on both sides), you're outside the spreadsheet paradigm and into constraint solvers, which is a far more complex technology.
Why would not you just write your own? Your assessment of complexity of this task might be wrong. It is much easier than you might think - chances are, learning how to deal with any 3rd party library would require much more effort than implementing such a trivial thing from scratch. It should not take more than a couple of hours in the worst case.
It does not make any sense to look for 3rd party libraries for doing simple things (I know, it is a part of the Java ethos, but still...)
I'd recommend to take a look at the Cells library for inspiration. It is in Common Lisp, but ideas are basic enough to be transferred anywhere else.
you can check these links too...
MathPiper (a Java fork of the Java Yacas version) (has it's own
editor based on jEdit) (GPL) http://code.google.com/p/mathpiper/
Symja/Matheclipse (my own project, uses JAS and Commons Math
libraries) (LGPL) http://krum.rz.uni-mannheim.de/jas/
Java Algebra System (JAS) (LGPL) http://krum.rz.uni-mannheim.de/jas/
I would embedd Groovy, see the Tutorial about embedding here. Freeplane (a Java Mindmapper) also uses Groovy for formulas.
Whenever a variable is changing you have to put the new value into the binding.
All the cell code should be given to the Groovy Shell as single code piece. You can register on changes via BindPath.
Anyway I assume you have to implement a thin layer to fullfill your requirements:
no need to handle by hand variables dependancies
Possibility to listen which variable changed

Categories

Resources