Search in sources :

Example 11 with ProjectClassLoader

use of org.drools.wiring.api.classloader.ProjectClassLoader in project drools by kiegroup.

the class ClassLoaderLeakTest method buildKjarsInALoop.

private void buildKjarsInALoop(boolean withExecModel) {
    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();
    KieContainer kieContainer = null;
    int oldSize = Integer.MAX_VALUE;
    for (int i = 0; i < 3; i++) {
        KieModule kModule = buildKieModule("1.0." + i, RULES, withExecModel);
        if (kieContainer == null) {
            kieContainer = ks.newKieContainer(kModule.getReleaseId());
        } else {
            kieContainer.updateToVersion(kModule.getReleaseId());
        }
        KieProject kp = ((KieContainerImpl) kieContainer).getKieProject();
        ProjectClassLoader cl = (ProjectClassLoader) kp.getClassLoader();
        System.out.println(String.format("ProjectClassLoader.store size: %d, " + "retained bytes: %d.", cl.getStore().size(), cl.getStore().values().stream().map(b -> b.length).reduce(0, Integer::sum)));
        assertTrue(cl.getStore().size() <= oldSize);
        oldSize = cl.getStore().size();
        kr.removeKieModule(kModule.getReleaseId());
    }
}
Also used : ProjectClassLoader(org.drools.wiring.api.classloader.ProjectClassLoader) KieFileSystem(org.kie.api.builder.KieFileSystem) KieBuilder(org.kie.api.builder.KieBuilder) KieProject(org.drools.compiler.kie.builder.impl.KieProject) KieContainer(org.kie.api.runtime.KieContainer) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) KieRepository(org.kie.api.builder.KieRepository) ReleaseId(org.kie.api.builder.ReleaseId) KieModule(org.kie.api.builder.KieModule) KieModuleModel(org.kie.api.builder.model.KieModuleModel) KieServices(org.kie.api.KieServices) Message(org.kie.api.builder.Message) KieContainerImpl(org.drools.compiler.kie.builder.impl.KieContainerImpl) ProjectClassLoader(org.drools.wiring.api.classloader.ProjectClassLoader) KieRepository(org.kie.api.builder.KieRepository) KieProject(org.drools.compiler.kie.builder.impl.KieProject) KieContainerImpl(org.drools.compiler.kie.builder.impl.KieContainerImpl) KieServices(org.kie.api.KieServices) KieModule(org.kie.api.builder.KieModule) KieContainer(org.kie.api.runtime.KieContainer)

Example 12 with ProjectClassLoader

use of org.drools.wiring.api.classloader.ProjectClassLoader in project drools by kiegroup.

the class KieBuilderSetImpl method buildChanges.

private IncrementalResults buildChanges(Collection<String> filesToBuild) {
    Map<String, Collection<KnowledgeBuilderResult>> currentResults = new HashMap<>();
    InternalKieModule kieModule = (InternalKieModule) kieBuilder.getKieModuleIgnoringErrors();
    for (KieBaseModel kBaseModel : kieModule.getKieModuleModel().getKieBaseModels().values()) {
        InternalKnowledgeBuilder kBuilder = (InternalKnowledgeBuilder) kieModule.getKnowledgeBuilderForKieBase(kBaseModel.getName());
        if (kBuilder == null) {
            continue;
        }
        CompositeKnowledgeBuilder ckbuilder = kBuilder.batch();
        boolean useFolders = kBuilder.getBuilderConfiguration().isGroupDRLsInKieBasesByFolder();
        KnowledgeBuilderImpl.ResourceRemovalResult removalResult = new KnowledgeBuilderImpl.ResourceRemovalResult();
        Set<String> wrongResources = resourcesWithErrors.get(kBaseModel.getName());
        for (String resourceName : wrongResources) {
            removalResult.add(kBuilder.removeObjectsGeneratedFromResource(new DummyResource(resourceName)));
            removalResult.mergeModified(addResource(ckbuilder, kBaseModel, kieModule, resourceName, useFolders));
        }
        for (String file : filesToBuild) {
            if (wrongResources.contains(file)) {
                removalResult.mergeModified(true);
            } else {
                // remove the objects generated by the old Resource
                removalResult.add(kBuilder.removeObjectsGeneratedFromResource(new DummyResource(file)));
                // add the modified Resource
                removalResult.mergeModified(addResource(ckbuilder, kBaseModel, kieModule, file, useFolders));
            }
        }
        if (removalResult.isModified()) {
            boolean typeRefreshed = !removalResult.getRemovedTypes().isEmpty();
            if (typeRefreshed) {
                ProjectClassLoader projectClassLoader = (ProjectClassLoader) kBuilder.getRootClassLoader();
                projectClassLoader.reinitTypes();
                for (String removedType : removalResult.getRemovedTypes()) {
                    projectClassLoader.undefineClass(removedType);
                }
            }
            ckbuilder.build();
            if (typeRefreshed) {
                Collection<KiePackage> kiePackages = kBuilder.getKnowledgePackages();
                for (KiePackage kiePackage : kiePackages) {
                    ((InternalKnowledgePackage) kiePackage).wireStore();
                    ((InternalKnowledgePackage) kiePackage).wireTypeDeclarations();
                }
            }
            resourcesWithErrors.put(kBaseModel.getName(), findResourcesWithMessages(kBuilder));
            if (kBuilder.hasResults(getSeverities())) {
                currentResults.put(kBaseModel.getName(), kBuilder.getResults(getSeverities()));
            }
            if (kBuilder.hasErrors()) {
                kBuilder.undo();
            } else {
                KieServices.Factory.get().getRepository().addKieModule(kieModule);
                kieBuilder.updateKieModuleMetaInfo();
            }
        }
    }
    IncrementalResultsImpl results = getIncrementalResults(currentResults);
    previousErrors = currentResults;
    return results;
}
Also used : ProjectClassLoader(org.drools.wiring.api.classloader.ProjectClassLoader) CompositeKnowledgeBuilder(org.kie.internal.builder.CompositeKnowledgeBuilder) InternalKnowledgeBuilder(org.drools.compiler.builder.InternalKnowledgeBuilder) HashMap(java.util.HashMap) KieBaseModel(org.kie.api.builder.model.KieBaseModel) KiePackage(org.kie.api.definition.KiePackage) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) Collection(java.util.Collection) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 13 with ProjectClassLoader

use of org.drools.wiring.api.classloader.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 {
            Dialect dialect = 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.kie.memorycompiler.resources.MemoryResourceReader) Dialect(org.drools.compiler.compiler.Dialect) PackageDescr(org.drools.drl.ast.descr.PackageDescr) ProjectClassLoader(org.drools.wiring.api.classloader.ProjectClassLoader) BadCommandLineException(com.sun.tools.xjc.BadCommandLineException) ProjectJavaCompiler(org.drools.compiler.compiler.ProjectJavaCompiler) JCodeModel(com.sun.codemodel.JCodeModel) 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 14 with ProjectClassLoader

use of org.drools.wiring.api.classloader.ProjectClassLoader in project drools by kiegroup.

the class PersisterHelper method writeRuntimeDefinedClasses.

private static void writeRuntimeDefinedClasses(TraitFactory traitFactory, MarshallerWriteContext context, ProtobufMessages.Header.Builder _header) {
    if (context.getKnowledgeBase() == null) {
        return;
    }
    ProjectClassLoader pcl = (ProjectClassLoader) (context.getKnowledgeBase()).getRootClassLoader();
    if (pcl.getStore() == null || pcl.getStore().isEmpty()) {
        return;
    }
    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.wiring.api.classloader.ProjectClassLoader) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString)

Example 15 with ProjectClassLoader

use of org.drools.wiring.api.classloader.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);
        }
    }
    KnowledgePackageImpl clonedPkg = ClassUtils.deepClone(this, classLoader, cloningResources);
    clonedPkg.setClassLoader(classLoader);
    if (ruleUnitDescriptionLoader != null) {
        for (String ruleUnit : ruleUnitDescriptionLoader.getDescriptions().keySet()) {
            clonedPkg.getRuleUnitDescriptionLoader().getDescription(ruleUnit);
        }
    }
    return clonedPkg;
}
Also used : ProjectClassLoader(org.drools.wiring.api.classloader.ProjectClassLoader) ProjectClassLoader(org.drools.wiring.api.classloader.ProjectClassLoader) JavaDialectRuntimeData(org.drools.core.rule.JavaDialectRuntimeData)

Aggregations

ProjectClassLoader (org.drools.wiring.api.classloader.ProjectClassLoader)21 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 KiePMMLException (org.kie.pmml.api.exceptions.KiePMMLException)4 JavaDialectRuntimeData (org.drools.core.rule.JavaDialectRuntimeData)3 Dialect (org.drools.compiler.compiler.Dialect)2 KieContainerImpl (org.drools.compiler.kie.builder.impl.KieContainerImpl)2 KieProject (org.drools.compiler.kie.builder.impl.KieProject)2 KieServices (org.kie.api.KieServices)2 KieFileSystem (org.kie.api.builder.KieFileSystem)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 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 ExecutionException (java.util.concurrent.ExecutionException)1 ExecutorService (java.util.concurrent.ExecutorService)1