Getting data from a relational database
by rtanikella
Hi,
I am using Drools Server 5.4.0.Final as a web application deployed on JBoss
AS 7.1.1.Final, and Guvnor 5.4.0.Final for authoring/managing the business
rules.
I need to get data from a relational database (and eventually any other
external system) into the WHEN clause of any rule in the Guvnor, and, if
needed, be able to insert that data into the working memory via the THEN
clause. What is the best approach in achieving this? If there are any
examples or samples, please point them out.
Thanks,
Ramgopal Tanikella
--
View this message in context: http://drools.46999.n3.nabble.com/Getting-data-from-a-relational-database...
Sent from the Drools: User forum mailing list archive at Nabble.com.
12 years, 8 months
Could not execute Rules getting NPE
by Smurfs
Hi
I am new to Drools. I am using a maven project to connect to guvnor and
execute the rules.
pom.xml
-----------
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>5.5.0.Final</version>
</dependency>
Code
-----
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
KnowledgeAgent ruleAgent =
KnowledgeAgentFactory.newKnowledgeAgent("/Guvnor.properties");
System.out.println(ruleAgent.getKnowledgeBase().getFactType("org.sample","NumberTest"));
KnowledgeBase ruleBase = ruleAgent.getKnowledgeBase();
System.out.println(ruleBase.getFactType("org.sample","NumberTest"));
FactType factType = ruleBase.getFactType("org.sample",
"NumberTest");
Object obj = factType.newInstance();
factType.set(obj, "numberone", 2);
factType.set(obj, "numbertwo", 1);
StatefulKnowledgeSession workingMemory =
ruleBase.newStatefulKnowledgeSession();
workingMemory.insert(obj);
workingMemory.fireAllRules();
System.out.println(factType.get(obj, "message"));
}
I am getting the null pointer exception as below:
null
Exception in thread "main" java.lang.NullPointerException
at com.test.drools.guvnor.App.main(App.java:44)
I know, that many people has raised this issue, can anyone know why it is
causing the issue?
Thanks
Smurfs
--
View this message in context: http://drools.46999.n3.nabble.com/Could-not-execute-Rules-getting-NPE-tp4...
Sent from the Drools: User forum mailing list archive at Nabble.com.
12 years, 8 months
Please help me on hibernate-meet-drools
by Hong Ju
Hi,
I would like Drools to save my POJO objects as Hibernate Entities so that I can see my POJO objects as db tables in my database.
These are my relevant files:
1. ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
xmlns:util="http://www.springframework.org/schema/util" xmlns:drools="http://drools.org/schema/drools-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://drools.org/schema/drools-spring
drools-spring.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="dataSourceH2"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:tcp://localhost/~/hibernateExample" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceH2" />
<property name="persistenceUnitName" value="stewardcareH2" />
<!-- The persistenceXmlLocation needs to be set so that the application will
not incorrectly use the test version. See:
http://stackoverflow.com/a/2949496 -->
<property name="persistenceXmlLocation" value="META-INF/persistence.xml" />
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<drools:grid-node id="CAREEngineNode" />
<drools:kstore id="CAREKnowledgeStore" />
<drools:kbase id="CAREEngineKBase" node="CAREEngineNode">
<drools:configuration>
<drools:assert-behavior mode="EQUALITY" />
</drools:configuration>
<drools:resources>
<drools:resource type="DRL" source="classpath:lily.drl" />
</drools:resources>
</drools:kbase>
</beans>
2. persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:orm="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd
http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd">
<persistence-unit name="stewardcareH2" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>org.drools.persistence.info.SessionInfo</class>
<class>org.jbpm.persistence.processinstance.ProcessInstanceInfo</class>
<class>org.drools.persistence.info.WorkItemInfo</class>
<class>com.mkyong.stock.Stock</class>
<class>com.mkyong.stock.StockDailyRecord</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.max_fetch_depth" value="3" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.autocommit" value="true" />
<!-- <property name="hibernate.transaction.manager_lookup_class" value= "org.hibernate.transaction.BTMTransactionManagerLookup"/> -->
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.BitronixJtaPlatform"/>
</properties>
</persistence-unit>
</persistence>
3. Rule file:
package com.mlyong.stock
//list any import classes here.
import com.mkyong.stock.Stock;
//declare any global variables here
rule "My First Rule"
when
$stock: Stock(stockCode == "123")//conditions
then
System.out.println("lily"); //actions
end
4. Java code:
public static void main(String[] args) throws Exception {
System.out.println("Hibernate one to many (Annotation)");
// Session session = HibernateUtil.getSessionFactory().openSession();
// session.beginTransaction();
context = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT_XML);
KnowledgeStoreService kstore = (KnowledgeStoreService) context.getBean("CAREKnowledgeStore");
Environment env = KnowledgeBaseFactory.newEnvironment();
env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, context.getBean("entityManagerFactory"));
BitronixTransactionManager transactionManager= TransactionManagerServices.getTransactionManager();
try {
UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
ut.begin();
// transactionManager.begin();
env.set( EnvironmentName.TRANSACTION_MANAGER, transactionManager);
env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{
new JPAPlaceholderResolverStrategy(env),
new SerializablePlaceholderResolverStrategy
(ClassObjectMarshallingStrategyAcceptor.DEFAULT)});
session = kstore.newStatefulKnowledgeSession((KnowledgeBase)context.getBean("CAREEngineKBase"), null, env);
Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("Lily");
session.insert(stock);
StockDailyRecord stockDailyRecords = new StockDailyRecord();
stockDailyRecords.setPriceOpen(new Float("1.2"));
stockDailyRecords.setPriceClose(new Float("1.1"));
stockDailyRecords.setPriceChange(new Float("10.0"));
stockDailyRecords.setVolume(3000000L);
stockDailyRecords.setDate(new Date());
stockDailyRecords.setStock(stock);
stock.getStockDailyRecords().add(stockDailyRecords);
session.insert(stockDailyRecords);
ut.commit();
System.out.println("Done");
} catch (SecurityException | IllegalStateException | RollbackException
| HeuristicMixedException | HeuristicRollbackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I can create tables in db, but there is data saved in the tables. Does anyone know what I am missing here?
Thank you so much in advance,
Hong Lily Ju
Software Engineer
hong.ju(a)steward.org<mailto:derrick.smith@steward.org>
Steward Heath Care
[Description: cid:image001.png@01CD0DC1.C0D81BD0]
Office: 781-375-3034
Cell: 781-801-9313
12 years, 8 months
Complex DSL constraints to fact
by Sean Su
I do not know if anyone has run into the following scenario. If yes, what
is the solution.
We are following the Drools DSL instruction for "adding constraints to the
fact":
[when]There is a Cheese with=Cheese()
[when]- age is less than {age}=age<{age}
[when]- type is '{type}'=type=='{type}'
[when]- country equal to '{country}'=country=='{country}'
However, Our fact is more complicated than just any Cheese(). We want to
look for all cheeses that follow certain constraints and then count them.
So our first line which defines the fact would be something like this:
[when]There are at least {number} cheese=java.util.Collection(
size>{number} ) from collect ( Cheese())
[when]- age is less than {age}=age<{age}
[when]- type is '{type}'=type=='{type}'
[when]- country equal to '{country}'=country=='{country}'
I am hoping that the "additional" constraints defined after "-" will be
added to Cheese(). However, under Guvnor version 5.5, they are added into
the first (), in this case, it is the Collection (size>{number}).
To be more specific, when adding "age is less than {age}" after "There are
at least {number} cheese", the DRL generated becomes:
java.util.Collection( size>{number}, age<{age} ) from collect ( Cheese())
while what I want is:
java.util.Collection( size>{number} ) from collect ( Cheese(age<{age}))
Is this something Drools DSL and Guvnor can't support at all at this time?
or there is something I am not using correctly?
Thanks in advance.
Sean
12 years, 8 months
Drools Server fails starting when reading brl rules from Guvnor
by gfalco77
Hello Community,
I'm having trouble with the integration of Drools Camel Server and Guvnor..
Version 5.5.0
I've created a JAR which contains POJO and used it in Guvnor to create a BRL
rule (in the future will be created by not technical people)..
The problem is that when I start the drools server , it complains that it
cannot find the class Message defined in the Import of the Rules..
Below the configuration of the Knowledge-servics.xml
<drools:grid-node id="node1" />
<drools:resource-change-scanner id="res-scanner1" interval="15"
enabled="true" />
<drools:kbase id="kbase1" node="node1" />
<drools:kagent id="kagent1" kbase="kbase1" new-instance="false">
<drools:resources>
<drools:resource type="PKG"
source="http://localhost:8082/guvnor/org.drools.guvnor.Guvnor/package/<mypackage>/LATEST"
basic-authentication="enabled" username="admin"
password="admin" />
</drools:resources>
</drools:kagent>
<drools:ksession id="ksession1" type="stateless" kbase="kbase1"
node="node1" />
This is my rule in Guvnor
package mypackage
import mypackage.model.Message
rule "first"
dialect "mvel"
when
Message( text == "a" )
then
Message fact0 = new Message();
fact0.setText( "b" );
insert( fact0 );
end
--
View this message in context: http://drools.46999.n3.nabble.com/Drools-Server-fails-starting-when-readi...
Sent from the Drools: User forum mailing list archive at Nabble.com.
12 years, 8 months
Persisted stateful sessions and knowledge base changes (revisited)
by dunnlow
I have an Drools 5.5. application that persists a stateful session to a
database. While it was running, I made some changes to my rules (via
Guvnor). When I restarted my application it was no longer able to reload
the persisted session:
*Caused by: java.lang.RuntimeException: Unable to load session snapshot at
org.drools.persistence.session.JPASessionMarshallingHelper.loadSnapshot(JPASessionMarshallingHelper.java:96)*
FYI, I do not use a KnowledgeAgent because I have a lot of events coming in
and I only want to load the knowledgebase changes when my application starts
up.
About two years ago, a discussion occurred on this topic
(https://community.jboss.org/message/628586#628586). Unfortunately, I
haven't seen much since but I am hoping that someone has concurred this
problem (elegantly or otherwise).
Is there a common way to solve this problem? Given a persisted session what
are the steps needed to migrate it to the new ruleset?
Thanks for any insight.
-J
--
View this message in context: http://drools.46999.n3.nabble.com/Persisted-stateful-sessions-and-knowled...
Sent from the Drools: User forum mailing list archive at Nabble.com.
12 years, 8 months
Problem with PKG from guvnor
by calcacuervo
Hi Guys,
I am having a problem using Drools 5.5.
Basically, I have a ksession in stream mode.
I have a rule with an event, like this
when
myfact: EventA( main > 21 ) over window:length (1)
myfact2 : EventA( main <= 21 , this before myfact ) over window:length (2)
I also use a KnowledgeAgent and apply a changeset.
If I declare this rule directly from the changeset, as a Classpath resource,
with resource type DRL, it seems to work fine (the kbase compiles!).
But If I have the rule in a guvnor package, and I put the PKG link in my
changeset, I am getting an error:
Caused by: java.lang.NullPointerException
at
org.drools.base.evaluators.BeforeEvaluatorDefinition$BeforeEvaluator.getInterval(BeforeEvaluatorDefinition.java:268)
[drools-core-5.5.0.Final.jar:5.5.0.Final]
at
org.drools.rule.constraint.EvaluatorConstraint.getInterval(EvaluatorConstraint.java:100)
[drools-core-5.5.0.Final.jar:5.5.0.Final]
at
org.drools.reteoo.builder.BuildUtils.gatherTemporalRelationships(BuildUtils.java:326)
[drools-core-5.5.0.Final.jar:5.5.0.Final]
at
org.drools.reteoo.builder.BuildUtils.calculateTemporalDistance(BuildUtils.java:292)
[drools-core-5.5.0.Final.jar:5.5.0.Final]
at
org.drools.reteoo.builder.ReteooRuleBuilder.addRule(ReteooRuleBuilder.java:119)
[drools-core-5.5.0.Final.jar:5.5.0.Final]
at org.drools.reteoo.ReteooBuilder.addRule(ReteooBuilder.java:113)
[drools-core-5.5.0.Final.jar:5.5.0.Final]
at org.drools.reteoo.ReteooRuleBase.addRule(ReteooRuleBase.java:445)
[drools-core-5.5.0.Final.jar:5.5.0.Final]
It seems that that getOperator() is null in this evaluation:
if ( this.getOperator().isNegated() ) {
I debugged a bit, and it seems the evaluator comes in serialized from
guvnor's package.But in case of getting directly the classpath resource, it
compiles the package and it gets the real operator ok (Operator = 'before')
Do you have any idea of why it could be happening? May I be doing something
wrong? Is this a bug in guvnor?
Thanks in advance!
Demian
--
View this message in context: http://drools.46999.n3.nabble.com/Problem-with-PKG-from-guvnor-tp4025687....
Sent from the Drools: User forum mailing list archive at Nabble.com.
12 years, 8 months
Using KnowledgeAgent with loadStatefulKnowledgeSession?
by dunnlow
Hello, I am using jBPM 5.4 with persistence and have long running processes
and make make changes to the knowledge base periodically (via drools guvnor
5.5). I use JPAKnowlegeService.loadStatefulKnowledgeSession(...) to retrieve
my existing knowledge session. When I make a change to the rule base (via
drools 5.5 guvnor) and then try to restart my application (and reload the
knowledgesession) I get an exception:
java.lang.RuntimeException: Unable to load session snapshot
at
org.drools.persistence.SessionMarshallingHelper.loadSnapshot(SessionMarshallingHelper.java:96)
.
.
Caused by: java.lang.NullPointerException
at
org.drools.common.Scheduler$activationTimerInputMarshaller.deserialize(Scheduler.java:230)
I am NOT currently using a KnowledgeAgent and it seems like it should be
able to help. I have read over the drools forum and this one and see a few
discussions on the topic (https://community.jboss.org/thread/172818) but
nothing concrete to put me on the right path.
The examples with knowledgeagent I have found assume that I am calling:
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
Can someone please show/explain how I can reload an existing persisted
knowledgesession given changes in my knowledge base? (for example, can the
knowledgeagent and JPAKnowlegeService.loadStatefulKnowledgeSession be used
together? If not, do I load the existing statefulknowledgesession by some
other means?)
I am using Spring-based configuration. Thanks for any insight.
-J
--
View this message in context: http://drools.46999.n3.nabble.com/Using-KnowledgeAgent-with-loadStatefulK...
Sent from the Drools: User forum mailing list archive at Nabble.com.
12 years, 8 months