[jboss-svn-commits] JBL Code SVN: r35655 - in labs/jbossrules/trunk: drools-container/drools-spring/src/main/java/org/drools/container/spring/beans and 18 other directories.
jboss-svn-commits at lists.jboss.org
jboss-svn-commits at lists.jboss.org
Thu Oct 21 14:17:21 EDT 2010
Author: salaboy21
Date: 2010-10-21 14:17:19 -0400 (Thu, 21 Oct 2010)
New Revision: 35655
Added:
labs/jbossrules/trunk/drools-flow-persistence-jpa/src/main/resources/
labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/marshaller/
labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/marshaller/JPAPlaceholderResolverStrategy.java
Removed:
labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/StringPersistedVariable.java
labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/StringVariablePersister.java
labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/VariablePersistenceStrategy.java
labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/VariablePersistenceStrategyFactory.java
Modified:
labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/DynamicRulesTest.java
labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MarshallingTest.java
labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/SerializationHelper.java
labs/jbossrules/trunk/drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/KnowledgeBaseBeanFactory.java
labs/jbossrules/trunk/drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/StatefulKnowledgeSessionBeanFactory.java
labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/VariablePersistenceStrategyTest.java
labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/timer/MyDroolsBean.java
labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/META-INF/persistence.xml
labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/org/drools/container/spring/beans/persistence/VariablePersistenceStrategyProcess.rf
labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/org/drools/container/spring/beans/persistence/beansVarPersistence.xml
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/SessionConfiguration.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/impl/EnvironmentFactory.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/impl/KnowledgeBaseFactoryServiceImpl.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/DefaultMarshaller.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/InputMarshaller.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/MarshallerReaderContext.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/MarshallerWriteContext.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/ObjectMarshallingStrategyStore.java
labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/OutputMarshaller.java
labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/marshalling/impl/AbstractProcessInstanceMarshaller.java
labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/marshalling/impl/ProcessInstanceMarshaller.java
labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/process/ProcessBaseFactoryService.java
labs/jbossrules/trunk/drools-flow-persistence-jpa/src/main/java/org/drools/persistence/processinstance/ProcessInstanceInfo.java
labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/java/org/drools/persistence/session/VariablePersistenceStrategyTest.java
labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/META-INF/persistence.xml
labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VPSProcessWithWorkItems.rf
labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VariablePersistenceStrategyProcess.rf
labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VariablePersistenceStrategyProcessTypeChange.rf
labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/WorkItemInfo.java
Log:
JBRULES-2741: Unify the Marshalling Strategies for Process Variables and Session's Snapshots
- unify the Marshalling Strategies. Now the Process variables are handle in the same way that the objects inside the working memory. If you need to externalize the Process Variables you can add another strategy into the Environment (EnvironmentName.OBJECT_MARSHALLING_STRATEGIES)
Modified: labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/DynamicRulesTest.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/DynamicRulesTest.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/DynamicRulesTest.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -16,7 +16,6 @@
package org.drools.integrationtests;
-import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.io.IOException;
@@ -63,10 +62,15 @@
import org.drools.definitions.impl.KnowledgePackageImp;
import org.drools.event.rule.ActivationCreatedEvent;
import org.drools.event.rule.AgendaEventListener;
+import org.drools.impl.EnvironmentFactory;
import org.drools.io.ResourceFactory;
-import org.drools.marshalling.MarshallerFactory;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.IdentityPlaceholderResolverStrategy;
import org.drools.reteoo.ReteooRuleBase;
import org.drools.rule.Package;
+import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.rule.WorkingMemoryEntryPoint;
@@ -614,8 +618,10 @@
Collection<KnowledgePackage> kpkgs = SerializationHelper.serializeObject( kbuilder.getKnowledgePackages() );
kbase.addKnowledgePackages( kpkgs );
kbase = SerializationHelper.serializeObject( kbase );
-
- StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
+ Environment env = EnvironmentFactory.newEnvironment();
+ env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{
+ new IdentityPlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)});
+ StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(null, env);
List results = new ArrayList();
ksession.setGlobal( "results",
results );
@@ -642,7 +648,7 @@
kbase = SerializationHelper.serializeObject( kbase );
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
false );
results = (List) ksession.getGlobal( "results" );
@@ -668,7 +674,7 @@
kbase = SerializationHelper.serializeObject( kbase );
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
false );
results = (List) ksession.getGlobal( "results" );
Modified: labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MarshallingTest.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MarshallingTest.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MarshallingTest.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -58,6 +58,8 @@
import org.drools.marshalling.MarshallerFactory;
import org.drools.marshalling.ObjectMarshallingStrategy;
import org.drools.marshalling.ObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.IdentityPlaceholderResolverStrategy;
import org.drools.marshalling.impl.RuleBaseNodes;
import org.drools.reteoo.ObjectTypeNode;
import org.drools.reteoo.ReteooStatefulSession;
@@ -65,6 +67,8 @@
import org.drools.rule.MapBackedClassLoader;
import org.drools.rule.Package;
import org.drools.rule.Rule;
+import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.spi.GlobalResolver;
@@ -1670,24 +1674,25 @@
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
-
+ Environment env = EnvironmentFactory.newEnvironment();
+ env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{
+ new IdentityPlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)});
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
- StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
+ StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(null, env);
List list = new ArrayList();
ksession.setGlobal( "list",
list );
// add a person, no cheese
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
true );
Person bobba = new Person( "bobba fet",
50 );
ksession.insert( bobba );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 1,
@@ -1695,13 +1700,13 @@
// add another person, no cheese
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
Person darth = new Person( "darth vadar",
200 );
ksession.insert( darth );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 2,
@@ -1709,13 +1714,13 @@
// add cheese
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
Cheese stilton = new Cheese( "stilton",
5 );
ksession.insert( stilton );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 2,
@@ -1723,11 +1728,11 @@
// remove cheese
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.retract( ksession.getFactHandle( stilton ) );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 4,
@@ -1735,11 +1740,11 @@
// put 2 cheeses back in
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.insert( stilton );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
Cheese brie = new Cheese( "brie",
18 );
@@ -1760,7 +1765,7 @@
// now remove a person, should be no change
ksession.retract( ksession.getFactHandle( bobba ) );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 4,
@@ -1769,7 +1774,7 @@
//removal remaining cheese, should increase by one, as one person left
ksession.retract( ksession.getFactHandle( brie ) );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 5,
@@ -1799,24 +1804,27 @@
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
-
+ Environment env = EnvironmentFactory.newEnvironment();
+ env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{
+ new IdentityPlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)});
+
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
- StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
+ StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(null, env);
List list = new ArrayList();
ksession.setGlobal( "list",
list );
// add a person, no cheese
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
Person bobba = new Person( "bobba fet",
50 );
ksession.insert( bobba );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 0,
@@ -1824,13 +1832,13 @@
// add another person, no cheese
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
Person darth = new Person( "darth vadar",
200 );
ksession.insert( darth );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 0,
@@ -1838,13 +1846,13 @@
// add cheese
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
Cheese stilton = new Cheese( "stilton",
5 );
ksession.insert( stilton );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 2,
@@ -1852,11 +1860,11 @@
// remove cheese
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.retract( ksession.getFactHandle( stilton ) );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 2,
@@ -1864,11 +1872,11 @@
// put 2 cheeses back in
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.insert( stilton );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
Cheese brie = new Cheese( "brie",
18 );
@@ -1880,7 +1888,7 @@
// now remove a cheese, should be no change
ksession.retract( ksession.getFactHandle( stilton ) );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 4,
@@ -1889,7 +1897,7 @@
// now remove a person, should be no change
ksession.retract( ksession.getFactHandle( bobba ) );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 4,
@@ -1898,7 +1906,7 @@
//removal remaining cheese, no
ksession.retract( ksession.getFactHandle( brie ) );
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.fireAllRules();
assertEquals( 4,
@@ -1906,7 +1914,7 @@
// put one cheese back in, with one person should increase by one
ksession = getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
true );
ksession.insert( stilton );
ksession.fireAllRules();
Modified: labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -93,7 +93,6 @@
import org.drools.Win;
import org.drools.WorkingMemory;
import org.drools.Cheesery.Maturity;
-import org.drools.Order.OrderStatus;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderConfiguration;
import org.drools.builder.KnowledgeBuilderError;
@@ -132,18 +131,23 @@
import org.drools.event.WorkingMemoryEventListener;
import org.drools.facttemplates.Fact;
import org.drools.facttemplates.FactTemplate;
+import org.drools.impl.EnvironmentFactory;
import org.drools.impl.StatefulKnowledgeSessionImpl;
import org.drools.io.ResourceFactory;
import org.drools.lang.DrlDumper;
import org.drools.lang.descr.AttributeDescr;
import org.drools.lang.descr.PackageDescr;
import org.drools.lang.descr.RuleDescr;
-import org.drools.marshalling.MarshallerFactory;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.IdentityPlaceholderResolverStrategy;
import org.drools.reteoo.LeftTuple;
import org.drools.reteoo.ReteooWorkingMemory;
import org.drools.rule.InvalidRulePackage;
import org.drools.rule.Package;
import org.drools.rule.builder.dialect.java.JavaDialectConfiguration;
+import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
import org.drools.runtime.Globals;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.rule.WorkingMemoryEntryPoint;
@@ -1703,7 +1707,10 @@
RuleBase ruleBase = getRuleBase();
ruleBase.addPackage( pkg );
ruleBase = SerializationHelper.serializeObject( ruleBase );
- StatefulSession session = ruleBase.newStatefulSession();
+ Environment env = EnvironmentFactory.newEnvironment();
+ env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{
+ new IdentityPlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)});
+ StatefulSession session = ruleBase.newStatefulSession(null, env);
final List list = new ArrayList();
session.setGlobal( "list",
@@ -1728,7 +1735,7 @@
state.setState( "finished" );
StatefulKnowledgeSession ksesion = SerializationHelper.getSerialisedStatefulKnowledgeSession( new StatefulKnowledgeSessionImpl( (ReteooWorkingMemory) session ),
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
false );
ksesion.fireAllRules();
@@ -1929,13 +1936,15 @@
Package pkg = builder.getPackage();
ruleBase.addPackage( pkg );
ruleBase = SerializationHelper.serializeObject( ruleBase );
-
- StatefulSession session = ruleBase.newStatefulSession();
+ Environment env = EnvironmentFactory.newEnvironment();
+ env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{
+ new IdentityPlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)});
+ StatefulSession session = ruleBase.newStatefulSession(null, env);
session.insert( cell1 );
FactHandle cellHandle = session.insert( cell );
StatefulKnowledgeSession ksesion = SerializationHelper.getSerialisedStatefulKnowledgeSession( new StatefulKnowledgeSessionImpl( (ReteooWorkingMemory) session ),
- MarshallerFactory.newIdentityMarshallingStrategy(),
+ // MarshallerFactory.newIdentityMarshallingStrategy(),
false );
ksesion.fireAllRules();
Modified: labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/SerializationHelper.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/SerializationHelper.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/SerializationHelper.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -5,7 +5,6 @@
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
-import java.io.OutputStream;
import org.drools.RuleBase;
import org.drools.SessionConfiguration;
@@ -16,6 +15,8 @@
import org.drools.marshalling.Marshaller;
import org.drools.marshalling.MarshallerFactory;
import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
import org.drools.runtime.StatefulKnowledgeSession;
/**
@@ -94,31 +95,24 @@
return session2;
}
- public static StatefulKnowledgeSession getSerialisedStatefulKnowledgeSession(StatefulKnowledgeSession ksession,
- boolean dispose) throws Exception {
+
- return getSerialisedStatefulKnowledgeSession( ksession,
- MarshallerFactory.newSerializeMarshallingStrategy(),
- dispose );
- }
-
public static StatefulKnowledgeSession getSerialisedStatefulKnowledgeSession(StatefulKnowledgeSession ksession,
- ObjectMarshallingStrategy strategy,
boolean dispose) throws Exception {
Marshaller marshaller = MarshallerFactory.newMarshaller( ksession.getKnowledgeBase(),
- new ObjectMarshallingStrategy[]{strategy} );
+ (ObjectMarshallingStrategy[])ksession.getEnvironment().get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES) );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
marshaller.marshall( bos,
ksession );
final byte[] b1 = bos.toByteArray();
bos.close();
-
+
ByteArrayInputStream bais = new ByteArrayInputStream( b1 );
StatefulKnowledgeSession ksession2 = marshaller.unmarshall( bais,
new SessionConfiguration(),
- EnvironmentFactory.newEnvironment() );
+ ksession.getEnvironment());
bais.close();
bos = new ByteArrayOutputStream();
Modified: labs/jbossrules/trunk/drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/KnowledgeBaseBeanFactory.java
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/KnowledgeBaseBeanFactory.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/KnowledgeBaseBeanFactory.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -178,6 +178,6 @@
public void setNode(ExecutionNode executionNode) {
this.node = executionNode;
- }
+ }
}
Modified: labs/jbossrules/trunk/drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/StatefulKnowledgeSessionBeanFactory.java
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/StatefulKnowledgeSessionBeanFactory.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/StatefulKnowledgeSessionBeanFactory.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -16,7 +16,6 @@
package org.drools.container.spring.beans;
-import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
@@ -24,9 +23,10 @@
import org.drools.KnowledgeBaseFactory;
import org.drools.SessionConfiguration;
import org.drools.command.Command;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.SerializablePlaceholderResolverStrategy;
import org.drools.persistence.jpa.JPAKnowledgeService;
-import org.drools.persistence.processinstance.VariablePersistenceStrategyFactory;
-import org.drools.persistence.processinstance.persisters.VariablePersister;
import org.drools.runtime.CommandExecutor;
import org.drools.runtime.Environment;
import org.drools.runtime.EnvironmentName;
@@ -64,20 +64,16 @@
}
if ( jpaConfiguration != null ) {
- if ( !jpaConfiguration.getVariablePersisters().isEmpty() ) {
- for ( Map.Entry<String, Class< ? extends VariablePersister>> entry : jpaConfiguration.getVariablePersisters().entrySet() ) {
- VariablePersistenceStrategyFactory.getVariablePersistenceStrategy().setPersister( entry.getKey(),
- entry.getValue().getName() );
- }
- }
+
Environment env = KnowledgeBaseFactory.newEnvironment();
env.set( EnvironmentName.ENTITY_MANAGER_FACTORY,
jpaConfiguration.getEntityManagerFactory() );
env.set( EnvironmentName.TRANSACTION_MANAGER,
jpaConfiguration.getPlatformTransactionManager() );
+ env.set( EnvironmentName.OBJECT_MARSHALLING_STRATEGIES,
+ new ObjectMarshallingStrategy[]{ new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)} );
-
if ( jpaConfiguration.getId() >= 0 ) {
ksession = JPAKnowledgeService.loadStatefulKnowledgeSession( jpaConfiguration.getId(),
getKbase(),
@@ -106,7 +102,7 @@
private int id = -1;
- private Map<String, Class< ? extends VariablePersister>> variablePersisters;
+
public EntityManagerFactory getEntityManagerFactory() {
return this.emf;
@@ -132,15 +128,6 @@
this.id = id;
}
- public Map<String, Class< ? extends VariablePersister>> getVariablePersisters() {
- if ( variablePersisters == null ) {
- variablePersisters = new HashMap<String, Class< ? extends VariablePersister>>();
- }
- return variablePersisters;
- }
-
- public void setVariablePersisters(Map<String, Class< ? extends VariablePersister>> variablePersisters) {
- this.variablePersisters = variablePersisters;
- }
+
}
}
Deleted: labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/StringPersistedVariable.java
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/StringPersistedVariable.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/StringPersistedVariable.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -1,49 +0,0 @@
-/**
- * Copyright 2010 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-
-package org.drools.container.spring.beans.persistence;
-
-import javax.persistence.Entity;
-
-import org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo;
-
-/**
- *
- * @author salaboy
- * @author baunax at gmail.com
- */
- at Entity
-public class StringPersistedVariable extends VariableInstanceInfo {
-
- private String string;
-
- public StringPersistedVariable() {
- }
-
- public String getString() {
- return string;
- }
-
- public void setString(String string) {
- this.string = string;
- }
-
-}
Deleted: labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/StringVariablePersister.java
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/StringVariablePersister.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/StringVariablePersister.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -1,89 +0,0 @@
-/**
- * Copyright 2010 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.drools.container.spring.beans.persistence;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.persistence.EntityManager;
-
-import org.drools.persistence.processinstance.persisters.JPAVariablePersister;
-import org.drools.persistence.processinstance.persisters.VariablePersister;
-import org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo;
-import org.drools.runtime.Environment;
-import org.drools.runtime.EnvironmentName;
-
-/**
- *
- * @author salaboy
- */
-public class StringVariablePersister
- implements
- VariablePersister {
-
- public VariableInstanceInfo persistExternalVariable(String name,
- Object o,
- VariableInstanceInfo oldValue,
- Environment env) {
- if ( o == null || (oldValue != null && oldValue.getPersister().equals( "" )) ) {
- return null;
- }
- try {
- boolean newVariable = false;
- EntityManager em = (EntityManager) env.get( EnvironmentName.CMD_SCOPED_ENTITY_MANAGER );
- StringPersistedVariable result = null;
- if ( oldValue instanceof StringPersistedVariable ) {
- result = (StringPersistedVariable) oldValue;
- }
- if ( result == null ) {
- result = new StringPersistedVariable();
-
- newVariable = true;
- }
- result.setPersister( this.getClass().getName() );
- result.setName( name );
- // entity might have changed, updating info
- result.setString( (String) o );
- if ( newVariable ) {
- em.persist( result );
- } else {
- em.merge( result );
- }
- System.out.println( "Saving StringPersistedVariable id=" + result.getId() + " string=" + result.getString() );
- return result;
- } catch ( Throwable t ) {
- Logger.getLogger( JPAVariablePersister.class.getName() ).log( Level.SEVERE,
- null,
- t );
- throw new RuntimeException( "Could not persist external variable",
- t );
- }
-
- }
-
- public Object getExternalPersistedVariable(VariableInstanceInfo variableInstanceInfo, Environment env) {
- env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
- if (variableInstanceInfo == null) {
- return null;
- }
- return ((StringPersistedVariable) variableInstanceInfo).getString();
- }
-}
Modified: labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/VariablePersistenceStrategyTest.java
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/VariablePersistenceStrategyTest.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/VariablePersistenceStrategyTest.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -16,6 +16,12 @@
package org.drools.container.spring.beans.persistence;
+import javax.naming.NamingException;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.SystemException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -25,14 +31,21 @@
import java.util.List;
import java.util.Map;
import java.util.Properties;
+import javax.naming.InitialContext;
+import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
+import javax.transaction.UserTransaction;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.base.MapGlobalResolver;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.SerializablePlaceholderResolverStrategy;
import org.drools.persistence.jpa.JPAKnowledgeService;
import org.drools.persistence.jpa.KnowledgeStoreService;
+import org.drools.persistence.jpa.marshaller.JPAPlaceholderResolverStrategy;
import org.drools.runtime.Environment;
import org.drools.runtime.EnvironmentName;
import org.drools.runtime.StatefulKnowledgeSession;
@@ -115,6 +128,8 @@
env.set( EnvironmentName.ENTITY_MANAGER_FACTORY, ctx.getBean( "myEmf" ));
env.set( EnvironmentName.TRANSACTION_MANAGER, txManager);
env.set( EnvironmentName.GLOBALS, new MapGlobalResolver() );
+ env.set( EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{new JPAPlaceholderResolverStrategy(env),
+ new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)} );
final KnowledgeStoreService kstore = ( KnowledgeStoreService ) ctx.getBean( "kstore1" );
final KnowledgeBase kbRollback = ( KnowledgeBase ) ctx.getBean( "kbRollback" );
@@ -216,7 +231,20 @@
}
@Test
- public void testPersistenceVariables() {
+ public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
+ MyEntity myEntity = new MyEntity( "This is a test Entity with annotation in fields" );
+ MyEntityMethods myEntityMethods = new MyEntityMethods( "This is a test Entity with annotations in methods" );
+ MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields( "This is a test Entity with annotations in fields and without accesors methods" ) ;
+ MyVariableSerializable myVariableSerializable = new MyVariableSerializable( "This is a test SerializableObject" );
+ EntityManager em = ((EntityManagerFactory)ctx.getBean( "myEmf" )).createEntityManager();
+
+ em.getTransaction().begin();
+ em.persist(myEntity);
+ em.persist(myEntityMethods);
+ em.persist(myEntityOnlyFields);
+ em.getTransaction().commit();
+ em.close();
+
log.info( "---> get bean jpaSingleSessionCommandService" );
StatefulKnowledgeSession service = (StatefulKnowledgeSession) ctx.getBean( "jpaSingleSessionCommandService" );
@@ -228,13 +256,13 @@
parameters.put( "x",
"SomeString" );
parameters.put( "y",
- new MyEntity( "This is a test Entity with annotation in fields" ) );
+ myEntity);
parameters.put( "m",
- new MyEntityMethods( "This is a test Entity with annotations in methods" ) );
+ myEntityMethods);
parameters.put( "f",
- new MyEntityOnlyFields( "This is a test Entity with annotations in fields and without accesors methods" ) );
+ myEntityOnlyFields);
parameters.put( "z",
- new MyVariableSerializable( "This is a test SerializableObject" ) );
+ myVariableSerializable);
WorkflowProcessInstance processInstance = (WorkflowProcessInstance) service.startProcess( "com.sample.ruleflow", parameters );
log.info( "Started process instance {}",
processInstance.getId() );
@@ -246,14 +274,18 @@
EntityManagerFactory emf = (EntityManagerFactory) ctx.getBean( "myEmf" );
- List< ? > result = emf.createEntityManager().createQuery( "select i from VariableInstanceInfo i" ).getResultList();
- assertEquals( 5,
- result.size() );
+// List< ? > result = emf.createEntityManager().createQuery( "select i from VariableInstanceInfo i" ).getResultList();
+// assertEquals( 5,
+// result.size() );
log.info( "### Retrieving process instance ###" );
Environment env = KnowledgeBaseFactory.newEnvironment();
- env.set( EnvironmentName.ENTITY_MANAGER_FACTORY, ctx.getBean( "myEmf" ));
- env.set( EnvironmentName.TRANSACTION_MANAGER, ctx.getBean( "txManager" ));
+ env.set( EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
+ env.set( EnvironmentName.TRANSACTION_MANAGER, ctx.getBean( "txManager" ));
+ env.set( EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{
+ // new JPAPlaceholderResolverStrategy(env),
+ new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)
+ });
KnowledgeStoreService kstore = ( KnowledgeStoreService ) ctx.getBean( "kstore1" );
KnowledgeBase kbase1 = ( KnowledgeBase ) ctx.getBean( "kbase1" );
Modified: labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/timer/MyDroolsBean.java
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/timer/MyDroolsBean.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/test/java/org/drools/container/spring/timer/MyDroolsBean.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -77,6 +77,7 @@
environment.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
environment.set(EnvironmentName.TRANSACTION_MANAGER, txm);
environment.set(EnvironmentName.GLOBALS, new MapGlobalResolver());
+
return environment;
}
Modified: labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/META-INF/persistence.xml
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/META-INF/persistence.xml 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/META-INF/persistence.xml 2010-10-21 18:17:19 UTC (rev 35655)
@@ -13,16 +13,12 @@
-->
<class>org.drools.persistence.session.SessionInfo</class>
<class>org.drools.persistence.processinstance.ProcessInstanceInfo</class>
- <class>org.drools.persistence.processinstance.variabletypes.JPAPersistedVariable</class>
- <class>org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo</class>
- <class>org.drools.persistence.processinstance.variabletypes.SerializablePersistedVariable</class>
- <class>org.drools.persistence.processinstance.WorkItemInfo</class>
+ <class>org.drools.persistence.processinstance.WorkItemInfo</class>
<!-- my persistent variables -->
<class>org.drools.container.spring.beans.persistence.MyEntity</class>
<class>org.drools.container.spring.beans.persistence.MyEntityMethods</class>
<class>org.drools.container.spring.beans.persistence.MyEntityOnlyFields</class>
- <class>org.drools.container.spring.beans.persistence.StringPersistedVariable</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<!--property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/-->
Modified: labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/org/drools/container/spring/beans/persistence/VariablePersistenceStrategyProcess.rf
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/org/drools/container/spring/beans/persistence/VariablePersistenceStrategyProcess.rf 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/org/drools/container/spring/beans/persistence/VariablePersistenceStrategyProcess.rf 2010-10-21 18:17:19 UTC (rev 35655)
@@ -8,6 +8,8 @@
<imports>
<import name="org.drools.container.spring.beans.persistence.MyEntity" />
<import name="org.drools.container.spring.beans.persistence.MyVariableSerializable" />
+ <import name="javax.persistence.EntityManager" />
+ <import name="org.drools.runtime.EnvironmentName" />
</imports>
<variables>
<variable name="x" >
@@ -66,7 +68,13 @@
System.out.println("y = " + y);
System.out.println("z = " + z);
kcontext.setVariable("a", "Some new String");
-kcontext.setVariable("b", new MyEntity("This is a new test Entity"));
+
+EntityManager em = (EntityManager) kcontext.getKnowledgeRuntime().getEnvironment().get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
+MyEntity myNewEntity = new MyEntity("This is a new test Entity");
+em.persist(myNewEntity);
+
+
+kcontext.setVariable("b", myNewEntity);
kcontext.setVariable("c", new MyVariableSerializable("This is a new test SerializableObject"));</action>
</actionNode>
<humanTask id="7" name="Human Task" x="445" y="20" width="80" height="40" >
@@ -99,7 +107,11 @@
System.out.println("b = " + b);
System.out.println("c = " + c);
kcontext.setVariable("a", "Some changed String");
-kcontext.setVariable("b", new MyEntity("This is a changed test Entity"));
+EntityManager em = (EntityManager) kcontext.getKnowledgeRuntime().getEnvironment().get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
+MyEntity myNewEntity = new MyEntity("This is a changed test Entity");
+em.persist(myNewEntity);
+
+kcontext.setVariable("b", myNewEntity);
kcontext.setVariable("c", new MyVariableSerializable("This is a changed test SerializableObject"));</action>
</actionNode>
<humanTask id="9" name="Human Task" x="550" y="94" width="100" height="48" >
Modified: labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/org/drools/container/spring/beans/persistence/beansVarPersistence.xml
===================================================================
--- labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/org/drools/container/spring/beans/persistence/beansVarPersistence.xml 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-container/drools-spring/src/test/resources/org/drools/container/spring/beans/persistence/beansVarPersistence.xml 2010-10-21 18:17:19 UTC (rev 35655)
@@ -42,11 +42,7 @@
<drools:jpa-persistence>
<drools:transaction-manager ref="txManager" />
<drools:entity-manager-factory ref="myEmf" />
- <drools:variable-persisters>
- <drools:persister for-class="javax.persistence.Entity" implementation="org.drools.persistence.processinstance.persisters.JPAVariablePersister"/>
- <drools:persister for-class="java.lang.String" implementation="org.drools.container.spring.beans.persistence.StringVariablePersister"/>
- <drools:persister for-class="java.io.Serializable" implementation="org.drools.persistence.processinstance.persisters.SerializableVariablePersister"/>
- </drools:variable-persisters>
+
</drools:jpa-persistence>
</drools:configuration>
</drools:ksession>
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/SessionConfiguration.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/SessionConfiguration.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/SessionConfiguration.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -27,6 +27,9 @@
import org.drools.command.CommandService;
import org.drools.core.util.ConfFileUtils;
import org.drools.core.util.StringUtils;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.SerializablePlaceholderResolverStrategy;
import org.drools.process.instance.WorkItemManagerFactory;
import org.drools.runtime.Environment;
import org.drools.runtime.KnowledgeSessionConfiguration;
@@ -82,13 +85,13 @@
private CommandService commandService;
private transient ClassLoader classLoader;
-
+
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject( chainedProperties );
out.writeBoolean( immutable );
out.writeBoolean( keepReference );
out.writeObject( clockType );
- out.writeObject( queryListener );
+ out.writeObject( queryListener );
}
@SuppressWarnings("unchecked")
@@ -98,7 +101,7 @@
immutable = in.readBoolean();
keepReference = in.readBoolean();
clockType = (ClockType) in.readObject();
- queryListener = (QueryListenerOption) in.readObject();
+ queryListener = (QueryListenerOption) in.readObject();
}
/**
@@ -436,5 +439,5 @@
public QueryListenerOption getQueryListenerOption() {
return this.queryListener;
}
-
+
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -65,6 +65,8 @@
import org.drools.event.process.ProcessEventListener;
import org.drools.event.process.ProcessEventManager;
import org.drools.management.DroolsManagementAgent;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.marshalling.impl.ObjectMarshallingStrategyStore;
import org.drools.reteoo.EntryPointNode;
import org.drools.reteoo.InitialFactImpl;
import org.drools.reteoo.LIANodePropagation;
@@ -221,6 +223,8 @@
private AtomicLong lastIdleTimestamp;
private InternalProcessRuntime processRuntime;
+
+ private transient ObjectMarshallingStrategyStore marshallingStore;
// ------------------------------------------------------------
// Constructors
@@ -1955,5 +1959,13 @@
this.partitionManager.releaseTasks();
}
}
+
+ public ObjectMarshallingStrategyStore getObjectMarshallingStrategyStore(){
+ if(this.marshallingStore == null){
+ this.marshallingStore = new ObjectMarshallingStrategyStore(
+ (ObjectMarshallingStrategy[])this.environment.get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES));
+ }
+ return this.marshallingStore;
+ }
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/impl/EnvironmentFactory.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/impl/EnvironmentFactory.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/impl/EnvironmentFactory.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -16,14 +16,20 @@
package org.drools.impl;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.SerializablePlaceholderResolverStrategy;
import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
public class EnvironmentFactory {
private static ThreadLocal<Environment> environment = new ThreadLocal<Environment>();
public static Environment newEnvironment() {
- return new EnvironmentImpl();
+ Environment env = new EnvironmentImpl();
+ env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT)});
+ return env;
// Environment environment = EnvironmentFactory.environment.get();
// if (environment == null) {
// environment = new EnvironmentImpl();
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/impl/KnowledgeBaseFactoryServiceImpl.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/impl/KnowledgeBaseFactoryServiceImpl.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/impl/KnowledgeBaseFactoryServiceImpl.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -64,6 +64,6 @@
}
public Environment newEnvironment() {
- return new EnvironmentImpl(); //EnvironmentFactory.newEnvironment();
+ return EnvironmentFactory.newEnvironment();//new EnvironmentImpl(); //
}
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/DefaultMarshaller.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/DefaultMarshaller.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/DefaultMarshaller.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -24,7 +24,6 @@
import org.drools.KnowledgeBaseFactory;
import org.drools.RuleBaseConfiguration;
import org.drools.SessionConfiguration;
-import org.drools.StatefulSession;
import org.drools.common.InternalRuleBase;
import org.drools.common.InternalWorkingMemory;
import org.drools.concurrent.CommandExecutor;
@@ -81,9 +80,10 @@
MarshallerReaderContext context = new MarshallerReaderContext( stream,
(InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase,
RuleBaseNodes.getNodeMap( (InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase ),
- this.strategyStore,
+ null,
this.marshallingConfig.isMarshallProcessInstances(),
- this.marshallingConfig.isMarshallWorkItems() );
+ this.marshallingConfig.isMarshallWorkItems() ,
+ environment);
int id = ((ReteooRuleBase) ((KnowledgeBaseImpl) this.kbase).ruleBase).nextWorkingMemoryCounter();
RuleBaseConfiguration conf = ((ReteooRuleBase) ((KnowledgeBaseImpl) this.kbase).ruleBase).getConfiguration();
@@ -109,9 +109,10 @@
MarshallerReaderContext context = new MarshallerReaderContext( stream,
(InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase,
RuleBaseNodes.getNodeMap( (InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase ),
- this.strategyStore,
+ null,
this.marshallingConfig.isMarshallProcessInstances(),
- marshallingConfig.isMarshallWorkItems() );
+ marshallingConfig.isMarshallWorkItems() ,
+ ksession.getEnvironment());
InputMarshaller.readSession( (ReteooStatefulSession) ((StatefulKnowledgeSessionImpl)ksession).session,
context );
@@ -128,9 +129,9 @@
(InternalRuleBase) ((InternalKnowledgeBase) kbase).getRuleBase(),
(InternalWorkingMemory) ((StatefulKnowledgeSessionImpl) session).session,
RuleBaseNodes.getNodeMap( (InternalRuleBase) ((InternalKnowledgeBase) kbase).getRuleBase() ),
- this.strategyStore,
+ ((StatefulKnowledgeSessionImpl)session).session.getObjectMarshallingStrategyStore(),
this.marshallingConfig.isMarshallProcessInstances(),
- this.marshallingConfig.isMarshallWorkItems() );
+ this.marshallingConfig.isMarshallWorkItems(), session.getEnvironment());
OutputMarshaller.writeSession( context );
context.close();
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/InputMarshaller.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/InputMarshaller.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/InputMarshaller.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -26,6 +26,7 @@
import org.drools.RuntimeDroolsException;
import org.drools.SessionConfiguration;
import org.drools.base.ClassObjectType;
+import org.drools.common.AbstractWorkingMemory;
import org.drools.common.AgendaItem;
import org.drools.common.BaseNode;
import org.drools.common.BinaryHeapQueueAgendaGroup;
@@ -801,7 +802,7 @@
pc );
}
- public static WorkItem readWorkItem(MarshallerReaderContext context, boolean includeVariables) throws IOException {
+ public static WorkItem readWorkItem(MarshallerReaderContext context) throws IOException {
ObjectInputStream stream = context.stream;
WorkItemImpl workItem = new WorkItemImpl();
@@ -810,26 +811,31 @@
workItem.setName( stream.readUTF() );
workItem.setState( stream.readInt() );
- if(includeVariables){
- int nbParameters = stream.readInt();
-
- for ( int i = 0; i < nbParameters; i++ ) {
- String name = stream.readUTF();
- try {
- Object value = stream.readObject();
- workItem.setParameter( name,
- value );
- } catch ( ClassNotFoundException e ) {
- throw new IllegalArgumentException( "Could not reload parameter " + name );
+ //WorkItem Paramaters
+ int nbVariables = stream.readInt();
+ if (nbVariables > 0) {
+
+ for (int i = 0; i < nbVariables; i++) {
+ String name = stream.readUTF();
+ try {
+ int index = stream.readInt();
+ ObjectMarshallingStrategy strategy = context.resolverStrategyFactory.getStrategy(index);
+
+ Object value = strategy.read(stream);
+ workItem.setParameter(name, value);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalArgumentException(
+ "Could not reload variable " + name);
+ }
+ }
}
- }
- }
+
+
+
return workItem;
}
- public static WorkItem readWorkItem(MarshallerReaderContext context) throws IOException {
- return readWorkItem(context, true);
- }
+
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/MarshallerReaderContext.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/MarshallerReaderContext.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/MarshallerReaderContext.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -30,9 +30,12 @@
import org.drools.common.InternalFactHandle;
import org.drools.common.InternalRuleBase;
import org.drools.common.InternalWorkingMemory;
+import org.drools.marshalling.ObjectMarshallingStrategy;
import org.drools.reteoo.LeftTuple;
import org.drools.reteoo.RightTuple;
import org.drools.rule.EntryPoint;
+import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
import org.drools.runtime.KnowledgeRuntime;
import org.drools.spi.PropagationContext;
@@ -55,17 +58,18 @@
public final boolean marshalProcessInstances;
public final boolean marshalWorkItems;
-
+ public final Environment env;
public MarshallerReaderContext(InputStream stream,
InternalRuleBase ruleBase,
Map<Integer, BaseNode> sinks,
- ObjectMarshallingStrategyStore resolverStrategyFactory) throws IOException {
+ ObjectMarshallingStrategyStore resolverStrategyFactory, Environment env) throws IOException {
this( stream,
ruleBase,
sinks,
resolverStrategyFactory,
true,
- true );
+ true,
+ env );
}
public MarshallerReaderContext(InputStream stream,
@@ -73,7 +77,7 @@
Map<Integer, BaseNode> sinks,
ObjectMarshallingStrategyStore resolverStrategyFactory,
boolean marshalProcessInstances,
- boolean marshalWorkItems) throws IOException {
+ boolean marshalWorkItems, Environment env) throws IOException {
super( stream );
this.stream = this;
this.ruleBase = ruleBase;
@@ -83,9 +87,15 @@
this.terminalTupleMap = new HashMap<Integer, LeftTuple>();
this.entryPoints = new HashMap<String, EntryPoint>();
this.propagationContexts = new HashMap<Long, PropagationContext>();
- this.resolverStrategyFactory = resolverStrategyFactory;
+ if(resolverStrategyFactory == null){
+ this.resolverStrategyFactory = new ObjectMarshallingStrategyStore((ObjectMarshallingStrategy[])env.get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES));
+ }
+ else{
+ this.resolverStrategyFactory = resolverStrategyFactory;
+ }
this.marshalProcessInstances = marshalProcessInstances;
this.marshalWorkItems = marshalWorkItems;
+ this.env = env;
}
@Override
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/MarshallerWriteContext.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/MarshallerWriteContext.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/MarshallerWriteContext.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -29,7 +29,10 @@
import org.drools.common.BaseNode;
import org.drools.common.InternalRuleBase;
import org.drools.common.InternalWorkingMemory;
+import org.drools.marshalling.ObjectMarshallingStrategy;
import org.drools.reteoo.LeftTuple;
+import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
public class MarshallerWriteContext extends ObjectOutputStream {
public final MarshallerWriteContext stream;
@@ -45,19 +48,22 @@
public final boolean marshalProcessInstances;
public final boolean marshalWorkItems;
+ public final Environment env;
+
public MarshallerWriteContext(OutputStream stream,
InternalRuleBase ruleBase,
InternalWorkingMemory wm,
Map<Integer, BaseNode> sinks,
- ObjectMarshallingStrategyStore resolverStrategyFactory) throws IOException {
+ ObjectMarshallingStrategyStore resolverStrategyFactory, Environment env) throws IOException {
this( stream,
ruleBase,
wm,
sinks,
resolverStrategyFactory,
true,
- true );
+ true ,
+ env);
}
public MarshallerWriteContext(OutputStream stream,
@@ -66,18 +72,29 @@
Map<Integer, BaseNode> sinks,
ObjectMarshallingStrategyStore resolverStrategyFactory,
boolean marshalProcessInstances,
- boolean marshalWorkItems) throws IOException {
+ boolean marshalWorkItems,
+ Environment env) throws IOException {
super( stream );
this.stream = this;
this.ruleBase = ruleBase;
this.wm = wm;
this.sinks = sinks;
+ if(this.objectMarshallingStrategyStore == null){
+ this.objectMarshallingStrategyStore = new ObjectMarshallingStrategyStore((ObjectMarshallingStrategy[])env.get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES));
+ }
+ else{
+ this.objectMarshallingStrategyStore = resolverStrategyFactory;
+ }
- this.objectMarshallingStrategyStore = resolverStrategyFactory;
-
this.terminalTupleMap = new IdentityHashMap<LeftTuple, Integer>();
this.marshalProcessInstances = marshalProcessInstances;
this.marshalWorkItems = marshalWorkItems;
+ this.env = env;
+
}
+
+
+
+
}
\ No newline at end of file
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/ObjectMarshallingStrategyStore.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/ObjectMarshallingStrategyStore.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/ObjectMarshallingStrategyStore.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -24,7 +24,7 @@
public class ObjectMarshallingStrategyStore {
private ObjectMarshallingStrategy[] strategiesList;
- ObjectMarshallingStrategyStore(ObjectMarshallingStrategy[] strategiesList) {
+ public ObjectMarshallingStrategyStore(ObjectMarshallingStrategy[] strategiesList) {
this.strategiesList = strategiesList;
}
Modified: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/OutputMarshaller.java
===================================================================
--- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/OutputMarshaller.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/marshalling/impl/OutputMarshaller.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -18,7 +18,9 @@
import java.io.IOException;
import java.io.ObjectOutputStream;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
@@ -744,26 +746,39 @@
stream.writeUTF( pc.getEntryPoint().getEntryPointId() );
}
- public static void writeWorkItem(MarshallerWriteContext context, WorkItem workItem) throws IOException {
- writeWorkItem(context, workItem, true);
- }
-
+
public static void writeWorkItem(MarshallerWriteContext context,
- WorkItem workItem, boolean includeVariables) throws IOException {
+ WorkItem workItem) throws IOException {
ObjectOutputStream stream = context.stream;
stream.writeLong(workItem.getId());
stream.writeLong(workItem.getProcessInstanceId());
stream.writeUTF(workItem.getName());
stream.writeInt(workItem.getState());
- if (includeVariables) {
- Map<String, Object> parameters = workItem.getParameters();
- stream.writeInt(parameters.size());
- for (Map.Entry<String, Object> entry : parameters.entrySet()) {
- stream.writeUTF(entry.getKey());
- stream.writeObject(entry.getValue());
- }
- }
+ //Work Item Parameters
+ Map<String, Object> parameters = workItem.getParameters();
+ Collection<Object> notNullValues = new ArrayList<Object>();
+ for(Object value: parameters.values()){
+ if(value != null){
+ notNullValues.add(value);
+ }
+ }
+
+ stream.writeInt(notNullValues.size());
+ for (String key : parameters.keySet()) {
+ Object object = parameters.get(key);
+ if(object != null){
+ stream.writeUTF(key);
+ int index = context.objectMarshallingStrategyStore.getStrategy(object);
+ stream.writeInt(index);
+ ObjectMarshallingStrategy strategy = context.objectMarshallingStrategyStore.getStrategy(index);
+ if(strategy.accept(object)){
+ strategy.write(stream, object);
+ }
+ }
+
+ }
+
}
}
Modified: labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/marshalling/impl/AbstractProcessInstanceMarshaller.java
===================================================================
--- labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/marshalling/impl/AbstractProcessInstanceMarshaller.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/marshalling/impl/AbstractProcessInstanceMarshaller.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -26,10 +26,13 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.drools.common.AbstractWorkingMemory;
import org.drools.common.InternalRuleBase;
import org.drools.common.InternalWorkingMemory;
import org.drools.definition.process.Process;
+import org.drools.marshalling.MarshallerFactory;
+import org.drools.marshalling.ObjectMarshallingStrategy;
import org.drools.process.core.Context;
import org.drools.process.core.context.exclusive.ExclusiveGroup;
import org.drools.process.core.context.swimlane.SwimlaneContext;
@@ -68,38 +71,18 @@
ProcessInstanceMarshaller {
// Output methods
+
+
public void writeProcessInstance(MarshallerWriteContext context,
ProcessInstance processInstance) throws IOException {
- writeProcessInstance(context, processInstance, true);
- }
- public void writeProcessInstance(MarshallerWriteContext context,
- ProcessInstance processInstance, boolean includeVariables) throws IOException {
-
WorkflowProcessInstanceImpl workFlow = (WorkflowProcessInstanceImpl) processInstance;
ObjectOutputStream stream = context.stream;
stream.writeLong(workFlow.getId());
stream.writeUTF(workFlow.getProcessId());
stream.writeInt(workFlow.getState());
stream.writeLong(workFlow.getNodeInstanceCounter());
- if (includeVariables) {
- VariableScopeInstance variableScopeInstance = (VariableScopeInstance) workFlow.getContextInstance(VariableScope.VARIABLE_SCOPE);
- Map<String, Object> variables = variableScopeInstance.getVariables();
- List<String> keys = new ArrayList<String>(variables.keySet());
- Collections.sort(keys,
- new Comparator<String>() {
- public int compare(String o1,
- String o2) {
- return o1.compareTo(o2);
- }
- });
- stream.writeInt(keys.size());
- for (String key : keys) {
- stream.writeUTF(key);
- stream.writeObject(variables.get(key));
- }
- }
SwimlaneContextInstance swimlaneContextInstance = (SwimlaneContextInstance) workFlow.getContextInstance(SwimlaneContext.SWIMLANE_SCOPE);
if (swimlaneContextInstance != null) {
@@ -144,6 +127,50 @@
}
}
}
+
+ VariableScopeInstance variableScopeInstance = (VariableScopeInstance) workFlow.getContextInstance(VariableScope.VARIABLE_SCOPE);
+ Map<String, Object> variables = variableScopeInstance.getVariables();
+ List<String> keys = new ArrayList<String>(variables.keySet());
+ Collection<Object> values = variables.values();
+
+ Collections.sort(keys,
+ new Comparator<String>() {
+
+ public int compare(String o1,
+ String o2) {
+ return o1.compareTo(o2);
+ }
+ });
+ // Process Variables
+ // - Number of non null Variables = nonnullvariables.size()
+ // For Each Variable
+ // - Variable Key
+ // - Marshalling Strategy Index
+ // - Marshalled Object
+
+ Collection<Object> notNullValues = new ArrayList<Object>();
+ for(Object value: values){
+ if(value != null){
+ notNullValues.add(value);
+ }
+ }
+
+ stream.writeInt(notNullValues.size());
+ for (String key : keys) {
+ Object object = variables.get(key);
+ if(object != null){
+ stream.writeUTF(key);
+ int index = context.objectMarshallingStrategyStore.getStrategy(object);
+ stream.writeInt(index);
+ ObjectMarshallingStrategy strategy = context.objectMarshallingStrategyStore.getStrategy(index);
+ if(strategy.accept(object)){
+ strategy.write(stream, object);
+ }
+ }
+
+ }
+
+
}
public void writeNodeInstance(MarshallerWriteContext context,
@@ -345,11 +372,9 @@
}
// Input methods
+
+
public ProcessInstance readProcessInstance(MarshallerReaderContext context) throws IOException {
- return readProcessInstance(context, true);
- }
-
- public ProcessInstance readProcessInstance(MarshallerReaderContext context, boolean includeVariables) throws IOException {
ObjectInputStream stream = context.stream;
InternalRuleBase ruleBase = context.ruleBase;
InternalWorkingMemory wm = context.wm;
@@ -365,24 +390,8 @@
processInstance.setState(stream.readInt());
long nodeInstanceCounter = stream.readLong();
processInstance.setKnowledgeRuntime(wm.getKnowledgeRuntime());
- if (includeVariables) {
- int nbVariables = stream.readInt();
- if (nbVariables > 0) {
- Context variableScope = ((org.drools.process.core.Process) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
- VariableScopeInstance variableScopeInstance = (VariableScopeInstance) processInstance.getContextInstance(variableScope);
- for (int i = 0; i < nbVariables; i++) {
- String name = stream.readUTF();
- try {
- Object value = stream.readObject();
- variableScopeInstance.setVariable(name, value);
- } catch (ClassNotFoundException e) {
- throw new IllegalArgumentException(
- "Could not reload variable " + name);
- }
- }
- }
- }
+
int nbSwimlanes = stream.readInt();
if (nbSwimlanes > 0) {
Context swimlaneContext = ((org.drools.process.core.Process) process).getDefaultContext(SwimlaneContext.SWIMLANE_SCOPE);
@@ -412,6 +421,30 @@
exclusiveGroupInstance.addNodeInstance(nodeInstance);
}
}
+ // Process Variables
+ // - Number of Variables = keys.size()
+ // For Each Variable
+ // - Variable Key
+ // - Marshalling Strategy Index
+ // - Marshalled Object
+ int nbVariables = stream.readInt();
+ if (nbVariables > 0) {
+ Context variableScope = ((org.drools.process.core.Process) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
+ VariableScopeInstance variableScopeInstance = (VariableScopeInstance) processInstance.getContextInstance(variableScope);
+ for (int i = 0; i < nbVariables; i++) {
+ String name = stream.readUTF();
+ try {
+ int index = stream.readInt();
+ ObjectMarshallingStrategy strategy = context.resolverStrategyFactory.getStrategy(index);
+
+ Object value = strategy.read(stream);
+ variableScopeInstance.setVariable(name, value);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalArgumentException(
+ "Could not reload variable " + name);
+ }
+ }
+ }
processInstance.internalSetNodeInstanceCounter(nodeInstanceCounter);
if (wm != null) {
Modified: labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/marshalling/impl/ProcessInstanceMarshaller.java
===================================================================
--- labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/marshalling/impl/ProcessInstanceMarshaller.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/marshalling/impl/ProcessInstanceMarshaller.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -40,16 +40,12 @@
public void writeProcessInstance(MarshallerWriteContext context,
ProcessInstance processInstance) throws IOException;
- public void writeProcessInstance(MarshallerWriteContext context,
- ProcessInstance processInstance, boolean includeVariables) throws IOException;
public void writeNodeInstance(MarshallerWriteContext context,
NodeInstance nodeInstance) throws IOException;
public ProcessInstance readProcessInstance(MarshallerReaderContext context)
throws IOException;
- public ProcessInstance readProcessInstance(MarshallerReaderContext context,
- boolean includeVariables) throws IOException;
public NodeInstance readNodeInstance(MarshallerReaderContext context,
NodeInstanceContainer nodeInstanceContainer,
Modified: labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/process/ProcessBaseFactoryService.java
===================================================================
--- labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/process/ProcessBaseFactoryService.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-core/src/main/java/org/drools/process/ProcessBaseFactoryService.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -24,7 +24,7 @@
import org.drools.RuleBaseConfiguration;
import org.drools.RuleBaseFactory;
import org.drools.SessionConfiguration;
-import org.drools.impl.EnvironmentImpl;
+import org.drools.impl.EnvironmentFactory;
import org.drools.runtime.Environment;
import org.drools.runtime.KnowledgeSessionConfiguration;
@@ -65,6 +65,6 @@
}
public Environment newEnvironment() {
- return new EnvironmentImpl(); //EnvironmentFactory.newEnvironment();
+ return EnvironmentFactory.newEnvironment();//new EnvironmentImpl(); //EnvironmentFactory.newEnvironment();
}
}
Modified: labs/jbossrules/trunk/drools-flow-persistence-jpa/src/main/java/org/drools/persistence/processinstance/ProcessInstanceInfo.java
===================================================================
--- labs/jbossrules/trunk/drools-flow-persistence-jpa/src/main/java/org/drools/persistence/processinstance/ProcessInstanceInfo.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-persistence-jpa/src/main/java/org/drools/persistence/processinstance/ProcessInstanceInfo.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -5,17 +5,11 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collection;
import java.util.Date;
-import java.util.HashMap;
import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
import java.util.Set;
-import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -24,8 +18,6 @@
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
-import javax.persistence.MapKey;
-import javax.persistence.OneToMany;
import javax.persistence.PreUpdate;
import javax.persistence.Transient;
import javax.persistence.Version;
@@ -38,18 +30,9 @@
import org.drools.marshalling.impl.MarshallerWriteContext;
import org.drools.marshalling.impl.ProcessInstanceMarshaller;
import org.drools.marshalling.impl.ProcessMarshallerRegistry;
-import org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo;
-import org.drools.process.core.context.variable.VariableScope;
-import org.drools.process.instance.ContextInstance;
-import org.drools.process.instance.ContextInstanceContainer;
-import org.drools.process.instance.ContextableInstance;
-import org.drools.process.instance.context.variable.VariableScopeInstance;
import org.drools.process.instance.impl.ProcessInstanceImpl;
import org.drools.runtime.Environment;
-import org.drools.runtime.process.NodeInstance;
-import org.drools.runtime.process.NodeInstanceContainer;
import org.drools.runtime.process.ProcessInstance;
-import org.drools.runtime.process.WorkflowProcessInstance;
import org.drools.workflow.instance.impl.WorkflowProcessInstanceImpl;
import org.hibernate.annotations.CollectionOfElements;
@@ -88,12 +71,7 @@
ProcessInstance processInstance;
private @Transient
Environment env;
- @OneToMany(cascade = CascadeType.ALL)
- @JoinColumn(name = "processInstanceId")
- @MapKey(name = "name")
- private Map<String, VariableInstanceInfo> variables = new HashMap<String, VariableInstanceInfo>();
- private boolean externalVariables = false;
-
+
protected ProcessInstanceInfo() {
}
@@ -148,14 +126,12 @@
MarshallerReaderContext context = new MarshallerReaderContext( bais,
(InternalRuleBase) ((InternalKnowledgeBase) kruntime.getKnowledgeBase()).getRuleBase(),
null,
- null );
+ null,
+ this.env
+ );
ProcessInstanceMarshaller marshaller = getMarshallerFromContext( context );
context.wm = ((StatefulKnowledgeSessionImpl) kruntime).getInternalWorkingMemory();
- processInstance = marshaller.readProcessInstance( context,
- !externalVariables );
- if ( externalVariables ) {
- restoreVariables();
- }
+ processInstance = marshaller.readProcessInstance(context);
context.close();
} catch ( IOException e ) {
e.printStackTrace();
@@ -166,60 +142,9 @@
return processInstance;
}
- private void restoreVariables() {
- for ( Map.Entry<String, VariableInstanceInfo> entry : variables.entrySet() ) {
- String[] variableHierarchy = entry.getKey().split( VARIABLE_SEPARATOR );
- // last one is variable name
- String variableName = variableHierarchy[variableHierarchy.length - 1];
- // other ones are parent ids
- List<Long> parentIds = new ArrayList<Long>();
- for ( int i = 0; i < variableHierarchy.length - 1; i++ ) {
- parentIds.add( Long.valueOf( variableHierarchy[i] ) );
- }
- restoreVariable( entry.getValue(),
- parentIds,
- variableName,
- (WorkflowProcessInstance) processInstance );
- }
- }
+
- private void restoreVariable(VariableInstanceInfo variableInfo,
- List<Long> parentIds,
- String variableName,
- NodeInstanceContainer nodeInstanceContainer) throws NumberFormatException {
- if ( parentIds.size() == 0 ) {
- if ( !(nodeInstanceContainer instanceof ContextableInstance) ) {
- throw new IllegalArgumentException( "Parent node instance is not a contextable instance: " + nodeInstanceContainer );
- }
- VariableScopeInstance variableScopeInstance = (VariableScopeInstance) ((ContextableInstance) nodeInstanceContainer).getContextInstance( VariableScope.VARIABLE_SCOPE );
- VariablePersistenceStrategy persistenceStrategy = VariablePersistenceStrategyFactory.getVariablePersistenceStrategy();
- Object value = persistenceStrategy.getVariable( variableInfo,
- this.env );
- System.out.println( ">>>>> Restoring variable " + variableName + " = " + value );
- variableScopeInstance.setVariable( variableName,
- value );
- } else {
- Long nodeInstanceId = parentIds.get( 0 );
- // find the node and get the variableScopeInstance and insert the
- // variable..
- Collection<NodeInstance> nodeInstances = nodeInstanceContainer.getNodeInstances();
- for ( NodeInstance nodeInstance : nodeInstances ) {
- if ( nodeInstance.getId() == nodeInstanceId ) {
- parentIds.remove( 0 );
- if ( !(nodeInstance instanceof NodeInstanceContainer) ) {
- throw new IllegalArgumentException( "Restoring variable " + variableName + " but node found is not a node instance container:" + nodeInstance );
- }
- restoreVariable( variableInfo,
- parentIds,
- variableName,
- (NodeInstanceContainer) nodeInstance );
- }
- return;
- }
- throw new IllegalArgumentException( "Could not find node instance " + nodeInstanceId + " in " + nodeInstanceContainer );
- }
- }
-
+
private ProcessInstanceMarshaller getMarshallerFromContext(MarshallerReaderContext context) throws IOException {
ObjectInputStream stream = context.stream;
String processInstanceType = stream.readUTF();
@@ -243,19 +168,16 @@
null,
null,
null,
- null );
+ null,
+ this.env );
String processType = ((ProcessInstanceImpl) processInstance).getProcess().getType();
saveProcessInstanceType( context,
processInstance,
processType );
ProcessInstanceMarshaller marshaller = ProcessMarshallerRegistry.INSTANCE.getMarshaller( processType );
- externalVariables = VariablePersistenceStrategyFactory.getVariablePersistenceStrategy().isEnabled();
- marshaller.writeProcessInstance( context,
- processInstance,
- !externalVariables );
- if ( externalVariables ) {
- variablesChanged = persistVariables();
- }
+
+ marshaller.writeProcessInstance( context,
+ processInstance);
context.close();
} catch ( IOException e ) {
throw new IllegalArgumentException( "IOException while storing process instance " + processInstance.getId() + ": " + e.getMessage() );
@@ -273,89 +195,7 @@
}
}
- private boolean persistVariables() {
- // Get Process Variables
- VariableScopeInstance variableScopeInstance = (VariableScopeInstance) ((WorkflowProcessInstanceImpl) this.processInstance).getContextInstance( VariableScope.VARIABLE_SCOPE );
- Map<String, Object> processVariables = variableScopeInstance.getVariables();
- Map<String, VariableInstanceInfo> newVariables = new HashMap<String, VariableInstanceInfo>();
- // persist process variables
- persist( processVariables,
- "",
- newVariables );
- // persist variables in nested variable scopes
- Collection<NodeInstance> nodeInstances = ((WorkflowProcessInstanceImpl) this.processInstance).getNodeInstances();
- if ( nodeInstances.size() > 0 ) {
- persistNodeVariables( nodeInstances,
- "",
- newVariables );
- }
- if ( newVariables.size() > 0 || this.variables.size() > 0 ) {
- // clear variables so unnecessary values are removed
- this.variables.clear();
- this.variables.putAll( newVariables );
- // TODO: how can I know that no variables were changed?
- return true;
- } else {
- return false;
- }
- }
- private void persist(Map<String, Object> variables,
- String prefix,
- Map<String, VariableInstanceInfo> newVariables) {
- VariablePersistenceStrategy persistenceStrategy = VariablePersistenceStrategyFactory.getVariablePersistenceStrategy();
- for ( Map.Entry<String, Object> entries : variables.entrySet() ) {
- String variableName = prefix + entries.getKey();
- Object value = entries.getValue();
- VariableInstanceInfo oldValue = this.variables.get( variableName );
- VariableInstanceInfo variable = persistenceStrategy.persistVariable( variableName,
- value,
- oldValue,
- this.env );
-
- if ( variable != null ) {
- System.out.println( "<<<<< Persisting variable " + variableName + " = " + value );
- newVariables.put( variableName,
- variable );
- } else {
- System.out.println( "<<<<< Variable " + variableName + " not persisted (value null)" );
- }
- }
- }
-
- private void persistNodeVariables(Collection<NodeInstance> nodeInstances,
- String parentPrefix,
- Map<String, VariableInstanceInfo> newVariables) {
- for ( NodeInstance nodeInstance : nodeInstances ) {
- String prefix = parentPrefix + nodeInstance.getId() + VARIABLE_SEPARATOR;
- if ( nodeInstance instanceof ContextInstanceContainer ) {
- List<ContextInstance> variableScopeInstances = ((ContextInstanceContainer) nodeInstance).getContextInstances( VariableScope.VARIABLE_SCOPE );
- if ( variableScopeInstances != null ) {
- for ( ContextInstance contextInstance : variableScopeInstances ) {
- VariableScopeInstance variableScopeInstance = (VariableScopeInstance) contextInstance;
- persist( variableScopeInstance.getVariables(),
- prefix,
- newVariables );
- }
- }
- }
- if ( nodeInstance instanceof NodeInstanceContainer ) {
- Collection<NodeInstance> nodeInstancesInsideTheContainer = ((NodeInstanceContainer) nodeInstance).getNodeInstances();
- persistNodeVariables( nodeInstancesInsideTheContainer,
- prefix,
- newVariables );
- }
- }
- }
-
- public Map<String, VariableInstanceInfo> getVariables() {
- return variables;
- }
-
- public void setVariables(Map<String, VariableInstanceInfo> variables) {
- this.variables = variables;
- }
-
@Override
public boolean equals(Object obj) {
if ( obj == null ) {
@@ -399,9 +239,7 @@
if ( this.env != other.env && (this.env == null || !this.env.equals( other.env )) ) {
return false;
}
- if ( this.variables != other.variables && (this.variables == null || !this.variables.equals( other.variables )) ) {
- return false;
- }
+
return true;
}
@@ -419,7 +257,6 @@
hash = 61 * hash + (this.eventTypes != null ? this.eventTypes.hashCode() : 0);
hash = 61 * hash + (this.processInstance != null ? this.processInstance.hashCode() : 0);
hash = 61 * hash + (this.env != null ? this.env.hashCode() : 0);
- hash = 61 * hash + (this.variables != null ? this.variables.hashCode() : 0);
return hash;
}
Modified: labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/java/org/drools/persistence/session/VariablePersistenceStrategyTest.java
===================================================================
--- labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/java/org/drools/persistence/session/VariablePersistenceStrategyTest.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/java/org/drools/persistence/session/VariablePersistenceStrategyTest.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -1,9 +1,14 @@
package org.drools.persistence.session;
+import javax.naming.NamingException;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.SystemException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
@@ -28,9 +33,6 @@
import org.drools.impl.InternalKnowledgeBase;
import org.drools.io.impl.ClassPathResource;
import org.drools.persistence.jpa.JPAKnowledgeService;
-import org.drools.persistence.processinstance.VariablePersistenceStrategyFactory;
-import org.drools.persistence.processinstance.persisters.JPAVariablePersister;
-import org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo;
import org.drools.process.core.Work;
import org.drools.process.core.context.variable.Variable;
import org.drools.process.core.datatype.impl.type.ObjectDataType;
@@ -60,6 +62,14 @@
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.resource.jdbc.PoolingDataSource;
+import javax.naming.InitialContext;
+import javax.persistence.EntityManager;
+import javax.transaction.UserTransaction;
+import org.drools.SessionConfiguration;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
+import org.drools.marshalling.impl.SerializablePlaceholderResolverStrategy;
+import org.drools.persistence.jpa.marshaller.JPAPlaceholderResolverStrategy;
public class VariablePersistenceStrategyTest {
@@ -83,13 +93,6 @@
"jdbc:h2:mem:mydb" );
ds1.init();
- VariablePersistenceStrategyFactory.getVariablePersistenceStrategy()
- .setPersister("javax.persistence.Entity",
- "org.drools.persistence.processinstance.persisters.JPAVariablePersister");
- VariablePersistenceStrategyFactory.getVariablePersistenceStrategy()
- .setPersister("java.io.Serializable",
- "org.drools.persistence.processinstance.persisters.SerializableVariablePersister");
-
emf = Persistence.createEntityManagerFactory("org.drools.persistence.jpa");
}
@@ -102,19 +105,17 @@
@Test
public void testExtendingInterfaceVariablePersistence(){
+ Environment env = createEnvironment();
String processId = "extendingInterfaceVariablePersistence";
String variableText = "my extending serializable variable text";
KnowledgeBase kbase = getKnowledgeBaseForExtendingInterfaceVariablePersistence(processId,
variableText);
- StatefulKnowledgeSession ksession = createSession( kbase );
+ StatefulKnowledgeSession ksession = createSession( kbase , env );
Map<String, Object> initialParams = new HashMap<String, Object>();
initialParams.put( "x", new MyVariableExtendingSerializable( variableText ) );
long processInstanceId = ksession.startProcess( processId, initialParams ).getId();
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
- List<?> variables = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
- Assert.assertEquals( 1, variables.size() );
-
long workItemId = TestWorkItemHandler.getInstance().getWorkItem().getId();
ksession.getWorkItemManager().completeWorkItem( workItemId, null );
@@ -175,28 +176,50 @@
}
@Test
- public void testPersistenceVariables() {
+ public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
+ MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
+ MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
+ MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods");
+ MyVariableSerializable myVariableSerializable = new MyVariableSerializable("This is a test SerializableObject");
+ EntityManager em = emf.createEntityManager();
+ UserTransaction utx = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
+ utx.begin();
+ em.joinTransaction();
+ em.persist(myEntity);
+ em.persist(myEntityMethods);
+ em.persist(myEntityOnlyFields);
+ utx.commit();
+ em.close();
+ Environment env = createEnvironment();
KnowledgeBase kbase = createKnowledgeBase( "VariablePersistenceStrategyProcess.rf" );
- StatefulKnowledgeSession ksession = createSession( kbase );
+ StatefulKnowledgeSession ksession = createSession( kbase, env );
+
+
+
+
logger.info("### Starting process ###");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("x", "SomeString");
- parameters.put("y", new MyEntity("This is a test Entity with annotation in fields"));
- parameters.put("m", new MyEntityMethods("This is a test Entity with annotations in methods"));
- parameters.put("f", new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods"));
- parameters.put("z", new MyVariableSerializable("This is a test SerializableObject"));
+ parameters.put("y", myEntity);
+ parameters.put("m", myEntityMethods);
+ parameters.put("f", myEntityOnlyFields);
+ parameters.put("z", myVariableSerializable);
long processInstanceId = ksession.startProcess( "com.sample.ruleflow", parameters ).getId();
TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
WorkItem workItem = handler.getWorkItem();
assertNotNull( workItem );
- List<?> result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
- assertEquals(5, result.size());
+ List<?> result = emf.createEntityManager().createQuery("select i from MyEntity i").getResultList();
+ assertEquals(1, result.size());
+ result = emf.createEntityManager().createQuery("select i from MyEntityMethods i").getResultList();
+ assertEquals(1, result.size());
+ result = emf.createEntityManager().createQuery("select i from MyEntityOnlyFields i").getResultList();
+ assertEquals(1, result.size());
logger.info("### Retrieving process instance ###");
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
WorkflowProcessInstance processInstance = (WorkflowProcessInstance)
ksession.getProcessInstance( processInstanceId );
assertNotNull( processInstance );
@@ -214,16 +237,10 @@
workItem = handler.getWorkItem();
assertNotNull( workItem );
- logger.info("### Retrieving variable instance infos ###");
- result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
- assertEquals(8, result.size());
- for (Object o: result) {
- assertTrue(VariableInstanceInfo.class.isAssignableFrom(o.getClass()));
- logger.info(o.toString());
- }
+
logger.info("### Retrieving process instance ###");
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase , env );
processInstance = (WorkflowProcessInstance)
ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
@@ -241,11 +258,9 @@
workItem = handler.getWorkItem();
assertNotNull(workItem);
- result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
- assertEquals(8, result.size());
-
+
logger.info("### Retrieving process instance ###");
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env);
processInstance = (WorkflowProcessInstance)
ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
@@ -263,35 +278,48 @@
workItem = handler.getWorkItem();
assertNull(workItem);
- result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
- //This was 6.. but I change it to 0 because all the variables will go away with the process instance..
- //we need to change that to leave the variables there???
- assertEquals(0, result.size());
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = (WorkflowProcessInstance)
ksession.getProcessInstance(processInstanceId);
assertNull(processInstance);
}
@Test
- public void testPersistenceVariablesWithTypeChange() {
+ public void testPersistenceVariablesWithTypeChange() throws NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
+ MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
+ MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
+ MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods");
+ MyVariableSerializable myVariableSerializable = new MyVariableSerializable("This is a test SerializableObject");
+ EntityManager em = emf.createEntityManager();
+ UserTransaction utx = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
+ utx.begin();
+ em.joinTransaction();
+ em.persist(myEntity);
+ em.persist(myEntityMethods);
+ em.persist(myEntityOnlyFields);
+ utx.commit();
+ em.close();
+ Environment env = createEnvironment();
KnowledgeBase kbase = createKnowledgeBase( "VariablePersistenceStrategyProcessTypeChange.rf" );
- StatefulKnowledgeSession ksession = createSession( kbase );
-
+ StatefulKnowledgeSession ksession = createSession( kbase, env );
+
+
+
+
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("x", "SomeString");
- parameters.put("y", new MyEntity("This is a test Entity with annotation in fields"));
- parameters.put("m", new MyEntityMethods("This is a test Entity with annotations in methods"));
- parameters.put("f", new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods"));
- parameters.put("z", new MyVariableSerializable("This is a test SerializableObject"));
+ parameters.put("y", myEntity);
+ parameters.put("m", myEntityMethods );
+ parameters.put("f", myEntityOnlyFields);
+ parameters.put("z", myVariableSerializable);
long processInstanceId = ksession.startProcess( "com.sample.ruleflow", parameters ).getId();
TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
WorkItem workItem = handler.getWorkItem();
assertNotNull( workItem );
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
ProcessInstance processInstance = ksession.getProcessInstance( processInstanceId );
assertNotNull( processInstance );
ksession.getWorkItemManager().completeWorkItem( workItem.getId(), null );
@@ -299,7 +327,7 @@
workItem = handler.getWorkItem();
assertNotNull( workItem );
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = ksession.getProcessInstance( processInstanceId );
assertNotNull( processInstance );
ksession.getWorkItemManager().completeWorkItem( workItem.getId(), null );
@@ -307,29 +335,47 @@
workItem = handler.getWorkItem();
assertNull( workItem );
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = ksession.getProcessInstance( processInstanceId );
assertNull( processInstance );
}
@Test
- public void testPersistenceVariablesSubProcess() {
+ public void testPersistenceVariablesSubProcess() throws NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
+
+ MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
+ MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
+ MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods");
+ MyVariableSerializable myVariableSerializable = new MyVariableSerializable("This is a test SerializableObject");
+ EntityManager em = emf.createEntityManager();
+ UserTransaction utx = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
+ utx.begin();
+ em.joinTransaction();
+ em.persist(myEntity);
+ em.persist(myEntityMethods);
+ em.persist(myEntityOnlyFields);
+ utx.commit();
+ em.close();
+ Environment env = createEnvironment();
KnowledgeBase kbase = createKnowledgeBase( "VariablePersistenceStrategySubProcess.rf" );
- StatefulKnowledgeSession ksession = createSession( kbase );
-
+ StatefulKnowledgeSession ksession = createSession( kbase, env );
+
+
+
+
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("x", "SomeString");
- parameters.put("y", new MyEntity("This is a test Entity with annotation in fields"));
- parameters.put("m", new MyEntityMethods("This is a test Entity with annotations in methods"));
- parameters.put("f", new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods"));
- parameters.put("z", new MyVariableSerializable("This is a test SerializableObject"));
+ parameters.put("y", myEntity);
+ parameters.put("m", myEntityMethods);
+ parameters.put("f", myEntityOnlyFields);
+ parameters.put("z", myVariableSerializable);
long processInstanceId = ksession.startProcess( "com.sample.ruleflow", parameters ).getId();
TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
WorkItem workItem = handler.getWorkItem();
assertNotNull( workItem );
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
ProcessInstance processInstance = ksession.getProcessInstance( processInstanceId );
assertNotNull( processInstance );
ksession.getWorkItemManager().completeWorkItem( workItem.getId(), null );
@@ -337,7 +383,7 @@
workItem = handler.getWorkItem();
assertNotNull( workItem );
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = ksession.getProcessInstance( processInstanceId );
assertNotNull( processInstance );
ksession.getWorkItemManager().completeWorkItem( workItem.getId(), null );
@@ -345,7 +391,7 @@
workItem = handler.getWorkItem();
assertNotNull( workItem );
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = ksession.getProcessInstance( processInstanceId );
assertNotNull( processInstance );
ksession.getWorkItemManager().completeWorkItem( workItem.getId(), null );
@@ -353,33 +399,44 @@
workItem = handler.getWorkItem();
assertNull( workItem );
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = ksession.getProcessInstance( processInstanceId );
assertNull( processInstance );
}
@Test
public void testWorkItemWithVariablePersistence() throws Exception{
+ MyEntity myEntity = new MyEntity("This is a test Entity");
+ MyVariableSerializable myVariableSerializable = new MyVariableSerializable("This is a test SerializableObject");
+ EntityManager em = emf.createEntityManager();
+ UserTransaction utx = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
+ utx.begin();
+
+ em.joinTransaction();
+ em.persist(myEntity);
+ utx.commit();
+ em.close();
+ Environment env = createEnvironment();
KnowledgeBase kbase = createKnowledgeBase( "VPSProcessWithWorkItems.rf" );
- StatefulKnowledgeSession ksession = createSession( kbase );
-
+ StatefulKnowledgeSession ksession = createSession( kbase , env);
+
+
+
+
+
logger.info("### Starting process ###");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("x", "SomeString");
- parameters.put("y", new MyEntity("This is a test Entity"));
- parameters.put("z", new MyVariableSerializable("This is a test SerializableObject"));
+ parameters.put("y", myEntity);
+ parameters.put("z", myVariableSerializable);
long processInstanceId = ksession.startProcess( "com.sample.ruleflow", parameters ).getId();
TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
WorkItem workItem = handler.getWorkItem();
assertNotNull( workItem );
- List<?> result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
-
- assertEquals(5, result.size());
-
logger.info("### Retrieving process instance ###");
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase , env);
WorkflowProcessInstance processInstance = (WorkflowProcessInstance)
ksession.getProcessInstance( processInstanceId );
assertNotNull( processInstance );
@@ -400,16 +457,8 @@
workItem = handler.getWorkItem();
assertNotNull( workItem );
- logger.info("### Retrieving variable instance infos ###");
- result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
- //6 Variables from the process and 2 variables from the workitems
- assertEquals(8, result.size());
- for (Object o: result) {
- logger.info(((VariableInstanceInfo) o).toString());
- }
-
logger.info("### Retrieving process instance ###");
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = (WorkflowProcessInstance)
ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
@@ -430,11 +479,8 @@
workItem = handler.getWorkItem();
assertNotNull(workItem);
- result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
- assertEquals(8, result.size());
-
logger.info("### Retrieving process instance ###");
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = (WorkflowProcessInstance)
ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
@@ -453,11 +499,8 @@
workItem = handler.getWorkItem();
assertNull(workItem);
- result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
- assertEquals(0, result.size());
-
- ksession = reloadSession( ksession, kbase );
+ ksession = reloadSession( ksession, kbase, env );
processInstance = (WorkflowProcessInstance)
ksession.getProcessInstance(processInstanceId);
assertNull(processInstance);
@@ -467,24 +510,24 @@
public void testEntityWithSuperClassAnnotationField() throws Exception {
MySubEntity subEntity = new MySubEntity();
subEntity.setId(3L);
- assertEquals(3L, JPAVariablePersister.getClassIdValue(subEntity));
+ assertEquals(3L, JPAPlaceholderResolverStrategy.getClassIdValue(subEntity));
}
@Test
public void testEntityWithSuperClassAnnotationMethod() throws Exception {
MySubEntityMethods subEntity = new MySubEntityMethods();
subEntity.setId(3L);
- assertEquals(3L, JPAVariablePersister.getClassIdValue(subEntity));
+ assertEquals(3L, JPAPlaceholderResolverStrategy.getClassIdValue(subEntity));
}
- private StatefulKnowledgeSession createSession(KnowledgeBase kbase){
- return JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, createEnvironment() );
+ private StatefulKnowledgeSession createSession(KnowledgeBase kbase, Environment env){
+ return JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env );
}
- private StatefulKnowledgeSession reloadSession(StatefulKnowledgeSession ksession, KnowledgeBase kbase){
+ private StatefulKnowledgeSession reloadSession(StatefulKnowledgeSession ksession, KnowledgeBase kbase, Environment env){
int sessionId = ksession.getId();
ksession.dispose();
- return JPAKnowledgeService.loadStatefulKnowledgeSession( sessionId, kbase, null, createEnvironment() );
+ return JPAKnowledgeService.loadStatefulKnowledgeSession( sessionId, kbase, null, env);
}
private KnowledgeBase createKnowledgeBase(String flowFile) {
@@ -510,8 +553,11 @@
Environment env = KnowledgeBaseFactory.newEnvironment();
env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
env.set(EnvironmentName.GLOBALS, new MapGlobalResolver());
- env.set( EnvironmentName.TRANSACTION_MANAGER,
- TransactionManagerServices.getTransactionManager() );
+ env.set( EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager() );
+ env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[]{
+ new JPAPlaceholderResolverStrategy(env),
+ new SerializablePlaceholderResolverStrategy( ClassObjectMarshallingStrategyAcceptor.DEFAULT )
+ });
return env;
}
Modified: labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/META-INF/persistence.xml
===================================================================
--- labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/META-INF/persistence.xml 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/META-INF/persistence.xml 2010-10-21 18:17:19 UTC (rev 35655)
@@ -14,15 +14,12 @@
<class>org.drools.persistence.session.MyEntity</class>
<class>org.drools.persistence.session.MyEntityMethods</class>
<class>org.drools.persistence.session.MyEntityOnlyFields</class>
- <class>org.drools.persistence.processinstance.variabletypes.JPAPersistedVariable</class>
- <class>org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo</class>
- <class>org.drools.persistence.processinstance.variabletypes.SerializablePersistedVariable</class>
<class>org.drools.persistence.processinstance.WorkItemInfo</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="update" />
- <property name="hibernate.show_sql" value="false" />
+ <property name="hibernate.show_sql" value="true" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.BTMTransactionManagerLookup" />
</properties>
</persistence-unit>
Modified: labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VPSProcessWithWorkItems.rf
===================================================================
--- labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VPSProcessWithWorkItems.rf 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VPSProcessWithWorkItems.rf 2010-10-21 18:17:19 UTC (rev 35655)
@@ -8,6 +8,8 @@
<imports>
<import name="org.drools.persistence.session.MyEntity" />
<import name="org.drools.persistence.session.MyVariableSerializable" />
+ <import name="javax.persistence.EntityManager" />
+ <import name="org.drools.runtime.EnvironmentName" />
</imports>
<variables>
<variable name="x" >
@@ -70,7 +72,11 @@
System.out.println("y = " + y);
System.out.println("z = " + z);
kcontext.setVariable("a", "Some new String");
-kcontext.setVariable("b", new MyEntity("This is a new test Entity"));
+EntityManager em = (EntityManager) kcontext.getKnowledgeRuntime().getEnvironment().get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
+MyEntity myNewEntity = new MyEntity("This is a new test Entity");
+em.persist(myNewEntity);
+
+kcontext.setVariable("b",myNewEntity );
kcontext.setVariable("c", new MyVariableSerializable("This is a new test SerializableObject"));</action>
</actionNode>
<humanTask id="7" name="Human Task" x="445" y="20" width="124" height="40" >
@@ -107,7 +113,12 @@
System.out.println("b = " + b);
System.out.println("c = " + c);
kcontext.setVariable("a", "Some changed String");
-kcontext.setVariable("b", new MyEntity("This is a changed test Entity"));
+EntityManager em = (EntityManager) kcontext.getKnowledgeRuntime().getEnvironment().get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
+MyEntity myNewEntity = new MyEntity("This is a changed test Entity");
+em.persist(myNewEntity);
+
+
+kcontext.setVariable("b",myNewEntity );
kcontext.setVariable("c", new MyVariableSerializable("This is a changed test SerializableObject"));</action>
</actionNode>
<humanTask id="9" name="Human Task" x="713" y="16" width="100" height="48" >
Modified: labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VariablePersistenceStrategyProcess.rf
===================================================================
--- labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VariablePersistenceStrategyProcess.rf 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VariablePersistenceStrategyProcess.rf 2010-10-21 18:17:19 UTC (rev 35655)
@@ -8,6 +8,8 @@
<imports>
<import name="org.drools.persistence.session.MyEntity" />
<import name="org.drools.persistence.session.MyVariableSerializable" />
+ <import name="javax.persistence.EntityManager" />
+ <import name="org.drools.runtime.EnvironmentName" />
</imports>
<variables>
<variable name="x" >
@@ -68,7 +70,11 @@
System.out.println("y = " + y);
System.out.println("z = " + z);
kcontext.setVariable("a", "Some new String");
-kcontext.setVariable("b", new MyEntity("This is a new test Entity"));
+EntityManager em = (EntityManager) kcontext.getKnowledgeRuntime().getEnvironment().get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
+MyEntity myNewEntity = new MyEntity("This is a new test Entity");
+em.persist(myNewEntity);
+
+kcontext.setVariable("b", myNewEntity);
kcontext.setVariable("c", new MyVariableSerializable("This is a new test SerializableObject"));</action>
</actionNode>
<humanTask id="7" name="Human Task" x="445" y="20" width="80" height="40" >
@@ -101,7 +107,10 @@
System.out.println("b = " + b);
System.out.println("c = " + c);
kcontext.setVariable("a", "Some changed String");
-kcontext.setVariable("b", new MyEntity("This is a changed test Entity"));
+EntityManager em = (EntityManager)kcontext.getKnowledgeRuntime().getEnvironment().get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
+MyEntity myNewEntity = new MyEntity("This is a changed test Entity");
+em.persist(myNewEntity);
+kcontext.setVariable("b", myNewEntity);
kcontext.setVariable("c", new MyVariableSerializable("This is a changed test SerializableObject"));</action>
</actionNode>
<humanTask id="9" name="Human Task" >
Modified: labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VariablePersistenceStrategyProcessTypeChange.rf
===================================================================
--- labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VariablePersistenceStrategyProcessTypeChange.rf 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-flow-persistence-jpa/src/test/resources/VariablePersistenceStrategyProcessTypeChange.rf 2010-10-21 18:17:19 UTC (rev 35655)
@@ -8,6 +8,8 @@
<imports>
<import name="org.drools.persistence.session.MyEntity" />
<import name="org.drools.persistence.session.MyVariableSerializable" />
+ <import name="javax.persistence.EntityManager" />
+ <import name="org.drools.runtime.EnvironmentName" />
</imports>
<variables>
<variable name="x" >
@@ -44,7 +46,10 @@
System.out.println("b = " + b);
System.out.println("c = " + c);
kcontext.setVariable("a", "Some new String");
-kcontext.setVariable("b", new MyEntity("This is a new test Entity"));
+EntityManager em = (EntityManager)kcontext.getKnowledgeRuntime().getEnvironment().get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
+MyEntity myNewEntity = new MyEntity("This is a new test Entity");
+em.persist(myNewEntity);
+kcontext.setVariable("b", myNewEntity);
kcontext.setVariable("c", new MyVariableSerializable("This is a new test SerializableObject"));</action>
</actionNode>
<humanTask id="7" name="Human Task" x="445" y="20" width="80" height="40" >
@@ -77,7 +82,10 @@
System.out.println("b = " + b);
System.out.println("c = " + c);
kcontext.setVariable("a", "Some changed String");
-kcontext.setVariable("c", new MyEntity("This is a changed test Entity"));
+EntityManager em = (EntityManager)kcontext.getKnowledgeRuntime().getEnvironment().get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
+MyEntity myNewEntity = new MyEntity("This is a changed test Entity");
+em.persist(myNewEntity);
+kcontext.setVariable("c", myNewEntity);
kcontext.setVariable("b", new MyVariableSerializable("This is a changed test SerializableObject"));</action>
</actionNode>
<humanTask id="9" name="Human Task" x="445" y="20" width="80" height="40" >
Added: labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/marshaller/JPAPlaceholderResolverStrategy.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/marshaller/JPAPlaceholderResolverStrategy.java (rev 0)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/marshaller/JPAPlaceholderResolverStrategy.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -0,0 +1,138 @@
+/*
+ * Copyright 2010 salaboy.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * under the License.
+ */
+package org.drools.persistence.jpa.marshaller;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Id;
+import org.drools.marshalling.ObjectMarshallingStrategy;
+import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * @author salaboy
+ */
+public class JPAPlaceholderResolverStrategy implements ObjectMarshallingStrategy {
+ private static Logger log = LoggerFactory.getLogger(JPAPlaceholderResolverStrategy.class);
+ private Environment env;
+
+ public JPAPlaceholderResolverStrategy(Environment env) {
+ this.env = env;
+ }
+
+ public boolean accept(Object object) {
+ return isEntity(object);
+ }
+
+ public void write(ObjectOutputStream os, Object object) throws IOException {
+
+
+ os.writeUTF(object.getClass().getCanonicalName());
+ os.writeObject(getClassIdValue(object));
+
+ }
+
+ public Object read(ObjectInputStream is) throws IOException, ClassNotFoundException {
+ String canonicalName = is.readUTF();
+ Object id = is.readObject();
+ EntityManagerFactory emf = (EntityManagerFactory) env.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
+ EntityManager em = emf.createEntityManager();
+ return em.find(Class.forName(canonicalName), id);
+ }
+
+ public static Serializable getClassIdValue(Object o) {
+ Class<? extends Object> varClass = o.getClass();
+ Serializable idValue = null;
+ try{
+ do {
+ Field[] fields = varClass.getDeclaredFields();
+ for (int i = 0; i < fields.length && idValue == null; i++) {
+ Field field = fields[i];
+ Id id = field.getAnnotation(Id.class);
+ if (id != null) {
+ try {
+ idValue = callIdMethod(o, "get"
+ + Character.toUpperCase(field.getName().charAt(0))
+ + field.getName().substring(1));
+ } catch (NoSuchMethodException e) {
+ idValue = (Serializable) field.get(o);
+ }
+ }
+ }
+ } while ((varClass = varClass.getSuperclass()) != null && idValue == null);
+ if (idValue == null) {
+ varClass = o.getClass();
+ do {
+ Method[] methods = varClass.getMethods();
+ for (int i = 0; i < methods.length && idValue == null; i++) {
+ Method method = methods[i];
+ Id id = method.getAnnotation(Id.class);
+ if (id != null) {
+ idValue = (Serializable) method.invoke(o);
+ }
+ }
+ } while ((varClass = varClass.getSuperclass()) != null && idValue == null);
+ }
+ }
+ catch(Exception ex){
+ log.error(ex.getMessage());
+ }
+ return idValue;
+ }
+
+ private static Serializable callIdMethod(Object target, String methodName) throws IllegalArgumentException,
+ SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ return (Serializable) target.getClass().getMethod(methodName, (Class[]) null).invoke(target, new Object[]{});
+ }
+
+ private static boolean isEntity(Object o){
+ Class<? extends Object> varClass = o.getClass();
+ do {
+ Field[] fields = varClass.getDeclaredFields();
+ for (int i = 0; i < fields.length; i++) {
+ Field field = fields[i];
+ Id id = field.getAnnotation(Id.class);
+ if (id != null) {
+ return true;
+ }
+ }
+ } while ((varClass = varClass.getSuperclass()) != null);
+ varClass = o.getClass();
+ do {
+ Method[] methods = varClass.getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ Method method = methods[i];
+ Id id = method.getAnnotation(Id.class);
+ if (id != null) {
+ return true;
+ }
+ }
+ } while ((varClass = varClass.getSuperclass()) != null );
+
+ return false;
+ }
+}
Deleted: labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/VariablePersistenceStrategy.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/VariablePersistenceStrategy.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/VariablePersistenceStrategy.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -1,155 +0,0 @@
-package org.drools.persistence.processinstance;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.drools.persistence.processinstance.persisters.VariablePersister;
-import org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo;
-import org.drools.runtime.Environment;
-
-/**
- *
- * @author <a href="mailto:kris_verlaenen at hotmail.com">Kris Verlaenen</a>
- * @author salaboy
- */
-public class VariablePersistenceStrategy {
-
- // map of variable persisters per type
- private Map<String, String> types = new HashMap<String, String>();
- // cache of already instantiated variable persisters
- private Map<String, VariablePersister> variablePersisters =
- new HashMap<String, VariablePersister>();
-
- public void setPersister(String type, String persisterClassname) {
- types.put(type, persisterClassname);
- }
-
- public boolean isEnabled() {
- return !types.isEmpty();
- }
-
- public VariableInstanceInfo persistVariable(String name, Object o,
- VariableInstanceInfo oldValue, Environment env) {
- VariablePersister persister = getVariablePersister(o);
- VariableInstanceInfo variable = null;
- if (persister != null) {
- variable = persister.persistExternalVariable(name, o, oldValue, env);
- }
- return variable;
- }
-
- @SuppressWarnings("unchecked")
- private VariablePersister getVariablePersister(Object o) {
- VariablePersister persister = null;
- String persisterFQN = getVariablePersistenceType(o);
- if (persisterFQN != null && !persisterFQN.equals("")) {
- Class<VariablePersister> persisterClass = null;
- persister = variablePersisters.get(persisterFQN);
- if (persister != null) {
- return persister;
- }
- try {
- persisterClass = (Class<VariablePersister>) Class.forName(persisterFQN);
- Constructor<VariablePersister> constructor = persisterClass.getConstructor();
- persister = (VariablePersister) constructor.newInstance();
- variablePersisters.put(persisterFQN, persister);
- return persister;
- } catch (ClassNotFoundException ex) {
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (NoSuchMethodException ex) {
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (SecurityException ex) {
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (InstantiationException ex) {
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IllegalAccessException ex) {
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IllegalArgumentException ex) {
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (InvocationTargetException ex) {
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- public Object getVariable(VariableInstanceInfo variableInfo, Environment env) {
- try {
- String persisterFQN = variableInfo.getPersister();
- VariablePersister persister = variablePersisters.get(persisterFQN);
- if (persister == null) {
- Class<VariablePersister> clazz = (Class<VariablePersister>) Class.forName(persisterFQN);
- Constructor<VariablePersister> constructor = clazz.getDeclaredConstructor();
- persister = (VariablePersister) constructor.newInstance();
- variablePersisters.put(persisterFQN, persister);
- }
- return persister.getExternalPersistedVariable(variableInfo, env);
- } catch (InstantiationException ex) {
- ex.printStackTrace();
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IllegalAccessException ex) {
- ex.printStackTrace();
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IllegalArgumentException ex) {
- ex.printStackTrace();
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (InvocationTargetException ex) {
- ex.printStackTrace();
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (NoSuchMethodException ex) {
- ex.printStackTrace();
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (SecurityException ex) {
- ex.printStackTrace();
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- } catch (ClassNotFoundException ex) {
- ex.printStackTrace();
- Logger.getLogger(VariablePersistenceStrategy.class.getName()).log(Level.SEVERE, null, ex);
- }
- return null;
- }
-
- private String getVariablePersistenceType(Object o) {
- if (o == null) {
- return null;
- }
- //First check for a specific type
- String className = o.getClass().getCanonicalName();
- String persisterFQN = types.get(className);
- if (persisterFQN != null && !persisterFQN.equals("")) {
- return persisterFQN;
- }
- //Then check for annotations
- Annotation[] annotations = o.getClass().getDeclaredAnnotations();
- if (annotations != null) {
-
- for (Annotation annotation : annotations) {
- persisterFQN = types.get(annotation.annotationType().getName());
- if (persisterFQN != null && !persisterFQN.equals("")) {
- return persisterFQN;
- }
- }
- }
-
- //finally look for interface to the root
- Class<?> clazz = o.getClass();
- do {
- Class<?>[] interfaces = clazz.getInterfaces();
- for(Class<?> interfaze : interfaces) {
- persisterFQN = types.get(interfaze.getName());
- if (persisterFQN != null && !persisterFQN.equals("")) {
- System.out.println("Persistence strategy returns: " + persisterFQN);
- return persisterFQN;
- }
- }
- } while ( (clazz = clazz.getSuperclass() ) != null);
-
- return null;
- }
-}
Deleted: labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/VariablePersistenceStrategyFactory.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/VariablePersistenceStrategyFactory.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/VariablePersistenceStrategyFactory.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -1,48 +0,0 @@
-package org.drools.persistence.processinstance;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-import java.util.Map.Entry;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- *
- * @author <a href="mailto:kris_verlaenen at hotmail.com">Kris Verlaenen</a>
- * @author salaboy
- */
-public class VariablePersistenceStrategyFactory {
-
- private static VariablePersistenceStrategy INSTANCE;
-
- public static VariablePersistenceStrategy getVariablePersistenceStrategy() {
- if (INSTANCE == null) {
- INSTANCE = new VariablePersistenceStrategy();
- loadPersisters();
- }
- return INSTANCE;
- }
-
- private static VariablePersistenceStrategy loadPersisters() {
- Properties props = new Properties();
- try {
- InputStream is = Thread.currentThread().getContextClassLoader()
- .getResourceAsStream("META-INF/PersistenceStrategies.conf");
- if (is != null) {
- props.load(is);
- }
- } catch (IOException ex) {
- Logger.getLogger(VariablePersistenceStrategyFactory.class.getName())
- .log(Level.SEVERE, null, ex);
- }
- if (INSTANCE == null) {
- INSTANCE = new VariablePersistenceStrategy();
- }
- for (Entry<Object, Object> entry : props.entrySet()) {
- INSTANCE.setPersister((String) entry.getKey(), (String) entry.getValue());
- }
- return INSTANCE;
- }
-
-}
Modified: labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/WorkItemInfo.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/WorkItemInfo.java 2010-10-21 18:16:04 UTC (rev 35654)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/WorkItemInfo.java 2010-10-21 18:17:19 UTC (rev 35655)
@@ -3,33 +3,26 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
-import javax.persistence.JoinColumn;
import javax.persistence.Lob;
-import javax.persistence.MapKey;
-import javax.persistence.OneToMany;
import javax.persistence.PreUpdate;
import javax.persistence.Transient;
import javax.persistence.Version;
+import org.drools.impl.StatefulKnowledgeSessionImpl;
import org.drools.marshalling.impl.InputMarshaller;
import org.drools.marshalling.impl.MarshallerReaderContext;
import org.drools.marshalling.impl.MarshallerWriteContext;
import org.drools.marshalling.impl.OutputMarshaller;
-import org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo;
import org.drools.process.instance.WorkItem;
import org.drools.runtime.Environment;
+import org.drools.runtime.EnvironmentName;
@Entity
public class WorkItemInfo {
@@ -55,11 +48,7 @@
private @Transient
Environment env;
- @OneToMany(cascade = CascadeType.ALL)
- @JoinColumn(name = "workItemId")
- @MapKey(name = "name")
- private Map<String, VariableInstanceInfo> variables = new HashMap<String, VariableInstanceInfo>();
- private boolean externalVariables = false;
+
@@ -106,11 +95,9 @@
MarshallerReaderContext context = new MarshallerReaderContext( bais,
null,
null,
- null );
- workItem = InputMarshaller.readWorkItem( context, !externalVariables );
- if ( externalVariables ) {
- restoreVariables();
- }
+ null,
+ env);
+ workItem = InputMarshaller.readWorkItem( context );
context.close();
} catch ( IOException e ) {
e.printStackTrace();
@@ -120,39 +107,8 @@
return workItem;
}
- private void restoreVariables() {
+
-
- for ( Map.Entry<String, VariableInstanceInfo> entry : variables.entrySet() ) {
- String[] variableHierarchy = entry.getKey().split( VARIABLE_SEPARATOR );
- // last one is variable name
- String variableName = variableHierarchy[variableHierarchy.length - 1];
- // other ones are parent ids
- List<Long> parentIds = new ArrayList<Long>();
- for ( int i = 0; i < variableHierarchy.length - 1; i++ ) {
- parentIds.add( Long.valueOf( variableHierarchy[i] ) );
- }
- restoreVariable( entry.getValue(),
- parentIds,
- variableName,
- workItem );
- }
- }
-
- private void restoreVariable(VariableInstanceInfo variableInfo,
- List<Long> parentIds,
- String variableName,
- WorkItem workItem) throws NumberFormatException {
-
- VariablePersistenceStrategy persistenceStrategy = VariablePersistenceStrategyFactory.getVariablePersistenceStrategy();
- Object value = persistenceStrategy.getVariable( variableInfo,
- this.env );
- System.out.println( ">>>>> Restoring variable inside workitem " + variableName + " = " + value );
- workItem.setParameter( variableName, value );
-
- }
-
-
@PreUpdate
public void update() {
this.state = workItem.getState();
@@ -163,15 +119,12 @@
null,
null,
null,
- null );
- externalVariables = VariablePersistenceStrategyFactory.getVariablePersistenceStrategy().isEnabled();
+ null,
+ this.env);
+
OutputMarshaller.writeWorkItem( context,
- workItem, !externalVariables );
+ workItem );
-
- if ( externalVariables ) {
- variablesChanged = persistVariables();
- }
context.close();
this.workItemByteArray = baos.toByteArray();
} catch ( IOException e ) {
@@ -179,50 +132,7 @@
}
}
- private boolean persistVariables() {
- // Get Process Variables
+
- Map<String, Object> processVariables = workItem.getParameters();
- Map<String, VariableInstanceInfo> newVariables = new HashMap<String, VariableInstanceInfo>();
- // persist process variables
- persist( processVariables,
- "workItem.",
- newVariables );
- // persist variables in nested variable scopes
- if ( newVariables.size() > 0 || this.variables.size() > 0 ) {
- // clear variables so unnecessary values are removed
- this.variables.clear();
- this.variables.putAll( newVariables );
- // TODO: how can I know that no variables were changed?
- return true;
- } else {
- return false;
}
- }
-
- private void persist(Map<String, Object> variables,
- String prefix,
- Map<String, VariableInstanceInfo> newVariables) {
- VariablePersistenceStrategy persistenceStrategy = VariablePersistenceStrategyFactory.getVariablePersistenceStrategy();
- for ( Map.Entry<String, Object> entries : variables.entrySet() ) {
- String variableName = prefix + entries.getKey();
- Object value = entries.getValue();
- VariableInstanceInfo oldValue = this.variables.get( variableName );
- VariableInstanceInfo variable = persistenceStrategy.persistVariable( variableName,
- value,
- oldValue,
- this.env );
-
- if ( variable != null ) {
- System.out.println( "<<<<< Persisting variable inside workitem " + variableName + " = " + value );
- newVariables.put( variableName,
- variable );
- } else {
- System.out.println( "<<<<< Variable inside workitem " + variableName + " not persisted (value null)" );
- }
- }
- }
-
-
-}
More information about the jboss-svn-commits
mailing list