Listen event in different package
by Marco Malziotti
Hello
I am a beginner in Drools 5.1.1 and try to listen a event in a packageX
inserted by a rule in another packageY.
I have following 2 drl file :
---inserter.drl----
package packageY
import internal.event.*;
declare EventItem
@role (event)
end
rule "insert EventItem"
when
...
then
EventItem ei = new EventItem(...);
insert(ei);
end
----------------
---listener.drl---
package packageX
import internal.event.*;
rule "listen EventItem temporal constraint"
when
ei: EventItem()
oi: OtherItem(this after ei)
then
System.out.println("Hello word");
end
----------------
EventItem and OtherItem are defined in 'internal.event' package.
If I run with a StatefulKnowledgeSession configured in 'pseudo clock',
I have following stack trace:
java.lang.ClassCastException: org.drools.common.DefaultFactHandle
cannot be cast to org.drools.common.EventFactHandle
at
org.drools.base.evaluators.AfterEvaluatorDefinition$AfterEvaluator.evaluateCachedRight(AfterEvaluatorDefinition.java:322)
at
org.drools.rule.VariableRestriction.isAllowedCachedRight(VariableRestriction.java:117)
at
org.drools.rule.VariableConstraint.isAllowedCachedRight(VariableConstraint.java:121)
at
org.drools.common.SingleBetaConstraints.isAllowedCachedRight(SingleBetaConstraints.java:151)
at org.drools.reteoo.JoinNode.assertObject(JoinNode.java:125)
at
org.drools.reteoo.SingleObjectSinkAdapter.propagateAssertObject(SingleObjectSinkAdapter.java:59)
at org.drools.reteoo.AlphaNode.assertObject(AlphaNode.java:145)
at
org.drools.reteoo.SingleObjectSinkAdapter.propagateAssertObject(SingleObjectSinkAdapter.java:59)
at
org.drools.reteoo.ObjectTypeNode.assertObject(ObjectTypeNode.java:190)
at
org.drools.reteoo.EntryPointNode.assertObject(EntryPointNode.java:145)
at
org.drools.common.AbstractWorkingMemory.insert(AbstractWorkingMemory.java:1174)
at
org.drools.common.AbstractWorkingMemory.insert(AbstractWorkingMemory.java:1123)
at
org.drools.common.AbstractWorkingMemory.insert(AbstractWorkingMemory.java:917)
at
org.drools.impl.StatefulKnowledgeSessionImpl.insert(StatefulKnowledgeSessionImpl.java:251)
...
Moving listener.drl in packageY, all works.
I don't know if it is already open a related issue, perhaps the :
https://issues.jboss.org/browse/JBRULES-2774
Thanks for your attention.
Regards.
Marco Malziotti
Tecnologie nelle Reti e nei Sistemi T.R.S. S.p.A.
Integration Test Engineer
Tel. + 39 06.87281.407
Fax. + 39 06.87281.550
E-mail: marco.malziotti(a)trs.it
Tecnologie nelle Reti e nei Sistemi T.R.S. SpA
Via della Bufalotta, 378 - 00139 Roma
Tel +39.06.87.28.1.1 - Fax +39.06.87.28.1.550
-------------------------------------------------------
Ai sensi del D.Lgs. 196/2003 si precisa che le informazioni contenute in questo messaggio
sono riservate ed a uso esclusivo del destinatario. Qualora il messaggio in parola Le
fosse pervenuto per errore, la preghiamo di eliminarlo senza copiarlo e di non inoltrarlo
a terzi, dandocene gentilmente comunicazione. Grazie.
This message, for the law 196/2003, may contain confidential and/or privileged information.
If you are not the addressee or authorized to receive this for the addressee, you must not
use, copy, disclose or take any action based on this message or any information herein.
If you have received this message in error, please advise the sender immediately by reply
e-mail and delete this message. Thank you for your cooperation.
-------------------------------------------------------
This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean.
13 years, 2 months
retracting facts based on fact properties
by Jeremy Ary
I've found myself in need of something similar to what Wolfgang described
in an archived post in order to handle retractions based on dynamic
properties found on the fact itself:
*****
Just in case anybody wonders about the effort for building a mechanism for
retracting facts based on fact attributes or other data, I outline the
solution I have implemented.
My class FactWiper implements WorkingMemoryEventListener and Runnable.
- The implementation of objectInserted( ObjectInsertedEvent event )
determines whether the object needs handling and, if so, the retraction
Date, based upon whatever strategy you care to implement, e.g., reflection
method call, Map<Class,Long>, etc. If it is to be handled, it signals
Condition "change" to the thread.
- A SortedMap<Date,Object> expiry2fact keeps track of pending
retractions.
- The thread loops into an awaitUntil( x ) on the "change" condition,
where x is (generally) the first retraction Date. If reached, it retracts
according to the foremost Map entry; if signalled it reasesses the
situation and reenters the awaitUntil.
-W
*****
However, I've been thus far unable to beat an IllegalMonitorStateException
I encounter when looping back in from an insertLogical. Below is my
Listener class and my example rules that demonstrate the exception. Anyone
see what I'm doing wrong with the thread conditions? Thanks for your time.
- Jeremy
--------------------- LISTENER CLASS ------------------------
@Slf4j
@Component
class RetractionListener implements WorkingMemoryEventListener, Runnable {
/** allow a sorted map to track dates and objects to be retracted */
NavigableMap<Date, Object> retractionSchedule = new TreeMap<Date,
Object>();
/** allow some condition to signify when we have a new retractable fact
to consider */
Condition change
/** session wrapper */
@Autowired
SessionManager sessionManager
/**
* runnable task entry point for executor
*/
void run() {
Lock lock = new ReentrantLock()
change = lock.newCondition()
lock.lock()
while (retractionSchedule.isEmpty()) {
change.await()
}
try {
while (System.currentTimeMillis() <
retractionSchedule.firstKey().time) {
log.debug("issuing wait")
change.awaitUntil(retractionSchedule.firstKey())
}
FactHandle handle =
sessionManager.factHandleMap.get(retractionSchedule.firstEntry().value)
sessionManager.session.retract(handle)
} catch (InterruptedException e) {
log.error("RetractionListener thread
${Thread.currentThread().name} interrupted!")
throw e
} finally {
lock.unlock()
}
}
/**
* detect new facts, determine if they are retractable, and add to the
tracker map if needed
*
* @param event
*/
void objectInserted(ObjectInsertedEvent event) {
if (event.object.isRetractable) {
log.debug("retractable object of type
${event.object.class.simpleName} detected")
try {
long duration = event.object.duration
if (!duration) {
// go ahead and throw up a similar exception to missing
property for a missing value
throw new MissingPropertyException("no value specified
for retractable object's duration")
} else {
Calendar calendar = GregorianCalendar.getInstance()
log.debug("duration of object noted to be ${duration}
milliseconds")
log.debug("current time: ${calendar.time}")
calendar.add(Calendar.MILLISECOND, duration.toInteger())
log.debug("setting schedule for ${calendar.time}")
retractionSchedule.put(calendar.time, event.object)
log.debug("signaling change condition")
change.signal()
}
} catch (MissingPropertyException e) {
log.error("retractable object ${event.object} missing
needed property/value 'duration'")
throw e
}
}
}
...[REST OF CLASS IRRELEVANT]...
}
--------------------- RULE FILE -------------------------
declare Fire
@role(event)
end
declare SprinklerInterval
@role(event)
fire : Fire
isRetractable : boolean
duration : long
end
rule "fire detected"
when
$f : Fire ( )
not SprinklerInterval ( fire == $f )
then
insertLogical ( new SprinklerInterval($f, true, 500) );
end
rule "add sprinklers running notification"
when
$s : SprinklerInterval ( )
then
log.info("Sprinklers running on fire located in: " +
$s.getFire().getName());
end
13 years, 2 months
Documentation for Drools Expert 5.1
by veit.guna@nightprogrammer.org
Hi.
I'm trying to find the old documentation for Drools Expert 5.1 but
without luck. On the servers I find >=5.2 versions only.
Any chance to get the 5.1 version somewhere?
Thanks.
13 years, 2 months
Dynamic refresh from Guvnor in Web Application
by kappert
Version 5.5.0.Final (Guvnor and libraries)
Tomcat 6
Goal: We would like to change rules on-the-fly in Guvnor so they become
immediately effective in a web application running in Tomcat.
The function below is used to connect go Guvnor. It works fine in a
standalone Java program, but in the web application the updates in Guvnor
have no effect.
Does anybody have experience with this scenario?
Is there something wrong with the function used to connect to Guvnor?
Additional observation: Instead of loading the rules from Guvnor I have
tried loading them from a file, with refresh. The file is found the first
time when Drools starts, so the path is correct. When I change the rules
file in Eclipse the updated file is auto-deployed to Tomcat. Indeed Drools
realizes a change, /but fails to load the file with the following error:
Caused by: java.io.FileNotFoundException: 'org/somewhere/Rules.drl' cannot
be opened because it does not exist
at org.drools.io.impl.ClassPathResource.getURL(ClassPathResource.java:165)
at
org.drools.io.impl.ClassPathResource.getLastModified(ClassPathResource.java:177)/
Is it possible that Drools uses different methods for loading rules
initially and when an update is detected? Why would the file be found the
first time, but not after an update?
Function connecting to Guvnor with refresh
/**
* Creates a StatefulKnowledgeSession that accesses Guvnor using the
resource specification in
* the provided changeset. Changes in the rules in Guvnor are detected
on-the-fly (scanner interval).
* "Build package" in Guvnor is required to activate changed rules.
* <p>
* TODO Services are started that detect changes in the Guvnor rules. They
should be shutdown when an application
* terminates. This should be imlemented in a production environment.
*
* @param pathChangeSet String with the location of the rules file. If your
rules file is in a top directory
* (for example src/main/rules), then the path is "changeset.xml".
If it is in a package
* org.somewhere, then the string is "org/somewhere/changeset.xml".
* @param scannerIntervalSeconds int, seconds between rescan of the rules
file
* @return StatefulKnowledgeSession
*/
public static StatefulKnowledgeSession
createStatefulKnowledgeSessionWithGuvnor(String pathChangeSet, int
scannerIntervalSeconds) {
final ResourceChangeScannerConfiguration sconf =
ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration();
sconf.setProperty("drools.resource.scanner.interval",
Integer.toString(scannerIntervalSeconds));
ResourceFactory.getResourceChangeScannerService().configure(sconf);
ResourceFactory.getResourceChangeScannerService().start();
ResourceFactory.getResourceChangeNotifierService().start();
final KnowledgeAgentConfiguration knowlegdeAgentConfiguration =
KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
knowlegdeAgentConfiguration.setProperty("drools.agent.newInstance",
"false"); // keeps the session
final KnowledgeAgent kagent =
KnowledgeAgentFactory.newKnowledgeAgent("MyKnowledgeAgent",
knowlegdeAgentConfiguration);
final Resource changeset =
ResourceFactory.newClassPathResource(pathChangeSet);
kagent.applyChangeSet(changeset);
return kagent.getKnowledgeBase().newStatefulKnowledgeSession();
}
Function connecting to rules file with refresh
/**
* Creates a StatefulKnowledgeSession that uses the specified rules file.
* Changes in the rules file are detected on-the-fly (scanner interval).
* <p>
* TODO Services are started that detect changes in the rules file. They
should be shutdown when an application
* terminates. This should be imlemented in a production environment.
*
* @param pathRulesFile String with the location of the rules file. If your
rules file is in a top directory
* (for example src/main/rules), then the path is "rules.drl". If it
is in a package
* ch.sbb.eventhub, then the string is "ch/sbb/eventhub/rules.drl".
* @param scannerIntervalSeconds int, seconds between rescan of the rules
file
* @return StatefulKnowledgeSession
*/
public static StatefulKnowledgeSession
createStatefulKnowledgeSessionWithFile(String pathRulesFile, int
scannerIntervalSeconds) {
final ResourceChangeScannerConfiguration sconf =
ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration();
sconf.setProperty("drools.resource.scanner.interval",
Integer.toString(scannerIntervalSeconds));
sconf.setProperty("drools.agent.newInstance", "false"); // not needed
ResourceFactory.getResourceChangeScannerService().configure(sconf);
ResourceFactory.getResourceChangeScannerService().start();
ResourceFactory.getResourceChangeNotifierService().start();
final KnowledgeBuilder kbuilder =
KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource(pathRulesFile),
ResourceType.DRL);
final KnowledgeBuilderErrors errors = kbuilder.getErrors();
if (errors.size() > 0) {
for (final KnowledgeBuilderError error : errors) {
System.err.println(error);
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
final KnowledgeAgentConfiguration knowlegdeAgentConfiguration =
KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
knowlegdeAgentConfiguration.setProperty("drools.agent.scanResources",
"true"); // not neeeded
knowlegdeAgentConfiguration.setProperty("drools.agent.scanDirectories",
"true"); // not needed
knowlegdeAgentConfiguration.setProperty("drools.agent.newInstance",
"false"); // required!
final KnowledgeAgent kagent =
KnowledgeAgentFactory.newKnowledgeAgent("From File", kbase,
knowlegdeAgentConfiguration);
return kagent.getKnowledgeBase().newStatefulKnowledgeSession();
}
--
View this message in context: http://drools.46999.n3.nabble.com/Dynamic-refresh-from-Guvnor-in-Web-Appl...
Sent from the Drools: User forum mailing list archive at Nabble.com.
13 years, 2 months
Drools: Using Declared Types in Decision Tables
by David Smith
Hi,
I am trying to use a declared type in a decision table
but get an "Unable to resolve ObjectType" message.
The declared type is in a file types.drl,
I have a spreadsheet test.xls that has a Ruleset with
an import line for the declared type.
Is it possible to reference a declared type from a decision table?
Is it possible to declare a type in a decision table?
Thanks
David
13 years, 2 months
Fw: proble with localSearch
by Michiel Vermandel
Hi Geoffrey,
Thanks for your advice.
Indeed one of the planning variables is consistently null over all planning entities.
Should drools planner take care of this or should I impose an extra rule to exclude these selections?
Once again I seem to struggle with nulls being passed in as planning variable...
Thanks,
Michiel
-----------------
http://www.codessentials.com - Your essential software, for free!
Follow us at http://twitter.com/#!/Codessentials
________________________________
From: Geoffrey De Smet <ge0ffrey.spam(a)gmail.com>
To: Michiel Vermandel <mvermand(a)yahoo.com>; Rules Users List <rules-users(a)lists.jboss.org>
Sent: Tuesday, January 8, 2013 4:27 PM
Subject: Re: proble with localSearch
Op 08-01-13 15:24, Michiel Vermandel schreef:
Hi,
>
>I'm trying to implement a basic local search (really new to it).
>
>When I run my project I now get:
>
>Exception in thread "main" java.lang.IllegalStateException:
Phase localSearch started with an uninitialized Solution. First
initialize the Solution. For example, run a phase
constructionHeuristic first.
> at
org.drools.planner.core.localsearch.DefaultLocalSearchSolverPhase.phaseStarted(DefaultLocalSearchSolverPhase.java:120)
>
You have a construction heuristic configured, so all @PlanningVariable's should be different from null after that phase is ended.
So when the local search phase starts, that check should be ok and
not throw that exception.
Comment out local search, write the solution to disk an verify that
all planning variables are now not null.
Or debug where that exception is throw and inspect
phaseScope.getSolverScope().getScoreDirector().getWorkingSolution().
>This is my config:
>
><?xml version="1.0" encoding="UTF-8"?>
><solver>
> <environmentMode>DEBUG</environmentMode>
>
> <!-- Domain model configuration -->
>
<solutionClass>be.axi.planner.app.InspectionSchedule</solutionClass>
>
<planningEntityClass>be.axi.planner.domain.Task</planningEntityClass>
>
> <!-- Score configuration -->
> <scoreDirectorFactory>
>
<scoreDefinitionType>HARD_AND_SOFT</scoreDefinitionType>
> <scoreDrl>/inspectionRules.drl</scoreDrl>
> </scoreDirectorFactory>
>
> <constructionHeuristic>
>
<constructionHeuristicType>BEST_FIT_DECREASING</constructionHeuristicType>
> <!--
constructionHeuristicPickEarlyType>FIRST_LAST_STEP_SCORE_EQUAL_OR_IMPROVING</constructionHeuristicPickEarlyType-->
> </constructionHeuristic>
>
> <localSearch>
> <termination>
>
<terminationCompositionStyle>OR</terminationCompositionStyle>
>
<maximumSecondsSpend>3600</maximumSecondsSpend>
>
<scoreAttained>0hard/0soft</scoreAttained>
> </termination>
> <unionMoveSelector>
> <changeMoveSelector>
> <valueSelector>
>
<planningVariableName>period</planningVariableName>
> </valueSelector>
> </changeMoveSelector>
> <changeMoveSelector>
> <valueSelector>
>
<planningVariableName>spector</planningVariableName>
> </valueSelector>
> </changeMoveSelector>
> <changeMoveSelector>
> <valueSelector>
>
<planningVariableName>type</planningVariableName>
> </valueSelector>
> </changeMoveSelector>
> <swapMoveSelector>
> </swapMoveSelector>
> </unionMoveSelector>
>
> <acceptor>
>
<planningEntityTabuSize>7</planningEntityTabuSize>
> </acceptor>
> <forager>
>
<minimalAcceptedSelection>1000</minimalAcceptedSelection>
> </forager>
> </localSearch>
>
></solver>
>
> Any thoughts on what I'm doing wrong?
>
>Thanks
>
>Michiel
>
>-----------------
>http://www.codessentials.com - Your essential software, for free!
>Follow us at http://twitter.com/#!/Codessentials
>
>
>_______________________________________________
rules-users mailing list rules-users(a)lists.jboss.org https://lists.jboss.org/mailman/listinfo/rules-users
13 years, 2 months
Anyone Using Scorecards in a Spreadsheet?
by Steven Núñez
Hello Droolers,
Is anyone out there using scorecard spreadsheets? I'm trying to, ideally, import a PMML scorecard model, but in lieu of that can export a spreadsheet from the modeling tool and massage that. Trouble is I can't find anything in the 5.5 docos that describe the format that the spreadsheet is supposed to be in.
Does anyone have any pointers to the scorecard spreadsheet format?
Regards,
- SteveN
13 years, 2 months
Re: [rules-users] Bomb when calling Drools with PKG containing a process
by David Shields OpenCDS
Problem resolved. I inadvertently left a Maven Dependency pointing to jBPM
5.3 instead of 5.4.
From: David Shields OpenCDS [mailto:david.shields@opencds.org]
Sent: Tuesday, January 08, 2013 7:42 AM
To: rules-users(a)lists.jboss.org
Subject: Bomb when calling Drools with PKG containing a process
I have been trying to upgrade our application to Drools 5.5 from Drools 5.4.
I rebuilt several knowledgeBases containing processes with Drools 5.5, but I
can't get them to run. I can get a simple DRL file that does not reference
any processes to run just fine. Both the DRL and the KBs use
statelessSessions. The program has been used for a couple years, and has
been modified to run with Drools 5.1.1, 5.3, 5.4, and now 5.5, and has been
supporting processes since Drools 5.3 / jBPM 5.2.
Here is the bomb that I get:
OpenCDS call to Drools.execute failed with error: Unexpected exception
executing action
org.jbpm.process.instance.event.DefaultSignalManager$SignalAction@5cd5a2a9
org.drools.common.AbstractWorkingMemory:executeQueuedActions:995
org.drools.common.DefaultAgenda:fireNextItem:1239
org.drools.common.DefaultAgenda:fireAllRules:1456
org.drools.common.AbstractWorkingMemory:fireAllRules:710
org.drools.common.AbstractWorkingMemory:fireAllRules:674
org.drools.impl.StatefulKnowledgeSessionImpl:fireAllRules:230
org.drools.impl.StatelessKnowledgeSessionImpl:execute:278
org.opencds.service.drools.v55.DroolsAdapter:getOneResponse:370
org.opencds.dss.evaluate.EvaluationImpl:evaluate:169
org.opencds.service.TestEvaluationImpl:main:156
org.omg.dss.DSSRuntimeExceptionFault: OpenCDS call to Drools.execute failed
with error: Unexpected exception executing action
org.jbpm.process.instance.event.DefaultSignalManager$SignalAction@5cd5a2a9
executeQueuedActions
fireNextItem
fireAllRules
fireAllRules
fireAllRules
fireAllRules
execute
getOneResponse
evaluate
main
I have single-stepped through the code with Eclipse, but I can't quite
figure out what is wrong with my KBs. They ran just fine on Drools 5.4
(although there was a memory leak in Drools with that version), and the only
thing I changed was to populate the "probability" value on the BPMN-Diagram
(because it wouldn't validate without it).
The program builds a command list, and executes it with the following:
ExecutionResults results = null;
try {
results =
statelessKnowledgeSession.execute(CommandFactory.newBatchExecution((cmds)));
} catch (Exception e) {
String err = "OpenCDS call to Drools.execute failed with error:
" + e.getMessage();
log.error(err);
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
String detail = elements[i].getClassName() + ":" +
elements[i].getMethodName() + ":" + elements[i].getLineNumber();
log.error(detail);
err += "\n" + elements[i].getMethodName();
}
throw new DSSRuntimeExceptionFault(err);
}
Has anybody seen this error before?
Thanks for any ideas or suggestions!
-- des
13 years, 2 months
Stateless session dis-associating listeners after first execute call. Bug or a feature?
by Michal Bali
Hello,
I am using a stateless session. First I add an agenda event listener. When
I first call session.execute(Itelable) all works as expected. However when
I call it the second time (without adding the listener again) the listener
does not seem to be called at all.
However note that when I call session.getAgendaEventListeners() the event
listener is always there.
IMHO I am guessing that the 'dispose' method that is called behind the
scenes possibly dis-associates the event listener.
I've tested this with 5.5.Final. BTW This worked fine with Drools 5.0. I
haven't checked later versions.
I wonder is this a bug or a feature?
Isolated test case is attached.
Thank you.
Best regards,
Michal
13 years, 2 months