Search in sources :

Example 1 with DroolsError

use of org.drools.drl.parser.DroolsError in project drools by kiegroup.

the class DroolsModelProvider method generateRulesFiles.

/**
 * This method depends on exec-model. Be aware in case of refactoring
 * @param packageDescr
 * @return
 */
protected List<GeneratedFile> generateRulesFiles(PackageDescr packageDescr) {
    ModelBuilderImpl<PackageSources> modelBuilder = new ModelBuilderImpl<>(PackageSources::dumpSources, new KnowledgeBuilderConfigurationImpl(getClass().getClassLoader()), new ReleaseIdImpl("dummy:dummy:0.0.0"), false);
    CompositeKnowledgeBuilder batch = modelBuilder.batch();
    batch.add(new DescrResource(packageDescr), ResourceType.DESCR);
    try {
        batch.build();
        if (modelBuilder.hasErrors()) {
            StringBuilder builder = new StringBuilder();
            for (DroolsError error : modelBuilder.getErrors().getErrors()) {
                logger.error(error.toString());
                builder.append(error.toString()).append(" ");
            }
            throw new KiePMMLException(builder.toString());
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
        StringBuilder builder = new StringBuilder(e.getMessage()).append(" ");
        for (DroolsError error : modelBuilder.getErrors().getErrors()) {
            logger.error(error.toString());
            builder.append(error.toString()).append(" ");
        }
        throw new RuntimeException(builder.toString(), e);
    }
    return generateModels(modelBuilder).stream().map(f -> new GeneratedFile(GeneratedFile.Type.RULE, f.getPath(), new String(f.getData()))).collect(toList());
}
Also used : ModelBuilderImpl(org.drools.modelcompiler.builder.ModelBuilderImpl) KiePMMLDroolsModel(org.kie.pmml.models.drools.commons.model.KiePMMLDroolsModel) DescrResource(org.drools.core.io.impl.DescrResource) EXPECTING_HAS_KNOWLEDGEBUILDER_TEMPLATE(org.kie.pmml.commons.Constants.EXPECTING_HAS_KNOWLEDGEBUILDER_TEMPLATE) KiePMMLOriginalTypeGeneratedType(org.kie.pmml.models.drools.tuples.KiePMMLOriginalTypeGeneratedType) Model(org.dmg.pmml.Model) CompositeKnowledgeBuilder(org.kie.internal.builder.CompositeKnowledgeBuilder) DroolsCompilationDTO(org.kie.pmml.models.drools.dto.DroolsCompilationDTO) KiePMMLDescrFactory.getBaseDescr(org.kie.pmml.models.drools.commons.factories.KiePMMLDescrFactory.getBaseDescr) KiePMMLDroolsType(org.kie.pmml.models.drools.ast.KiePMMLDroolsType) LoggerFactory(org.slf4j.LoggerFactory) StringUtils.getPkgUUID(org.drools.core.util.StringUtils.getPkgUUID) HashMap(java.util.HashMap) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) ModelImplementationProvider(org.kie.pmml.compiler.api.provider.ModelImplementationProvider) ResourceType(org.kie.api.io.ResourceType) ArrayList(java.util.ArrayList) Field(org.dmg.pmml.Field) Map(java.util.Map) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) KiePMMLModelWithSources(org.kie.pmml.commons.model.KiePMMLModelWithSources) ModelBuilderImpl(org.drools.modelcompiler.builder.ModelBuilderImpl) CompilationDTO(org.kie.pmml.compiler.api.dto.CompilationDTO) PackageSources(org.drools.modelcompiler.builder.PackageSources) Logger(org.slf4j.Logger) PackageDescr(org.drools.drl.ast.descr.PackageDescr) IOException(java.io.IOException) HasKnowledgeBuilder(org.kie.pmml.kie.dependencies.HasKnowledgeBuilder) Collectors(java.util.stream.Collectors) DATA_TYPE(org.kie.pmml.api.enums.DATA_TYPE) GeneratedFile(org.drools.modelcompiler.builder.GeneratedFile) KiePMMLDataDictionaryASTFactory(org.kie.pmml.models.drools.ast.factories.KiePMMLDataDictionaryASTFactory) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ReleaseIdImpl(org.kie.util.maven.support.ReleaseIdImpl) DroolsError(org.drools.drl.parser.DroolsError) KiePMMLDroolsAST(org.kie.pmml.models.drools.ast.KiePMMLDroolsAST) KiePMMLDroolsModelWithSources(org.kie.pmml.models.drools.commons.model.KiePMMLDroolsModelWithSources) CompositePackageDescr(org.drools.compiler.lang.descr.CompositePackageDescr) Collections(java.util.Collections) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) ReleaseIdImpl(org.kie.util.maven.support.ReleaseIdImpl) CompositeKnowledgeBuilder(org.kie.internal.builder.CompositeKnowledgeBuilder) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) DescrResource(org.drools.core.io.impl.DescrResource) IOException(java.io.IOException) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) GeneratedFile(org.drools.modelcompiler.builder.GeneratedFile) DroolsError(org.drools.drl.parser.DroolsError) PackageSources(org.drools.modelcompiler.builder.PackageSources) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException)

Example 2 with DroolsError

use of org.drools.drl.parser.DroolsError in project drools by kiegroup.

the class ConditionalBranchBuilder method build.

public ConditionalBranch build(RuleBuildContext context, BaseDescr descr, Pattern prefixPattern) {
    ConditionalBranchDescr conditionalBranch = (ConditionalBranchDescr) descr;
    String consequenceName = conditionalBranch.getConsequence().getName();
    if (!context.getRuleDescr().getNamedConsequences().containsKey(consequenceName)) {
        DroolsError err = new RuleBuildError(context.getRule(), context.getParentDescr(), null, "Unknown consequence name: " + consequenceName);
        context.addError(err);
        return null;
    }
    RuleConditionBuilder evalBuilder = (RuleConditionBuilder) context.getDialect().getBuilder(EvalDescr.class);
    EvalCondition condition = (EvalCondition) evalBuilder.build(context, conditionalBranch.getCondition(), getLastPattern(context));
    NamedConsequenceBuilder namedConsequenceBuilder = (NamedConsequenceBuilder) context.getDialect().getBuilder(NamedConsequenceDescr.class);
    NamedConsequence consequence = namedConsequenceBuilder.build(context, conditionalBranch.getConsequence());
    ConditionalBranchDescr elseBranchDescr = conditionalBranch.getElseBranch();
    return new ConditionalBranch(condition, consequence, elseBranchDescr != null ? build(context, elseBranchDescr, prefixPattern) : null);
}
Also used : DroolsError(org.drools.drl.parser.DroolsError) NamedConsequenceDescr(org.drools.drl.ast.descr.NamedConsequenceDescr) ConditionalBranchDescr(org.drools.drl.ast.descr.ConditionalBranchDescr) RuleBuildError(org.drools.compiler.compiler.RuleBuildError) EvalDescr(org.drools.drl.ast.descr.EvalDescr) ConditionalBranch(org.drools.core.rule.ConditionalBranch) EvalCondition(org.drools.core.rule.EvalCondition) NamedConsequence(org.drools.core.rule.NamedConsequence)

Example 3 with DroolsError

use of org.drools.drl.parser.DroolsError in project drools by kiegroup.

the class RuleBuilder method buildAttributes.

public static void buildAttributes(final RuleBuildContext context) {
    final RuleImpl rule = context.getRule();
    final RuleDescr ruleDescr = context.getRuleDescr();
    boolean enforceEager = false;
    for (final AttributeDescr attributeDescr : ruleDescr.getAttributes().values()) {
        final String name = attributeDescr.getName();
        switch(name) {
            case "no-loop":
                rule.setNoLoop(getBooleanValue(attributeDescr, true));
                enforceEager = true;
                break;
            case "auto-focus":
                rule.setAutoFocus(getBooleanValue(attributeDescr, true));
                break;
            case "agenda-group":
                if (StringUtils.isEmpty(rule.getRuleFlowGroup())) {
                    // don't override if RFG has already set this
                    rule.setAgendaGroup(attributeDescr.getValue());
                } else {
                    if (rule.getRuleFlowGroup().equals(attributeDescr.getValue())) {
                        DroolsWarning warn = new RuleBuildWarning(rule, context.getParentDescr(), null, "Both an agenda-group ( " + attributeDescr.getValue() + " ) and a ruleflow-group ( " + rule.getRuleFlowGroup() + " ) are defined for rule " + rule.getName() + ". Since version 6.x the " + "two concepts have been unified, the ruleflow-group name will override the agenda-group. ");
                        context.addWarning(warn);
                    }
                }
                break;
            case "activation-group":
                rule.setActivationGroup(attributeDescr.getValue());
                break;
            case "ruleflow-group":
                rule.setRuleFlowGroup(attributeDescr.getValue());
                if (!rule.getAgendaGroup().equals(AgendaGroup.MAIN) && !rule.getAgendaGroup().equals(attributeDescr.getValue())) {
                    DroolsWarning warn = new RuleBuildWarning(rule, context.getParentDescr(), null, "Both an agenda-group ( " + attributeDescr.getValue() + " ) and a ruleflow-group ( " + rule.getRuleFlowGroup() + " ) are defined for rule " + rule.getName() + ". Since version 6.x the " + "two concepts have been unified, the ruleflow-group name will override the agenda-group. ");
                    context.addWarning(warn);
                }
                // assign AG to the same name as RFG, as they are aliased to AGs anyway
                rule.setAgendaGroup(attributeDescr.getValue());
                break;
            case "lock-on-active":
                boolean lockOnActive = getBooleanValue(attributeDescr, true);
                rule.setLockOnActive(lockOnActive);
                enforceEager |= lockOnActive;
                break;
            case DroolsSoftKeywords.DURATION:
            case DroolsSoftKeywords.TIMER:
                String duration = attributeDescr.getValue();
                rule.setTimer(buildTimer(rule, duration, context));
                break;
            case "calendars":
                buildCalendars(rule, attributeDescr.getValue(), context);
                break;
            case "date-effective":
                try {
                    Date date = DateUtils.parseDate(attributeDescr.getValue());
                    final Calendar cal = Calendar.getInstance();
                    cal.setTime(date);
                    rule.setDateEffective(cal);
                } catch (Exception e) {
                    DroolsError err = new RuleBuildError(rule, context.getParentDescr(), null, "Wrong date-effective value: " + e.getMessage());
                    context.addError(err);
                }
                break;
            case "date-expires":
                try {
                    Date date = DateUtils.parseDate(attributeDescr.getValue());
                    final Calendar cal = Calendar.getInstance();
                    cal.setTime(date);
                    rule.setDateExpires(cal);
                } catch (Exception e) {
                    DroolsError err = new RuleBuildError(rule, context.getParentDescr(), null, "Wrong date-expires value: " + e.getMessage());
                    context.addError(err);
                }
                break;
        }
    }
    buildSalience(context);
    buildEnabled(context);
    parseAnnotation(context, rule, ruleDescr, enforceEager);
}
Also used : DroolsError(org.drools.drl.parser.DroolsError) Calendar(java.util.Calendar) RuleBuildError(org.drools.compiler.compiler.RuleBuildError) RuleDescr(org.drools.drl.ast.descr.RuleDescr) DroolsWarning(org.drools.compiler.compiler.DroolsWarning) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) RuleBuildWarning(org.drools.compiler.compiler.RuleBuildWarning) AttributeDescr(org.drools.drl.ast.descr.AttributeDescr) Date(java.util.Date) ParseException(java.text.ParseException)

Example 4 with DroolsError

use of org.drools.drl.parser.DroolsError in project drools by kiegroup.

the class RuleBuilder method parseAnnotation.

private static void parseAnnotation(RuleBuildContext context, RuleImpl rule, RuleDescr ruleDescr, boolean enforceEager) {
    try {
        ActivationListener activationListener = getTypedAnnotation(ruleDescr, ActivationListener.class);
        if (activationListener != null) {
            rule.setActivationListener(CoreComponentsBuilder.get().getMVELExecutor().evalToString(activationListener.value()));
        }
        if (enforceEager) {
            rule.setEager(true);
        } else {
            Propagation propagation = getTypedAnnotation(ruleDescr, Propagation.class);
            if (propagation != null) {
                if (propagation.value() == Propagation.Type.IMMEDIATE) {
                    rule.setDataDriven(true);
                } else if (propagation.value() == Propagation.Type.EAGER) {
                    rule.setEager(true);
                }
            }
        }
        Direct direct = getTypedAnnotation(ruleDescr, Direct.class);
        if (direct != null && direct.value()) {
            rule.setActivationListener("direct");
        }
        rule.setAllMatches(ruleDescr.hasAnnotation(All.class));
    } catch (Exception e) {
        DroolsError err = new RuleBuildError(rule, context.getParentDescr(), null, e.getMessage());
        context.addError(err);
    }
}
Also used : All(org.kie.api.definition.rule.All) DroolsError(org.drools.drl.parser.DroolsError) Propagation(org.kie.api.definition.rule.Propagation) RuleBuildError(org.drools.compiler.compiler.RuleBuildError) ParseException(java.text.ParseException) ActivationListener(org.kie.api.definition.rule.ActivationListener) Direct(org.kie.api.definition.rule.Direct)

Example 5 with DroolsError

use of org.drools.drl.parser.DroolsError in project drools by kiegroup.

the class RuleBuilder method buildCalendars.

private static void buildCalendars(RuleImpl rule, String calendarsString, RuleBuildContext context) {
    Object val = null;
    try {
        val = CoreComponentsBuilder.get().getMVELExecutor().eval(calendarsString);
        String[] calNames = null;
        if (val instanceof List) {
            calNames = (String[]) ((List) val).toArray(new String[((List) val).size()]);
        } else if (val instanceof String) {
            calNames = new String[] { (String) val };
        } else {
            DroolsError err = new RuleBuildError(rule, context.getParentDescr(), null, "Calendars attribute did not return a String or String[] '" + val + "'");
            context.addError(err);
        }
        if (calNames != null) {
            rule.setCalendars(calNames);
        }
    } catch (Exception e) {
        DroolsError err = new RuleBuildError(rule, context.getParentDescr(), null, "Unable to build Calendars attribute '" + val + "'" + e.getMessage());
        context.addError(err);
    }
}
Also used : DroolsError(org.drools.drl.parser.DroolsError) RuleBuildError(org.drools.compiler.compiler.RuleBuildError) List(java.util.List) ParseException(java.text.ParseException)

Aggregations

DroolsError (org.drools.drl.parser.DroolsError)13 RuleBuildError (org.drools.compiler.compiler.RuleBuildError)5 ParseException (java.text.ParseException)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IOException (java.io.IOException)2 DescrResource (org.drools.core.io.impl.DescrResource)2 AttributeDescr (org.drools.drl.ast.descr.AttributeDescr)2 PackageDescr (org.drools.drl.ast.descr.PackageDescr)2 RuleDescr (org.drools.drl.ast.descr.RuleDescr)2 Resource (org.kie.api.io.Resource)2 InputStream (java.io.InputStream)1 UncheckedIOException (java.io.UncheckedIOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Calendar (java.util.Calendar)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1