Search in sources :

Example 26 with Environment

use of org.kie.api.runtime.Environment in project drools by kiegroup.

the class ReloadSessionTest method reloadKnowledgeSessionTest.

@Test
public void reloadKnowledgeSessionTest() {
    // Initialize drools environment stuff
    Environment env = createEnvironment();
    KieBase kbase = initializeKnowledgeBase(simpleRule);
    StatefulKnowledgeSession commandKSession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    assertTrue("There should be NO facts present in a new (empty) knowledge session.", commandKSession.getFactHandles().isEmpty());
    // Persist a facthandle to the database
    Integer integerFact = (new Random()).nextInt(Integer.MAX_VALUE - 1) + 1;
    commandKSession.insert(integerFact);
    // At this point in the code, the fact has been persisted to the database
    // (within a transaction via the PersistableRunner)
    Collection<FactHandle> factHandles = commandKSession.getFactHandles();
    assertTrue("At least one fact should have been inserted by the ksession.insert() method above.", !factHandles.isEmpty());
    FactHandle origFactHandle = factHandles.iterator().next();
    assertTrue("The stored fact should contain the same number as the value inserted (but does not).", Integer.parseInt(((DefaultFactHandle) origFactHandle).getObject().toString()) == integerFact.intValue());
    // Save the sessionInfo id in order to retrieve it later
    long sessionInfoId = commandKSession.getIdentifier();
    // Clean up the session, environment, etc.
    PersistenceContextManager pcm = (PersistenceContextManager) commandKSession.getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
    commandKSession.dispose();
    pcm.dispose();
    emf.close();
    // Reload session from the database
    emf = Persistence.createEntityManagerFactory(DROOLS_PERSISTENCE_UNIT_NAME);
    context.put(ENTITY_MANAGER_FACTORY, emf);
    env = createEnvironment();
    // Re-initialize the knowledge session:
    StatefulKnowledgeSession newCommandKSession = JPAKnowledgeService.loadStatefulKnowledgeSession(sessionInfoId, kbase, null, env);
    // Test that the session has been successfully reinitialized
    factHandles = newCommandKSession.getFactHandles();
    assertTrue("At least one fact should have been persisted by the ksession.insert above.", !factHandles.isEmpty() && factHandles.size() == 1);
    FactHandle retrievedFactHandle = factHandles.iterator().next();
    assertTrue("If the retrieved and original FactHandle object are the same, then the knowledge session has NOT been reloaded!", origFactHandle != retrievedFactHandle);
    assertTrue("The retrieved fact should contain the same info as the original (but does not).", Integer.parseInt(((DefaultFactHandle) retrievedFactHandle).getObject().toString()) == integerFact.intValue());
    // Test to see if the (retrieved) facts can be processed
    ArrayList<Object> list = new ArrayList<Object>();
    newCommandKSession.setGlobal("list", list);
    newCommandKSession.fireAllRules();
    assertEquals(1, list.size());
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ArrayList(java.util.ArrayList) PersistenceContextManager(org.drools.persistence.api.PersistenceContextManager) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) Random(java.util.Random) KieBase(org.kie.api.KieBase) Environment(org.kie.api.runtime.Environment) Test(org.junit.Test)

Example 27 with Environment

use of org.kie.api.runtime.Environment in project drools by kiegroup.

the class DroolsPersistenceUtil method createEnvironment.

public static Environment createEnvironment(Map<String, Object> context) {
    Environment env = EnvironmentFactory.newEnvironment();
    UserTransaction ut = (UserTransaction) context.get(TRANSACTION);
    if (ut != null) {
        env.set(TRANSACTION, ut);
    }
    env.set(ENTITY_MANAGER_FACTORY, context.get(ENTITY_MANAGER_FACTORY));
    env.set(GLOBALS, new MapGlobalResolver());
    return env;
}
Also used : UserTransaction(javax.transaction.UserTransaction) Environment(org.kie.api.runtime.Environment) MapGlobalResolver(org.drools.core.base.MapGlobalResolver)

Example 28 with Environment

use of org.kie.api.runtime.Environment in project drools by kiegroup.

the class EnvironmentFactory method newEnvironment.

public static Environment newEnvironment() {
    Environment env = new EnvironmentImpl();
    env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[] { new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT) });
    return env;
}
Also used : SerializablePlaceholderResolverStrategy(org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy) Environment(org.kie.api.runtime.Environment)

Example 29 with Environment

use of org.kie.api.runtime.Environment in project drools by kiegroup.

the class ObjectMarshallingStrategyStoreTest method testMultipleObjectMarshallingStrategiesOfTheSameClassWithDifferentNames.

@Test
public void testMultipleObjectMarshallingStrategiesOfTheSameClassWithDifferentNames() throws IOException, ClassNotFoundException {
    Environment env = EnvironmentFactory.newEnvironment();
    final Thing entityOne = new Thing(1, "Object 1");
    final Thing entityTwo = new Thing(2, "Object 2");
    Collection srcItems = new ArrayList();
    srcItems.add(entityOne);
    srcItems.add(entityTwo);
    ObjectMarshallingStrategy[] strats = new ObjectMarshallingStrategy[] { new IdentityPlaceholderResolverStrategy("entityOne", new ObjectMarshallingStrategyAcceptor() {

        @Override
        public boolean accept(Object object) {
            return entityOne.equals(object);
        }
    }, Collections.singletonMap(entityOne.id, (Object) entityOne)), new IdentityPlaceholderResolverStrategy("entityTwo", new ObjectMarshallingStrategyAcceptor() {

        @Override
        public boolean accept(Object object) {
            return entityTwo.equals(object);
        }
    }, Collections.singletonMap(entityTwo.id, (Object) entityTwo)) };
    env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, strats);
    KieSessionConfiguration ksc = SessionConfiguration.newInstance();
    final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconf.setOption(EventProcessingOption.STREAM);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbconf);
    KieSession ks = kbase.newKieSession(ksc, env);
    ks.insert(entityOne);
    ks.insert(entityTwo);
    ProtobufMarshaller marshaller = (ProtobufMarshaller) MarshallerFactory.newMarshaller(kbase, strats);
    // Serialize object
    final byte[] b1;
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        marshaller.marshall(bos, ks, System.currentTimeMillis());
        b1 = bos.toByteArray();
        bos.close();
    }
    // Deserialize object
    StatefulKnowledgeSession ksession2;
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(b1);
        try {
            ksession2 = marshaller.unmarshall(bais, ks.getSessionConfiguration(), ks.getEnvironment());
            Collection items = ksession2.getFactHandles();
            Assert.assertTrue(items.size() == 2);
            for (Object item : items) {
                FactHandle factHandle = (FactHandle) item;
                Assert.assertTrue(srcItems.contains(((DefaultFactHandle) factHandle).getObject()));
            }
        } catch (RuntimeException npe) {
            // Here ocurrs the bug that shows that NamedObjectMarshallingStrategies are required.
            Assert.fail("This error only happens if identity ObjectMarshallingStrategy use old name");
        } finally {
            bais.close();
        }
    }
}
Also used : ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KieBaseConfiguration(org.kie.api.KieBaseConfiguration) ByteArrayInputStream(java.io.ByteArrayInputStream) Environment(org.kie.api.runtime.Environment) Collection(java.util.Collection) KieSession(org.kie.api.runtime.KieSession) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) ObjectMarshallingStrategyAcceptor(org.kie.api.marshalling.ObjectMarshallingStrategyAcceptor) Test(org.junit.Test)

Example 30 with Environment

use of org.kie.api.runtime.Environment in project drools by kiegroup.

the class ObjectMarshallingStrategyStoreTest method testThrowErrorWhenExistMultipleMarshallingStrategiesWithSameName.

@Test
public void testThrowErrorWhenExistMultipleMarshallingStrategiesWithSameName() throws IOException, ClassNotFoundException {
    Environment env = EnvironmentFactory.newEnvironment();
    final Thing entityOne = new Thing(1, "Object 1");
    final Thing entityTwo = new Thing(2, "Object 2");
    Collection srcItems = new ArrayList();
    srcItems.add(entityOne);
    srcItems.add(entityTwo);
    ObjectMarshallingStrategy[] strats = new ObjectMarshallingStrategy[] { new IdentityPlaceholderResolverStrategy(new ObjectMarshallingStrategyAcceptor() {

        @Override
        public boolean accept(Object object) {
            return entityOne.equals(object);
        }
    }, Collections.singletonMap(entityOne.id, (Object) entityOne)), new IdentityPlaceholderResolverStrategy(new ObjectMarshallingStrategyAcceptor() {

        @Override
        public boolean accept(Object object) {
            return entityTwo.equals(object);
        }
    }, Collections.singletonMap(entityTwo.id, (Object) entityTwo)) };
    env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, strats);
    KieSessionConfiguration ksc = SessionConfiguration.newInstance();
    final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconf.setOption(EventProcessingOption.STREAM);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbconf);
    KieSession ks = kbase.newKieSession(ksc, env);
    ks.insert(entityOne);
    ks.insert(entityTwo);
    try {
        ProtobufMarshaller marshaller = (ProtobufMarshaller) MarshallerFactory.newMarshaller(kbase, strats);
        // Here ocurrs the bug that shows that NamedObjectMarshallingStrategies are required.
        Assert.fail("A runtime error must be thrown while found strategies with same name");
    } catch (RuntimeException re) {
        Assert.assertTrue(re.getMessage().contains("Multiple"));
    }
}
Also used : ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) ArrayList(java.util.ArrayList) KieBaseConfiguration(org.kie.api.KieBaseConfiguration) Environment(org.kie.api.runtime.Environment) Collection(java.util.Collection) KieSession(org.kie.api.runtime.KieSession) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) ObjectMarshallingStrategyAcceptor(org.kie.api.marshalling.ObjectMarshallingStrategyAcceptor) Test(org.junit.Test)

Aggregations

Environment (org.kie.api.runtime.Environment)31 Test (org.junit.Test)15 KieBase (org.kie.api.KieBase)9 KieSession (org.kie.api.runtime.KieSession)9 ArrayList (java.util.ArrayList)6 DroolsPersistenceUtil.createEnvironment (org.drools.persistence.util.DroolsPersistenceUtil.createEnvironment)6 KieSessionConfiguration (org.kie.api.runtime.KieSessionConfiguration)6 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)5 IdentityPlaceholderResolverStrategy (org.drools.core.marshalling.impl.IdentityPlaceholderResolverStrategy)4 StatefulKnowledgeSession (org.kie.internal.runtime.StatefulKnowledgeSession)4 Cheese (org.drools.compiler.Cheese)3 PersistenceContext (org.drools.persistence.api.PersistenceContext)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 Collection (java.util.Collection)2 List (java.util.List)2 EntityManager (javax.persistence.EntityManager)2 UserTransaction (javax.transaction.UserTransaction)2 Person (org.drools.compiler.Person)2 IteratorToList (org.drools.compiler.integrationtests.IteratorToList)2