Search in sources :

Example 11 with DroolsObjectInputStream

use of org.drools.core.common.DroolsObjectInputStream in project drools by kiegroup.

the class SerializedPackageMergeTwoSteps2Test method _deserializeFromBytes.

private Collection<KiePackage> _deserializeFromBytes(byte[] byteCode) {
    Collection<KiePackage> ret = null;
    ByteArrayInputStream bis = null;
    ObjectInput in = null;
    try {
        bis = new ByteArrayInputStream(byteCode);
        in = new DroolsObjectInputStream(bis);
        ret = (Collection<KiePackage>) in.readObject();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (bis != null)
                bis.close();
            if (in != null)
                in.close();
        } catch (IOException e) {
        }
    }
    return ret;
}
Also used : DroolsObjectInputStream(org.drools.core.common.DroolsObjectInputStream) KiePackage(org.kie.api.definition.KiePackage) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(java.io.ObjectInput) IOException(java.io.IOException) ParseException(java.text.ParseException) IOException(java.io.IOException)

Example 12 with DroolsObjectInputStream

use of org.drools.core.common.DroolsObjectInputStream in project drools by kiegroup.

the class SerializedPackageMergeTwoSteps2Test method testBuildAndSerializePackagesInTwoSteps2.

@Test
public void testBuildAndSerializePackagesInTwoSteps2() throws IOException, ClassNotFoundException {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    // Read the two serialized knowledgePackages
    for (String fileName : SerializedPackageMergeTwoSteps1Test.BINPKG) {
        Collection<KiePackage> kpkgs = null;
        byte[] data = null;
        try {
            data = Files.readAllBytes(Paths.get(fileName));
        } catch (java.nio.file.NoSuchFileException ex) {
            // bin file does not exist, finish test
            return;
        }
        kpkgs = _deserializeFromBytes(data);
        if (kpkgs != null)
            kbase.addPackages(kpkgs);
    }
    Collection<KiePackage> knowledgePackagesCombined = kbase.getKiePackages();
    // serialize
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new DroolsObjectOutputStream(baos);
    out.writeObject(knowledgePackagesCombined);
    out.flush();
    out.close();
    // deserialize
    ObjectInputStream in = new DroolsObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    Collection<KiePackage> deserializedPackages = (Collection<KiePackage>) in.readObject();
    // Use the deserialized knowledgePackages
    InternalKnowledgeBase kbase2 = KnowledgeBaseFactory.newKnowledgeBase();
    kbase2.addPackages(deserializedPackages);
    KieSession ksession = kbase2.newKieSession();
    List<String> list = new ArrayList<String>();
    ksession.setGlobal("list", list);
    ksession.insert(new org.drools.compiler.Person("John"));
    ksession.fireAllRules();
    assertEquals(2, list.size());
    ksession.dispose();
}
Also used : DroolsObjectInputStream(org.drools.core.common.DroolsObjectInputStream) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DroolsObjectOutputStream(org.drools.core.common.DroolsObjectOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) KiePackage(org.kie.api.definition.KiePackage) ByteArrayInputStream(java.io.ByteArrayInputStream) Collection(java.util.Collection) KieSession(org.kie.api.runtime.KieSession) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) DroolsObjectOutputStream(org.drools.core.common.DroolsObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream) DroolsObjectInputStream(org.drools.core.common.DroolsObjectInputStream) Test(org.junit.Test)

Example 13 with DroolsObjectInputStream

use of org.drools.core.common.DroolsObjectInputStream in project drools by kiegroup.

the class KnowledgeBaseImpl method readExternal.

// ------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------
/**
 * Handles the read serialization of the Package. Patterns in Rules may reference generated data which cannot be serialized by default methods.
 * The Package uses PackageCompilationData to hold a reference to the generated bytecode; which must be restored before any Rules.
 * A custom ObjectInputStream, able to resolve classes against the bytecode in the PackageCompilationData, is used to restore the Rules.
 */
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
    // PackageCompilationData must be restored before Rules as it has the ClassLoader needed to resolve the generated code references in Rules
    DroolsObjectInput droolsStream;
    boolean isDrools = in instanceof DroolsObjectInputStream;
    boolean wasDrools = in.readBoolean();
    if (wasDrools && !isDrools) {
        throw new IllegalArgumentException("The knowledge base was serialized using a DroolsObjectOutputStream. A DroolsObjectInputStream is required for deserialization.");
    }
    if (isDrools) {
        droolsStream = (DroolsObjectInput) in;
    } else {
        ByteArrayInputStream bytes = new ByteArrayInputStream((byte[]) in.readObject());
        droolsStream = new DroolsObjectInputStream(bytes);
    }
    boolean classLoaderCacheEnabled = droolsStream.readBoolean();
    Map<String, byte[]> store = (Map<String, byte[]>) droolsStream.readObject();
    this.rootClassLoader = createProjectClassLoader(droolsStream.getParentClassLoader(), store);
    droolsStream.setClassLoader(this.rootClassLoader);
    droolsStream.setKnowledgeBase(this);
    this.classFieldAccessorCache = new ClassFieldAccessorCache(this.rootClassLoader);
    this.config = (RuleBaseConfiguration) droolsStream.readObject();
    this.config.setClassLoader(droolsStream.getParentClassLoader());
    this.sessionConfiguration = new SessionConfigurationImpl(null, config.getClassLoader(), config.getChainedProperties());
    kieComponentFactory = getConfiguration().getComponentFactory();
    this.pkgs = (Map<String, InternalKnowledgePackage>) droolsStream.readObject();
    for (InternalKnowledgePackage pkg : this.pkgs.values()) {
        pkg.getDialectRuntimeRegistry().onAdd(this.rootClassLoader);
    }
    // PackageCompilationData must be restored before Rules as it has the ClassLoader needed to resolve the generated code references in Rules
    this.id = (String) droolsStream.readObject();
    this.workingMemoryCounter.set(droolsStream.readInt());
    this.processes = (Map<String, Process>) droolsStream.readObject();
    Class cls = null;
    try {
        cls = droolsStream.getParentClassLoader().loadClass(droolsStream.readUTF());
        this.factHandleFactory = (FactHandleFactory) cls.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        DroolsObjectInputStream.newInvalidClassException(cls, e);
    }
    for (InternalKnowledgePackage pkg : this.pkgs.values()) {
        pkg.getDialectRuntimeRegistry().onBeforeExecute();
        pkg.getClassFieldAccessorStore().setClassFieldAccessorCache(this.classFieldAccessorCache);
        pkg.getClassFieldAccessorStore().wire();
    }
    this.populateTypeDeclarationMaps();
    // read globals
    Map<String, String> globs = (Map<String, String>) droolsStream.readObject();
    populateGlobalsMap(globs);
    this.eventSupport = (KieBaseEventSupport) droolsStream.readObject();
    this.eventSupport.setKnowledgeBase(this);
    this.reteooBuilder = (ReteooBuilder) droolsStream.readObject();
    this.reteooBuilder.setRuleBase(this);
    this.rete = (Rete) droolsStream.readObject();
    this.resolvedReleaseId = (ReleaseId) droolsStream.readObject();
    ((DroolsObjectInputStream) droolsStream).bindAllExtractors(this);
    if (!isDrools) {
        droolsStream.close();
    }
    this.getConfiguration().getComponentFactory().getTraitFactory().setRuleBase(this);
    rewireReteAfterDeserialization();
}
Also used : DroolsObjectInputStream(org.drools.core.common.DroolsObjectInputStream) Process(org.kie.api.definition.process.Process) ClassFieldAccessorCache(org.drools.core.base.ClassFieldAccessorCache) DroolsObjectInput(org.drools.core.common.DroolsObjectInput) ByteArrayInputStream(java.io.ByteArrayInputStream) SessionConfigurationImpl(org.drools.core.SessionConfigurationImpl) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 14 with DroolsObjectInputStream

use of org.drools.core.common.DroolsObjectInputStream in project drools by kiegroup.

the class KnowledgePackageImpl method readExternal.

/**
 * Handles the read serialization of the Package. Patterns in Rules may
 * reference generated data which cannot be serialized by default methods.
 * The Package uses PackageCompilationData to hold a reference to the
 * generated bytecode; which must be restored before any Rules. A custom
 * ObjectInputStream, able to resolve classes against the bytecode in the
 * PackageCompilationData, is used to restore the Rules.
 *
 * @param stream, the stream to read data from in order to restore the object;
 *                should be an instance of DroolsObjectInputStream or
 *                InputStream
 */
public void readExternal(ObjectInput stream) throws IOException, ClassNotFoundException {
    boolean isDroolsStream = stream instanceof DroolsObjectInputStream;
    DroolsObjectInputStream in = isDroolsStream ? (DroolsObjectInputStream) stream : new DroolsObjectInputStream(new ByteArrayInputStream((byte[]) stream.readObject()));
    this.name = (String) in.readObject();
    this.classFieldAccessorStore = (ClassFieldAccessorStore) in.readObject();
    in.setStore(this.classFieldAccessorStore);
    this.dialectRuntimeRegistry = (DialectRuntimeRegistry) in.readObject();
    this.typeDeclarations = (Map) in.readObject();
    this.imports = (Map<String, ImportDeclaration>) in.readObject();
    this.staticImports = (Set) in.readObject();
    this.functions = (Map<String, Function>) in.readObject();
    this.accumulateFunctions = (Map<String, AccumulateFunction>) in.readObject();
    this.factTemplates = (Map) in.readObject();
    this.ruleFlows = (Map) in.readObject();
    this.globals = (Map<String, String>) in.readObject();
    this.valid = in.readBoolean();
    this.needStreamMode = in.readBoolean();
    this.rules = (Map<String, RuleImpl>) in.readObject();
    this.entryPointsIds = (Set<String>) in.readObject();
    this.windowDeclarations = (Map<String, WindowDeclaration>) in.readObject();
    this.traitRegistry = (TraitRegistry) in.readObject();
    this.resourceTypePackages = (Map<ResourceType, ResourceTypePackage>) in.readObject();
    in.setStore(null);
    if (!isDroolsStream) {
        in.close();
    }
}
Also used : DroolsObjectInputStream(org.drools.core.common.DroolsObjectInputStream) Function(org.drools.core.rule.Function) AccumulateFunction(org.kie.api.runtime.rule.AccumulateFunction) ByteArrayInputStream(java.io.ByteArrayInputStream) WindowDeclaration(org.drools.core.rule.WindowDeclaration) ImportDeclaration(org.drools.core.rule.ImportDeclaration) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) ResourceType(org.kie.api.io.ResourceType) AccumulateFunction(org.kie.api.runtime.rule.AccumulateFunction) ResourceTypePackage(org.kie.api.internal.io.ResourceTypePackage)

Example 15 with DroolsObjectInputStream

use of org.drools.core.common.DroolsObjectInputStream in project drools by kiegroup.

the class ClassUtils method deepClone.

public static <T extends Externalizable> T deepClone(T origin, ClassLoader classLoader, Map<String, Object> cloningResources) {
    if (origin == null) {
        return null;
    }
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DroolsObjectOutputStream oos = new DroolsObjectOutputStream(baos);
        if (cloningResources != null) {
            cloningResources.forEach((k, v) -> oos.addCustomExtensions(k, v));
        }
        oos.writeObject(origin);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        DroolsObjectInputStream ois = new DroolsObjectInputStream(bais, classLoader);
        if (cloningResources != null) {
            cloningResources.forEach((k, v) -> ois.addCustomExtensions(k, v));
        }
        Object deepCopy = ois.readObject();
        return (T) deepCopy;
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    }
}
Also used : DroolsObjectInputStream(org.drools.core.common.DroolsObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DroolsObjectOutputStream(org.drools.core.common.DroolsObjectOutputStream)

Aggregations

DroolsObjectInputStream (org.drools.core.common.DroolsObjectInputStream)16 ByteArrayInputStream (java.io.ByteArrayInputStream)12 DroolsObjectOutputStream (org.drools.core.common.DroolsObjectOutputStream)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 Test (org.junit.Test)6 KieBase (org.kie.api.KieBase)6 ObjectInputStream (java.io.ObjectInputStream)5 KieSession (org.kie.api.runtime.KieSession)5 ObjectOutputStream (java.io.ObjectOutputStream)4 ArrayList (java.util.ArrayList)3 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)3 KiePackage (org.kie.api.definition.KiePackage)3 Marshaller (org.kie.api.marshalling.Marshaller)3 IOException (java.io.IOException)2 Collection (java.util.Collection)2 EOFException (java.io.EOFException)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 ObjectInput (java.io.ObjectInput)1