Search in sources :

Example 36 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy in project drools by kiegroup.

the class MarshallingTest method testDisposeAfterMarshall.

@Test(timeout = 10_000L)
public void testDisposeAfterMarshall() throws InterruptedException, IOException {
    // DROOLS-4413
    String str = "package com.sample\n" + "rule R when\n" + "  $s : String()\n" + "then\n" + "  System.out.println($s);\n" + "end\n";
    KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL).build();
    KieSession ksession = kbase.newKieSession();
    CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread(() -> {
        System.out.println("Firing.");
        latch.countDown();
        ksession.fireUntilHalt();
        System.out.println("Halted.");
    });
    t.start();
    // wait fireUntilHalt to be invoked
    latch.await();
    Thread.sleep(100L);
    // Halt the session without adding any facts
    ksession.halt();
    KieMarshallers kMarshallers = KieServices.Factory.get().getMarshallers();
    ObjectMarshallingStrategy oms = kMarshallers.newSerializeMarshallingStrategy();
    Marshaller marshaller = kMarshallers.newMarshaller(kbase, new ObjectMarshallingStrategy[] { oms });
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        marshaller.marshall(baos, ksession);
    }
    // Destroy
    ksession.dispose();
    ksession.destroy();
    // Wait for our thread to exit
    // ** The thread exits if we call t.interrupt();
    t.join();
}
Also used : Marshaller(org.kie.api.marshalling.Marshaller) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) KieBase(org.kie.api.KieBase) KieHelper(org.kie.internal.utils.KieHelper) KieSession(org.kie.api.runtime.KieSession) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) KieMarshallers(org.kie.api.marshalling.KieMarshallers) Test(org.junit.Test)

Example 37 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy in project drools by kiegroup.

the class OldOutputMarshallerMethods method writeFactHandle_v1.

// Changed with JBRULES-3257
public static void writeFactHandle_v1(MarshallerWriteContext context, ObjectOutputStream stream, ObjectMarshallingStrategyStore objectMarshallingStrategyStore, int type, InternalFactHandle handle) throws IOException {
    stream.writeInt(type);
    stream.writeLong(handle.getId());
    stream.writeLong(handle.getRecency());
    if (type == 2) {
        // is event
        EventFactHandle efh = (EventFactHandle) handle;
        stream.writeLong(efh.getStartTimestamp());
        stream.writeLong(efh.getDuration());
        stream.writeBoolean(efh.isExpired());
        stream.writeLong(efh.getActivationsCount());
    }
    // context.out.println( "Object : int:" + handle.getId() + " long:" + handle.getRecency() );
    // context.out.println( handle.getObject() );
    Object object = handle.getObject();
    if (object != null) {
        int index = objectMarshallingStrategyStore.getStrategy(object);
        ObjectMarshallingStrategy strategy = objectMarshallingStrategyStore.getStrategy(index);
        stream.writeInt(index);
        strategy.write(stream, object);
    } else {
        stream.writeInt(-1);
    }
    String entryPoint = handle.getEntryPointId() != null ? handle.getEntryPointId().getEntryPointId() : null;
    if (entryPoint != null && !entryPoint.equals("")) {
        stream.writeBoolean(true);
        stream.writeUTF(entryPoint);
    } else {
        stream.writeBoolean(false);
    }
}
Also used : ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) EventFactHandle(org.drools.core.common.EventFactHandle)

Example 38 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy 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 = RuleBaseFactory.newKnowledgeBaseConfiguration();
    kbconf.setOption(EventProcessingOption.STREAM);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(RuleBaseFactory.newRuleBase(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) IdentityPlaceholderResolverStrategy(org.drools.serialization.protobuf.marshalling.IdentityPlaceholderResolverStrategy) 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.kiesession.rulebase.InternalKnowledgeBase) ObjectMarshallingStrategyAcceptor(org.kie.api.marshalling.ObjectMarshallingStrategyAcceptor) Test(org.junit.Test)

Example 39 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy 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 = RuleBaseFactory.newKnowledgeBaseConfiguration();
    kbconf.setOption(EventProcessingOption.STREAM);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(RuleBaseFactory.newRuleBase(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) IdentityPlaceholderResolverStrategy(org.drools.serialization.protobuf.marshalling.IdentityPlaceholderResolverStrategy) 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.kiesession.rulebase.InternalKnowledgeBase) ObjectMarshallingStrategyAcceptor(org.kie.api.marshalling.ObjectMarshallingStrategyAcceptor) Test(org.junit.Test)

Example 40 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy in project drools by kiegroup.

the class PersisterHelper method writeStrategiesIndex.

private static void writeStrategiesIndex(MarshallerWriteContext context, ProtobufMessages.Header.Builder _header) throws IOException {
    for (Entry<ObjectMarshallingStrategy, Integer> entry : context.getUsedStrategies().entrySet()) {
        Builder _strat = ProtobufMessages.Header.StrategyIndex.newBuilder().setId(entry.getValue().intValue()).setName(entry.getKey().getName());
        Context ctx = context.getStrategyContext().get(entry.getKey());
        if (ctx != null) {
            Output os = ByteString.newOutput();
            ctx.write(new DroolsObjectOutputStream(os));
            _strat.setData(os.toByteString());
            os.close();
        }
        _header.addStrategy(_strat.build());
    }
}
Also used : Context(org.kie.api.marshalling.ObjectMarshallingStrategy.Context) MarshallerReaderContext(org.drools.core.marshalling.MarshallerReaderContext) MarshallerWriteContext(org.drools.core.marshalling.MarshallerWriteContext) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) Builder(org.drools.serialization.protobuf.ProtobufMessages.Header.StrategyIndex.Builder) Output(com.google.protobuf.ByteString.Output) DroolsObjectOutputStream(org.drools.core.common.DroolsObjectOutputStream)

Aggregations

ObjectMarshallingStrategy (org.kie.api.marshalling.ObjectMarshallingStrategy)52 ArrayList (java.util.ArrayList)11 InternalFactHandle (org.drools.core.common.InternalFactHandle)9 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)8 EventFactHandle (org.drools.core.common.EventFactHandle)8 IOException (java.io.IOException)7 ObjectInputStream (java.io.ObjectInputStream)7 HashMap (java.util.HashMap)7 ObjectMarshallingStrategyAcceptor (org.kie.api.marshalling.ObjectMarshallingStrategyAcceptor)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 QueryElementFactHandle (org.drools.core.common.QueryElementFactHandle)6 ObjectTypeConf (org.drools.core.reteoo.ObjectTypeConf)6 Marshaller (org.kie.api.marshalling.Marshaller)6 SerializablePlaceholderResolverStrategy (org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy)5 Test (org.junit.Test)5 Environment (org.kie.api.runtime.Environment)5 KieSession (org.kie.api.runtime.KieSession)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 File (java.io.File)4 Collection (java.util.Collection)4