Search in sources :

Example 11 with ProjectClassLoader

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

the class PersisterHelper method writeRuntimeDefinedClasses.

public static void writeRuntimeDefinedClasses(MarshallerWriteContext context, ProtobufMessages.Header.Builder _header) {
    if (context.kBase == null) {
        return;
    }
    ProjectClassLoader pcl = (ProjectClassLoader) (context.kBase).getRootClassLoader();
    if (pcl.getStore() == null || pcl.getStore().isEmpty()) {
        return;
    }
    TraitFactory traitFactory = TraitFactory.getTraitBuilderForKnowledgeBase(context.kBase);
    List<String> runtimeClassNames = new ArrayList(pcl.getStore().keySet());
    Collections.sort(runtimeClassNames);
    ProtobufMessages.RuntimeClassDef.Builder _classDef = ProtobufMessages.RuntimeClassDef.newBuilder();
    for (String resourceName : runtimeClassNames) {
        if (traitFactory.isRuntimeClass(resourceName)) {
            _classDef.clear();
            _classDef.setClassFqName(resourceName);
            _classDef.setClassDef(ByteString.copyFrom(pcl.getStore().get(resourceName)));
            _header.addRuntimeClassDefinitions(_classDef.build());
        }
    }
}
Also used : ProjectClassLoader(org.drools.core.common.ProjectClassLoader) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) TraitFactory(org.drools.core.factmodel.traits.TraitFactory)

Example 12 with ProjectClassLoader

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

the class KnowledgeBaseImpl method internalRemoveFunction.

private void internalRemoveFunction(String packageName, String functionName) {
    final InternalKnowledgePackage pkg = this.pkgs.get(packageName);
    if (pkg == null) {
        throw new IllegalArgumentException("Package name '" + packageName + "' does not exist for this Rule Base.");
    }
    Function function = pkg.getFunctions().get(functionName);
    if (function == null) {
        throw new IllegalArgumentException("function name '" + packageName + "' does not exist in the Package '" + packageName + "'.");
    }
    this.eventSupport.fireBeforeFunctionRemoved(pkg, functionName);
    pkg.removeFunction(functionName);
    this.eventSupport.fireAfterFunctionRemoved(pkg, functionName);
    if (rootClassLoader instanceof ProjectClassLoader) {
        ((ProjectClassLoader) rootClassLoader).undefineClass(function.getClassName());
    }
    addReloadDialectDatas(pkg.getDialectRuntimeRegistry());
}
Also used : ProjectClassLoader.createProjectClassLoader(org.drools.core.common.ProjectClassLoader.createProjectClassLoader) ProjectClassLoader(org.drools.core.common.ProjectClassLoader) Function(org.drools.core.rule.Function) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 13 with ProjectClassLoader

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

the class KnowledgePackageImpl method deepCloneIfAlreadyInUse.

public KnowledgePackageImpl deepCloneIfAlreadyInUse(ClassLoader classLoader) {
    if (inUse.compareAndSet(false, true)) {
        return this;
    }
    if (classLoader instanceof ProjectClassLoader) {
        JavaDialectRuntimeData javaDialectRuntimeData = (JavaDialectRuntimeData) dialectRuntimeRegistry.getDialectData("java");
        if (javaDialectRuntimeData == null) {
            // using the canonical model there's no runtime registry and no need for any clone
            return this;
        }
        ClassLoader originalClassLoader = javaDialectRuntimeData.getRootClassLoader();
        if (classLoader == originalClassLoader) {
            // if the classloader isn't changed there's no need for a clone
            return this;
        }
        if (originalClassLoader instanceof ProjectClassLoader) {
            ((ProjectClassLoader) classLoader).initFrom((ProjectClassLoader) originalClassLoader);
        }
    }
    return ClassUtils.deepClone(this, classLoader, cloningResources);
}
Also used : ProjectClassLoader(org.drools.core.common.ProjectClassLoader) ProjectClassLoader(org.drools.core.common.ProjectClassLoader) JavaDialectRuntimeData(org.drools.core.rule.JavaDialectRuntimeData)

Example 14 with ProjectClassLoader

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

the class DroolsJaxbHelperProviderImpl method addXsdModel.

public static String[] addXsdModel(Resource resource, KnowledgeBuilderImpl kBuilder, Options xjcOpts, String systemId) throws IOException {
    InputSource source = new InputSource(new CachingRewindableReader(resource.getReader()));
    source.setSystemId(systemId.trim().startsWith(".") ? systemId : "." + systemId);
    xjcOpts.addGrammar(source);
    try {
        xjcOpts.parseArguments(new String[] { "-npa" });
    } catch (BadCommandLineException e) {
        throw new IllegalArgumentException("Unable to parse arguments", e);
    }
    ErrorReceiver errorReceiver = new JaxbErrorReceiver4Drools();
    Model model = ModelLoader.load(xjcOpts, new JCodeModel(), errorReceiver);
    model.generateCode(xjcOpts, errorReceiver);
    MapVfsCodeWriter codeWriter = new MapVfsCodeWriter();
    model.codeModel.build(xjcOpts.createCodeWriter(codeWriter));
    MemoryResourceReader src = new MemoryResourceReader();
    boolean useProjectClassLoader = kBuilder.getRootClassLoader() instanceof ProjectClassLoader;
    List<String> classNames = new ArrayList<String>();
    List<String> srcNames = new ArrayList<String>();
    for (Entry<String, byte[]> entry : codeWriter.getMap().entrySet()) {
        String name = entry.getKey();
        int dotPos = name.lastIndexOf('.');
        String pkgName = name.substring(0, dotPos);
        if (!name.endsWith("package-info.java")) {
            classNames.add(pkgName);
        }
        dotPos = pkgName.lastIndexOf('.');
        if (dotPos != -1) {
            pkgName = pkgName.substring(0, dotPos);
        }
        PackageRegistry pkgReg = kBuilder.getPackageRegistry(pkgName);
        if (pkgReg == null) {
            kBuilder.addPackage(new PackageDescr(pkgName));
            pkgReg = kBuilder.getPackageRegistry(pkgName);
        }
        if (useProjectClassLoader) {
            String srcName = convertToResource(entry.getKey());
            src.add(srcName, entry.getValue());
            srcNames.add(srcName);
        } else {
            JavaDialect dialect = (JavaDialect) pkgReg.getDialectCompiletimeRegistry().getDialect("java");
            dialect.addSrc(convertToResource(entry.getKey()), entry.getValue());
        }
    }
    if (useProjectClassLoader) {
        ProjectJavaCompiler compiler = new ProjectJavaCompiler(kBuilder.getBuilderConfiguration());
        List<KnowledgeBuilderResult> results = compiler.compileAll((ProjectClassLoader) kBuilder.getRootClassLoader(), srcNames, src);
        for (String className : classNames) {
            Class<?> clazz = null;
            try {
                clazz = Class.forName(className, true, kBuilder.getRootClassLoader());
            } catch (ClassNotFoundException e) {
                continue;
            }
            String pkgName = className.substring(0, className.lastIndexOf('.'));
            PackageRegistry pkgReg = kBuilder.getPackageRegistry(pkgName);
            pkgReg.getPackage().addTypeDeclaration(TypeDeclaration.createTypeDeclarationForBean(clazz));
        }
        kBuilder.updateResults(results);
    } else {
        kBuilder.compileAll();
        kBuilder.updateResults();
    }
    return classNames.toArray(new String[classNames.size()]);
}
Also used : InputSource(org.xml.sax.InputSource) ArrayList(java.util.ArrayList) ErrorReceiver(com.sun.tools.xjc.ErrorReceiver) MemoryResourceReader(org.drools.compiler.commons.jci.readers.MemoryResourceReader) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) ProjectClassLoader(org.drools.core.common.ProjectClassLoader) BadCommandLineException(com.sun.tools.xjc.BadCommandLineException) ProjectJavaCompiler(org.drools.compiler.compiler.ProjectJavaCompiler) JCodeModel(com.sun.codemodel.JCodeModel) JavaDialect(org.drools.compiler.rule.builder.dialect.java.JavaDialect) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) Model(com.sun.tools.xjc.model.Model) JCodeModel(com.sun.codemodel.JCodeModel) KnowledgeBuilderResult(org.kie.internal.builder.KnowledgeBuilderResult)

Example 15 with ProjectClassLoader

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

the class InstancesHashcodedTest method build.

/*
        <dimension name="bck_cycle_dm"  item-expression="cycleDimension"
                   mode="ignore" cache="10" export-to="cycle_id">
            <id    name="objid"            type="long"             generator-sql="select bck_dimensions_uid.nextval from dual"/>
            <field name="cut_date"         type="java.util.Date"   value="cutDate"     key="true"/>
            <field name="due_date"         type="java.util.Date"   value="dueDate"     key="true"/>
            <field name="cycle_code"       type="java.lang.String" value="cycleCode"/>
            <field name="issue_date"       type="java.util.Date"   value="issueDate"/>
        </dimension>
 */
private Class build(ClassBuilder builder, ClassDefinition classDef) throws Exception {
    ProjectClassLoader prjClassLoader = ProjectClassLoader.createProjectClassLoader();
    byte[] d = builder.buildClass(classDef, prjClassLoader);
    JavaDialectRuntimeData data = new JavaDialectRuntimeData();
    data.write(convertClassToResourcePath(classDef.getClassName()), d);
    ClassLoader classLoader = new PackageClassLoader(data, prjClassLoader);
    ClassFieldAccessorStore store = new ClassFieldAccessorStore();
    store.setClassFieldAccessorCache(new ClassFieldAccessorCache(classLoader));
    store.setEagerWire(true);
    Class clazz = classLoader.loadClass(classDef.getClassName());
    classDef.setDefinedClass(clazz);
    return clazz;
}
Also used : ProjectClassLoader(org.drools.core.common.ProjectClassLoader) ClassFieldAccessorCache(org.drools.core.base.ClassFieldAccessorCache) PackageClassLoader(org.drools.core.rule.JavaDialectRuntimeData.PackageClassLoader) ProjectClassLoader(org.drools.core.common.ProjectClassLoader) ClassFieldAccessorStore(org.drools.core.base.ClassFieldAccessorStore) JavaDialectRuntimeData(org.drools.core.rule.JavaDialectRuntimeData) PackageClassLoader(org.drools.core.rule.JavaDialectRuntimeData.PackageClassLoader)

Aggregations

ProjectClassLoader (org.drools.core.common.ProjectClassLoader)17 ArrayList (java.util.ArrayList)3 JavaDialectRuntimeData (org.drools.core.rule.JavaDialectRuntimeData)3 Before (org.junit.Before)3 KnowledgeBaseImpl (org.drools.core.impl.KnowledgeBaseImpl)2 ByteString (com.google.protobuf.ByteString)1 JCodeModel (com.sun.codemodel.JCodeModel)1 BadCommandLineException (com.sun.tools.xjc.BadCommandLineException)1 ErrorReceiver (com.sun.tools.xjc.ErrorReceiver)1 Model (com.sun.tools.xjc.model.Model)1 XStream (com.thoughtworks.xstream.XStream)1 ExplicitTypePermission (com.thoughtworks.xstream.security.ExplicitTypePermission)1 IOException (java.io.IOException)1 ObjectInput (java.io.ObjectInput)1 ObjectOutput (java.io.ObjectOutput)1 URL (java.net.URL)1 URLClassLoader (java.net.URLClassLoader)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1