Search in sources :

Example 96 with ObjectOutput

use of java.io.ObjectOutput in project drools by kiegroup.

the class FieldConstraintTest method testPredicateConstraint.

/**
 * <pre>
 *
 *                (Cheese (price ?price1 )
 *                (Cheese (price ?price2&amp;:(= ?price2 (* 2 ?price1) )
 *
 * </pre>
 */
@Test
public void testPredicateConstraint() {
    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    ;
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final InternalReadAccessor priceExtractor = store.getReader(Cheese.class, "price");
    Pattern pattern = new Pattern(0, new ClassObjectType(Cheese.class));
    // Bind the extractor to a decleration
    // Declarations know the pattern they derive their value form
    final Declaration price1Declaration = new Declaration("price1", priceExtractor, pattern);
    pattern = new Pattern(1, new ClassObjectType(Cheese.class));
    // Bind the extractor to a decleration
    // Declarations know the pattern they derive their value form
    final Declaration price2Declaration = new Declaration("price2", priceExtractor, pattern);
    final PredicateExpression evaluator = new PredicateExpression() {

        private static final long serialVersionUID = 510l;

        public boolean evaluate(InternalFactHandle handle, Tuple tuple, Declaration[] previousDeclarations, Declaration[] localDeclarations, ReteEvaluator reteEvaluator, Object context) {
            int price1 = previousDeclarations[0].getIntValue(reteEvaluator, tuple.getObject(previousDeclarations[0]));
            int price2 = localDeclarations[0].getIntValue(reteEvaluator, handle.getObject());
            return (price2 == (price1 * 2));
        }

        public Object createContext() {
            return null;
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        }

        public void writeExternal(ObjectOutput out) throws IOException {
        }
    };
    final PredicateConstraint constraint1 = new PredicateConstraint(evaluator, new Declaration[] { price1Declaration }, new Declaration[] { price2Declaration });
    final Cheese cheddar0 = new Cheese("cheddar", 5);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar0);
    LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
    final Cheese cheddar1 = new Cheese("cheddar", 10);
    final InternalFactHandle f1 = (InternalFactHandle) ksession.insert(cheddar1);
    tuple = new LeftTupleImpl(tuple, new RightTupleImpl(f1, null), null, true);
    final PredicateContextEntry context = (PredicateContextEntry) constraint1.createContextEntry();
    context.updateFromTuple(ksession, tuple);
    assertTrue(constraint1.isAllowedCachedLeft(context, f1));
}
Also used : ReteEvaluator(org.drools.core.common.ReteEvaluator) Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectOutput(java.io.ObjectOutput) Cheese(org.drools.mvel.model.Cheese) PredicateExpression(org.drools.core.spi.PredicateExpression) RightTupleImpl(org.drools.core.reteoo.RightTupleImpl) AlphaNodeFieldConstraint(org.drools.core.spi.AlphaNodeFieldConstraint) PredicateConstraint(org.drools.core.rule.PredicateConstraint) PredicateContextEntry(org.drools.core.rule.PredicateConstraint.PredicateContextEntry) StatefulKnowledgeSessionImpl(org.drools.kiesession.session.StatefulKnowledgeSessionImpl) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) LeftTupleImpl(org.drools.core.reteoo.LeftTupleImpl) Declaration(org.drools.core.rule.Declaration) ObjectInput(java.io.ObjectInput) PredicateConstraint(org.drools.core.rule.PredicateConstraint) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.kiesession.rulebase.InternalKnowledgeBase) Tuple(org.drools.core.spi.Tuple) Test(org.junit.Test)

Example 97 with ObjectOutput

use of java.io.ObjectOutput in project drools by kiegroup.

the class KnowledgeBaseEventSupportTest method setUp.

/* (non-Javadoc)
     * @see junit.framework.TestCase#setUp()
     */
@Before
public void setUp() throws Exception {
    kbase = KnowledgeBaseFactory.newKnowledgeBase();
    listener1 = new TestRuleBaseListener("(listener-1) ");
    listener2 = new TestRuleBaseListener("(listener-2) ");
    kbase.addEventListener(listener1);
    kbase.addEventListener(listener2);
    final RuleImpl rule1 = new RuleImpl("test1");
    final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjectType);
    ClassFieldAccessorStore store = new ClassFieldAccessorStore();
    store.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);
    AlphaNodeFieldConstraint constraint = ConstraintTestUtil.createCheeseTypeEqualsConstraint(store, "cheddar", useLambdaConstraint);
    pattern.addConstraint(constraint);
    rule1.addPattern(pattern);
    rule1.setConsequence(new Consequence() {

        private static final long serialVersionUID = 510l;

        public void evaluate(final KnowledgeHelper knowledgeHelper, final ReteEvaluator reteEvaluator) throws Exception {
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        }

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            return "default";
        }
    });
    final RuleImpl rule2 = new RuleImpl("test2");
    final ClassObjectType cheeseObjectType2 = new ClassObjectType(Cheese.class);
    final Pattern pattern2 = new Pattern(0, cheeseObjectType2);
    AlphaNodeFieldConstraint constraint2 = ConstraintTestUtil.createCheeseTypeEqualsConstraint(store, "stilton", useLambdaConstraint);
    pattern2.addConstraint(constraint2);
    rule2.addPattern(pattern2);
    rule2.setConsequence(new Consequence() {

        private static final long serialVersionUID = 510l;

        public void evaluate(final KnowledgeHelper knowledgeHelper, final ReteEvaluator reteEvaluator) throws Exception {
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        }

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            return "default";
        }
    });
    pkg = CoreComponentFactory.get().createKnowledgePackage("org.drools.test1");
    pkg.addRule(rule1);
    pkg.addRule(rule2);
}
Also used : ReteEvaluator(org.drools.core.common.ReteEvaluator) Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectOutput(java.io.ObjectOutput) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) ClassFieldAccessorStore(org.drools.mvel.accessors.ClassFieldAccessorStore) IOException(java.io.IOException) IOException(java.io.IOException) ClassFieldAccessorCache(org.drools.core.base.ClassFieldAccessorCache) AlphaNodeFieldConstraint(org.drools.core.spi.AlphaNodeFieldConstraint) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) ObjectInput(java.io.ObjectInput) Before(org.junit.Before)

Example 98 with ObjectOutput

use of java.io.ObjectOutput in project drools by kiegroup.

the class TraitKnowledgePackageImpl method writeExternal.

@Override
public void writeExternal(ObjectOutput stream) throws IOException {
    ByteArrayOutputStream bytes = null;
    ObjectOutput out;
    if (stream instanceof DroolsObjectOutputStream) {
        out = stream;
    } else {
        bytes = new ByteArrayOutputStream();
        out = new DroolsObjectOutputStream(bytes);
    }
    try {
        out.writeObject(this.name);
        out.writeObject(this.classFieldAccessorStore);
        out.writeObject(this.dialectRuntimeRegistry);
        out.writeObject(this.typeDeclarations);
        out.writeObject(this.imports);
        out.writeObject(this.staticImports);
        out.writeObject(this.functions);
        out.writeObject(this.accumulateFunctions);
        out.writeObject(this.factTemplates);
        out.writeObject(this.globals);
        out.writeBoolean(this.valid);
        out.writeBoolean(this.needStreamMode);
        out.writeObject(this.rules);
        out.writeObject(this.entryPointsIds);
        out.writeObject(this.windowDeclarations);
        out.writeObject(this.traitRegistry);
        out.writeObject(this.resourceTypePackages);
    } finally {
        // writing the whole stream as a byte array
        if (bytes != null) {
            bytes.flush();
            bytes.close();
            stream.writeObject(bytes.toByteArray());
        }
    }
}
Also used : ObjectOutput(java.io.ObjectOutput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DroolsObjectOutputStream(org.drools.core.common.DroolsObjectOutputStream)

Example 99 with ObjectOutput

use of java.io.ObjectOutput in project kie-wb-common by kiegroup.

the class KieAfterDecorator method readObjectFromADifferentClassloader.

private KieTuple readObjectFromADifferentClassloader(Object o) {
    ObjectInput in = null;
    ObjectOutput out;
    ByteArrayInputStream bis;
    ByteArrayOutputStream bos = null;
    try {
        bos = new ByteArrayOutputStream();
        out = new ObjectOutputStream(bos);
        out.writeObject(o);
        out.flush();
        byte[] objBytes = bos.toByteArray();
        bis = new ByteArrayInputStream(objBytes);
        in = new ObjectInputStream(bis);
        Object newObj = in.readObject();
        return new KieTuple(newObj);
    } catch (NotSerializableException nse) {
        logger.warn("Object it not serializable {}", nse.getMessage());
        StringBuilder sb = new StringBuilder("NotSerializableException:").append(nse.getMessage());
        return new KieTuple(sb.toString());
    } catch (IOException ioe) {
        StringBuilder sb = new StringBuilder("IOException:").append(ioe.getMessage());
        return new KieTuple(sb.toString());
    } catch (ClassNotFoundException cnfe) {
        StringBuilder sb = new StringBuilder("ClassNotFoundException:").append(cnfe.getMessage());
        return new KieTuple(sb.toString());
    } catch (Exception e) {
        StringBuilder sb = new StringBuilder("Exception:").append(e.getMessage());
        return new KieTuple(sb.toString());
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
}
Also used : ObjectOutput(java.io.ObjectOutput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ObjectOutputStream(java.io.ObjectOutputStream) IOException(java.io.IOException) NotSerializableException(java.io.NotSerializableException) NotSerializableException(java.io.NotSerializableException) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(java.io.ObjectInput) ObjectInputStream(java.io.ObjectInputStream)

Example 100 with ObjectOutput

use of java.io.ObjectOutput in project wildfly by wildfly.

the class DsTestCase method testDatasourceSerialization.

@Test
public void testDatasourceSerialization() throws Exception {
    InitialContext context = new InitialContext();
    DataSource originalDs = (DataSource) context.lookup(JNDI_NAME);
    // serialize
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;
    DataSource ds;
    ObjectInput in = null;
    try {
        out = new ObjectOutputStream(bos);
        out.writeObject(originalDs);
        byte[] bytes = bos.toByteArray();
        // deserialize
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        try {
            in = new ObjectInputStream(bis);
            ds = (DataSource) in.readObject();
        } finally {
            try {
                bis.close();
            } catch (IOException ex) {
            // ignore close exception
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
            // ignore close exception
            }
        }
        // use
        Connection conn = ds.getConnection();
        ResultSet rs = conn.prepareStatement("select 1").executeQuery();
        Assert.assertTrue(rs.next());
        conn.close();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
        // ignore close exception
        }
        try {
            bos.close();
        } catch (IOException ex) {
        // ignore close exception
        }
    }
}
Also used : ObjectOutput(java.io.ObjectOutput) ByteArrayInputStream(java.io.ByteArrayInputStream) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectInput(java.io.ObjectInput) IOException(java.io.IOException) ObjectOutputStream(java.io.ObjectOutputStream) InitialContext(javax.naming.InitialContext) WildFlyDataSource(org.jboss.as.connector.subsystems.datasources.WildFlyDataSource) DataSource(javax.sql.DataSource) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Aggregations

ObjectOutput (java.io.ObjectOutput)123 ObjectOutputStream (java.io.ObjectOutputStream)88 ByteArrayOutputStream (java.io.ByteArrayOutputStream)76 IOException (java.io.IOException)63 ObjectInput (java.io.ObjectInput)38 ObjectInputStream (java.io.ObjectInputStream)28 ByteArrayInputStream (java.io.ByteArrayInputStream)26 Test (org.junit.Test)23 Pattern (org.drools.core.rule.Pattern)16 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)15 Consequence (org.drools.core.spi.Consequence)15 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)15 FileOutputStream (java.io.FileOutputStream)13 OutputStream (java.io.OutputStream)12 WorkingMemory (org.drools.core.WorkingMemory)12 ClassObjectType (org.drools.core.base.ClassObjectType)10 Declaration (org.drools.core.rule.Declaration)10 Test (org.junit.jupiter.api.Test)9 File (java.io.File)8 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)8