Search in sources :

Example 26 with PackageRegistry

use of org.drools.compiler.compiler.PackageRegistry in project drools by kiegroup.

the class PatternBuilder method getTypeDeclaration.

private TypeDeclaration getTypeDeclaration(RuleBuildContext context, Class<?> userProvidedClass) {
    String packageName = ClassUtils.getPackage(userProvidedClass);
    KnowledgeBuilderImpl kbuilder = context.getKnowledgeBuilder();
    PackageRegistry pkgr = kbuilder.getPackageRegistry(packageName);
    TypeDeclaration typeDeclaration = pkgr != null ? pkgr.getPackage().getTypeDeclaration(userProvidedClass) : null;
    if (typeDeclaration == null && kbuilder.getKnowledgeBase() != null) {
        // check if the type declaration is contained only in the already existing kbase (possible during incremental compilation)
        InternalKnowledgePackage pkg = kbuilder.getKnowledgeBase().getPackage(packageName);
        typeDeclaration = pkg != null ? pkg.getTypeDeclaration(userProvidedClass) : null;
    }
    if (typeDeclaration == null) {
        typeDeclaration = context.getPkg().getTypeDeclaration(userProvidedClass);
    }
    return typeDeclaration;
}
Also used : PackageRegistry(org.drools.compiler.compiler.PackageRegistry) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) TypeDeclaration(org.drools.core.rule.TypeDeclaration) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 27 with PackageRegistry

use of org.drools.compiler.compiler.PackageRegistry in project drools by kiegroup.

the class PatternBuilder method buildQuery.

private RuleConditionElement buildQuery(RuleBuildContext context, PatternDescr descr, PatternDescr patternDescr) {
    RuleConditionElement rce = null;
    // it might be a recursive query, so check for same names
    if (context.getRule().getName().equals(patternDescr.getObjectType())) {
        // it's a query so delegate to the QueryElementBuilder
        rce = buildQueryElement(context, descr, (QueryImpl) context.getRule());
    }
    if (rce == null) {
        // look up the query in the current package
        RuleImpl rule = context.getPkg().getRule(patternDescr.getObjectType());
        if (rule instanceof QueryImpl) {
            // it's a query so delegate to the QueryElementBuilder
            rce = buildQueryElement(context, descr, (QueryImpl) rule);
        }
    }
    if (rce == null) {
        // the query may have been imported, so try package imports
        for (String importName : context.getDialect().getTypeResolver().getImports()) {
            importName = importName.trim();
            int pos = importName.indexOf('*');
            if (pos >= 0) {
                String pkgName = importName.substring(0, pos - 1);
                PackageRegistry pkgReg = context.getKnowledgeBuilder().getPackageRegistry(pkgName);
                if (pkgReg != null) {
                    RuleImpl rule = pkgReg.getPackage().getRule(patternDescr.getObjectType());
                    if (rule instanceof QueryImpl) {
                        // it's a query so delegate to the QueryElementBuilder
                        rce = buildQueryElement(context, descr, (QueryImpl) rule);
                        break;
                    }
                }
            }
        }
    }
    if (rce == null) {
        // this isn't a query either, so log an error
        registerDescrBuildError(context, patternDescr, "Unable to resolve ObjectType '" + patternDescr.getObjectType() + "'");
    }
    return rce;
}
Also used : QueryImpl(org.drools.core.rule.QueryImpl) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) RuleConditionElement(org.drools.core.rule.RuleConditionElement) XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) NegConstraint(org.drools.core.rule.constraint.NegConstraint) Constraint(org.drools.core.spi.Constraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) EvaluatorConstraint(org.drools.core.rule.constraint.EvaluatorConstraint) PredicateConstraint(org.drools.core.rule.PredicateConstraint)

Example 28 with PackageRegistry

use of org.drools.compiler.compiler.PackageRegistry in project drools by kiegroup.

the class ModelBuilderImpl method buildRules.

protected void buildRules(Collection<CompositePackageDescr> packages) {
    for (CompositePackageDescr packageDescr : packages) {
        PackageRegistry pkgRegistry = getPackageRegistry(packageDescr.getNamespace());
        generatePOJOs(packageDescr, pkgRegistry);
    }
    List<GeneratedClassWithPackage> allGeneratedPojos = packageModels.values().stream().flatMap(p -> p.getGeneratedPOJOsSource().stream().map(c -> new GeneratedClassWithPackage(c, p.getName(), p.getImports()))).collect(Collectors.toList());
    // Every class gets compiled in each classloader, maybe they can be compiled only one time?
    final Map<String, Class<?>> allCompiledClasses = new HashMap<>();
    for (CompositePackageDescr packageDescr : packages) {
        InternalKnowledgePackage pkg = getPackageRegistry(packageDescr.getNamespace()).getPackage();
        allCompiledClasses.putAll(compileType(this, pkg.getPackageClassLoader(), allGeneratedPojos));
    }
    for (CompositePackageDescr packageDescr : packages) {
        InternalKnowledgePackage pkg = getPackageRegistry(packageDescr.getNamespace()).getPackage();
        allGeneratedPojos.forEach(c -> registerType(pkg.getTypeResolver(), allCompiledClasses));
    }
    if (hasErrors()) {
        // if Error while generating pojo do not try compile rule as they very likely depends hence fail too.
        return;
    }
    for (CompositePackageDescr packageDescr : packages) {
        setAssetFilter(packageDescr.getFilter());
        PackageRegistry pkgRegistry = getPackageRegistry(packageDescr.getNamespace());
        compileKnowledgePackages(packageDescr, pkgRegistry);
        setAssetFilter(null);
    }
}
Also used : PackageRegistry(org.drools.compiler.compiler.PackageRegistry) POJOGenerator.registerType(org.drools.modelcompiler.builder.generator.POJOGenerator.registerType) TypeDeclaration(org.drools.core.rule.TypeDeclaration) Collection(java.util.Collection) ModelGenerator.generateModel(org.drools.modelcompiler.builder.generator.ModelGenerator.generateModel) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) TypeDeclarationDescr(org.drools.compiler.lang.descr.TypeDeclarationDescr) HashMap(java.util.HashMap) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) TypeDeclarationFactory(org.drools.compiler.builder.impl.TypeDeclarationFactory) POJOGenerator.generatePOJO(org.drools.modelcompiler.builder.generator.POJOGenerator.generatePOJO) Collectors(java.util.stream.Collectors) POJOGenerator.compileType(org.drools.modelcompiler.builder.generator.POJOGenerator.compileType) ArrayList(java.util.ArrayList) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) List(java.util.List) Map(java.util.Map) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) CompositePackageDescr(org.drools.compiler.lang.descr.CompositePackageDescr) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) CompositePackageDescr(org.drools.compiler.lang.descr.CompositePackageDescr) HashMap(java.util.HashMap) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 29 with PackageRegistry

use of org.drools.compiler.compiler.PackageRegistry 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 30 with PackageRegistry

use of org.drools.compiler.compiler.PackageRegistry in project drools by kiegroup.

the class BayesAssemblerService method addResource.

@Override
public void addResource(Object kbuilder, Resource resource, ResourceType type, ResourceConfiguration configuration) throws Exception {
    BayesNetwork network;
    JunctionTreeBuilder builder;
    KnowledgeBuilder kb = (KnowledgeBuilder) kbuilder;
    Bif bif = XmlBifParser.loadBif(resource, kb.getErrors());
    if (bif == null) {
        return;
    }
    try {
        network = XmlBifParser.buildBayesNetwork(bif);
    } catch (Exception e) {
        kb.getErrors().add(new BayesNetworkAssemblerError(resource, "Unable to parse opening Stream:\n" + e.toString()));
        return;
    }
    try {
        builder = new JunctionTreeBuilder(network);
    } catch (Exception e) {
        kb.getErrors().add(new BayesNetworkAssemblerError(resource, "Unable to build Junction Tree:\n" + e.toString()));
        return;
    }
    KnowledgeBuilderImpl kbuilderImpl = (KnowledgeBuilderImpl) kbuilder;
    PackageRegistry pkgReg = kbuilderImpl.getOrCreatePackageRegistry(new PackageDescr(network.getPackageName()));
    InternalKnowledgePackage kpkgs = pkgReg.getPackage();
    Map<ResourceType, ResourceTypePackage> rpkg = kpkgs.getResourceTypePackages();
    BayesPackage bpkg = (BayesPackage) rpkg.get(ResourceType.BAYES);
    if (bpkg == null) {
        bpkg = new BayesPackage();
        rpkg.put(ResourceType.BAYES, bpkg);
    }
    bpkg.addJunctionTree(network.getName(), builder.build());
}
Also used : JunctionTreeBuilder(org.drools.beliefs.bayes.JunctionTreeBuilder) ResourceType(org.kie.api.io.ResourceType) BayesNetwork(org.drools.beliefs.bayes.BayesNetwork) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) ResourceTypePackage(org.kie.api.internal.io.ResourceTypePackage) Bif(org.drools.beliefs.bayes.model.Bif) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Aggregations

PackageRegistry (org.drools.compiler.compiler.PackageRegistry)33 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)17 TypeDeclaration (org.drools.core.rule.TypeDeclaration)12 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)11 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)10 DialectCompiletimeRegistry (org.drools.compiler.compiler.DialectCompiletimeRegistry)7 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)7 ArrayList (java.util.ArrayList)6 KnowledgeBuilderConfigurationImpl (org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl)6 CompositePackageDescr (org.drools.compiler.lang.descr.CompositePackageDescr)6 RuleBuildContext (org.drools.compiler.rule.builder.RuleBuildContext)6 KnowledgePackageImpl (org.drools.core.definitions.impl.KnowledgePackageImpl)6 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)6 HashMap (java.util.HashMap)5 HashSet (java.util.HashSet)3 LinkedHashMap (java.util.LinkedHashMap)3 Map (java.util.Map)3 TypeDeclarationError (org.drools.compiler.compiler.TypeDeclarationError)3 TypeDeclarationDescr (org.drools.compiler.lang.descr.TypeDeclarationDescr)3 ClassObjectType (org.drools.core.base.ClassObjectType)3