Search in sources :

Example 6 with FromDescr

use of org.drools.compiler.lang.descr.FromDescr in project drools by kiegroup.

the class RuleModelDRLPersistenceImpl method parsePatternSource.

private IFactPattern parsePatternSource(final RuleModel m, final PatternDescr pattern, final PatternSourceDescr patternSource, final boolean isJavaDialect, final Map<String, String> boundParams, final PackageDataModelOracle dmo) {
    if (pattern.getIdentifier() != null) {
        boundParams.put(pattern.getIdentifier(), pattern.getObjectType());
    }
    if (patternSource instanceof AccumulateDescr) {
        AccumulateDescr accumulate = (AccumulateDescr) patternSource;
        FromAccumulateCompositeFactPattern fac = new FromAccumulateCompositeFactPattern();
        fac.setSourcePattern(parseBaseDescr(m, accumulate.getInput(), isJavaDialect, boundParams, dmo));
        fac.setInitCode(accumulate.getInitCode());
        fac.setActionCode(accumulate.getActionCode());
        fac.setReverseCode(accumulate.getReverseCode());
        fac.setResultCode(accumulate.getResultCode());
        FactPattern factPattern = new FactPattern(pattern.getObjectType());
        factPattern.setBoundName(pattern.getIdentifier());
        parseConstraint(m, factPattern, pattern.getConstraint(), isJavaDialect, boundParams, dmo);
        fac.setFactPattern(factPattern);
        for (AccumulateDescr.AccumulateFunctionCallDescr func : accumulate.getFunctions()) {
            String funcName = func.getFunction();
            boolean first = true;
            StringBuilder sb = new StringBuilder();
            for (String param : func.getParams()) {
                if (first) {
                    first = false;
                } else {
                    sb.append(", ");
                }
                sb.append(param);
            }
            fac.setFunction(funcName + "(" + sb + ")");
            break;
        }
        return fac;
    } else if (patternSource instanceof CollectDescr) {
        CollectDescr collect = (CollectDescr) patternSource;
        FromCollectCompositeFactPattern fac = new FromCollectCompositeFactPattern();
        fac.setRightPattern(parseBaseDescr(m, collect.getInputPattern(), isJavaDialect, boundParams, dmo));
        fac.setFactPattern(getFactPattern(m, pattern, isJavaDialect, boundParams, dmo));
        return fac;
    } else if (patternSource instanceof EntryPointDescr) {
        EntryPointDescr entryPoint = (EntryPointDescr) patternSource;
        FromEntryPointFactPattern fep = new FromEntryPointFactPattern();
        fep.setEntryPointName(entryPoint.getText());
        fep.setFactPattern(getFactPattern(m, pattern, isJavaDialect, boundParams, dmo));
        return fep;
    } else if (patternSource instanceof FromDescr) {
        FromDescr from = (FromDescr) patternSource;
        FromCompositeFactPattern fcfp = new FromCompositeFactPattern();
        FactPattern factPattern = new FactPattern(pattern.getObjectType());
        factPattern.setBoundName(pattern.getIdentifier());
        parseConstraint(m, factPattern, pattern.getConstraint(), isJavaDialect, boundParams, dmo);
        fcfp.setFactPattern(factPattern);
        ExpressionFormLine expression = new ExpressionFormLine();
        fcfp.setExpression(expression);
        String dataSource = from.getDataSource().toString();
        String[] splitSource = dataSource.split("\\.");
        ModelField[] fields = null;
        for (int i = 0; i < splitSource.length; i++) {
            String sourcePart = splitSource[i];
            if (i == 0) {
                String type = boundParams.get(sourcePart);
                expression.appendPart(new ExpressionVariable(sourcePart, type, DataType.TYPE_NUMERIC));
                fields = findFields(m, dmo, type);
            } else {
                ModelField modelField = null;
                if (fields != null) {
                    for (ModelField field : fields) {
                        if (field.getName().equals(sourcePart)) {
                            modelField = field;
                            break;
                        }
                    }
                }
                if (modelField == null) {
                    final String previousClassName = expression.getClassType();
                    final List<MethodInfo> mis = dmo.getModuleMethodInformation().get(previousClassName);
                    boolean isMethod = false;
                    if (mis != null) {
                        for (MethodInfo mi : mis) {
                            if (mi.getName().equals(sourcePart)) {
                                expression.appendPart(new ExpressionMethod(mi.getName(), mi.getReturnClassType(), mi.getGenericType(), mi.getParametricReturnType()));
                                isMethod = true;
                                break;
                            }
                        }
                    }
                    if (isMethod == false) {
                        expression.appendPart(new ExpressionText(sourcePart));
                    }
                } else {
                    expression.appendPart(new ExpressionField(sourcePart, modelField.getClassName(), modelField.getType()));
                    fields = findFields(m, dmo, modelField.getClassName());
                }
            }
        }
        return fcfp;
    }
    throw new RuntimeException("Unknown pattern source " + patternSource);
}
Also used : FromEntryPointFactPattern(org.drools.workbench.models.datamodel.rule.FromEntryPointFactPattern) EntryPointDescr(org.drools.compiler.lang.descr.EntryPointDescr) FromEntryPointFactPattern(org.drools.workbench.models.datamodel.rule.FromEntryPointFactPattern) CompositeFactPattern(org.drools.workbench.models.datamodel.rule.CompositeFactPattern) FromCollectCompositeFactPattern(org.drools.workbench.models.datamodel.rule.FromCollectCompositeFactPattern) FromAccumulateCompositeFactPattern(org.drools.workbench.models.datamodel.rule.FromAccumulateCompositeFactPattern) FromCompositeFactPattern(org.drools.workbench.models.datamodel.rule.FromCompositeFactPattern) IFactPattern(org.drools.workbench.models.datamodel.rule.IFactPattern) FactPattern(org.drools.workbench.models.datamodel.rule.FactPattern) FromDescr(org.drools.compiler.lang.descr.FromDescr) ExpressionText(org.drools.workbench.models.datamodel.rule.ExpressionText) FromCollectCompositeFactPattern(org.drools.workbench.models.datamodel.rule.FromCollectCompositeFactPattern) ExpressionField(org.drools.workbench.models.datamodel.rule.ExpressionField) AccumulateDescr(org.drools.compiler.lang.descr.AccumulateDescr) ExpressionFormLine(org.drools.workbench.models.datamodel.rule.ExpressionFormLine) ExpressionMethod(org.drools.workbench.models.datamodel.rule.ExpressionMethod) FromCompositeFactPattern(org.drools.workbench.models.datamodel.rule.FromCompositeFactPattern) ModelField(org.kie.soup.project.datamodel.oracle.ModelField) CollectDescr(org.drools.compiler.lang.descr.CollectDescr) FromAccumulateCompositeFactPattern(org.drools.workbench.models.datamodel.rule.FromAccumulateCompositeFactPattern) ExpressionVariable(org.drools.workbench.models.datamodel.rule.ExpressionVariable) ArrayList(java.util.ArrayList) StringUtils.splitArgumentsList(org.drools.core.util.StringUtils.splitArgumentsList) List(java.util.List) ActionFieldList(org.drools.workbench.models.datamodel.rule.ActionFieldList) MethodInfo(org.kie.soup.project.datamodel.oracle.MethodInfo) RuleModelPersistenceHelper.findMethodInfo(org.drools.workbench.models.commons.backend.rule.RuleModelPersistenceHelper.findMethodInfo)

Example 7 with FromDescr

use of org.drools.compiler.lang.descr.FromDescr in project drools by kiegroup.

the class MVELFromBuilder method build.

public RuleConditionElement build(final RuleBuildContext context, final BaseDescr descr, final Pattern prefixPattern) {
    String text = ((FromDescr) descr).getExpression();
    Optional<EntryPointId> entryPointId = context.getEntryPointId(text);
    if (entryPointId.isPresent()) {
        return entryPointId.get();
    }
    // This builder is re-usable in other dialects, so specify by name
    MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
    boolean typeSafe = context.isTypesafe();
    if (!dialect.isStrictMode()) {
        context.setTypesafe(false);
    }
    try {
        Map<String, Declaration> decls = context.getDeclarationResolver().getDeclarations(context.getRule());
        AnalysisResult analysis = dialect.analyzeExpression(context, descr, text, new BoundIdentifiers(DeclarationScopeResolver.getDeclarationClasses(decls), context));
        if (analysis == null) {
            // something bad happened
            return null;
        }
        Class<?> returnType = ((MVELAnalysisResult) analysis).getReturnType();
        if (prefixPattern != null && !prefixPattern.isCompatibleWithFromReturnType(returnType)) {
            context.addError(new DescrBuildError(descr, context.getRuleDescr(), null, "Pattern of type: '" + prefixPattern.getObjectType() + "' on rule '" + context.getRuleDescr().getName() + "' is not compatible with type " + returnType.getCanonicalName() + " returned by source"));
            return null;
        }
        final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
        final Declaration[] declarations = new Declaration[usedIdentifiers.getDeclrClasses().size()];
        int j = 0;
        for (String str : usedIdentifiers.getDeclrClasses().keySet()) {
            declarations[j++] = decls.get(str);
        }
        Arrays.sort(declarations, SortDeclarations.instance);
        MVELCompilationUnit unit = dialect.getMVELCompilationUnit(text, analysis, declarations, null, null, context, "drools", KnowledgeHelper.class, false, MVELCompilationUnit.Scope.CONSEQUENCE);
        MVELDataProvider dataProvider = new MVELDataProvider(unit, context.getDialect().getId());
        From from = new From(dataProvider);
        from.setResultPattern(prefixPattern);
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        data.addCompileable(from, dataProvider);
        dataProvider.compile(data, context.getRule());
        return from;
    } catch (final Exception e) {
        DialectUtil.copyErrorLocation(e, descr);
        context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Unable to build expression for 'from' : " + e.getMessage() + " '" + text + "'"));
        return null;
    } finally {
        context.setTypesafe(typeSafe);
    }
}
Also used : MVELDataProvider(org.drools.core.base.dataproviders.MVELDataProvider) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) FromDescr(org.drools.compiler.lang.descr.FromDescr) From(org.drools.core.rule.From) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) EntryPointId(org.drools.core.rule.EntryPointId) Declaration(org.drools.core.rule.Declaration)

Example 8 with FromDescr

use of org.drools.compiler.lang.descr.FromDescr in project drools by kiegroup.

the class FromVisitor method visit.

public Optional<Expression> visit(PatternSourceDescr sourceDescr) {
    if (sourceDescr instanceof FromDescr) {
        final String expression = ((FromDescr) sourceDescr).getDataSource().toString();
        Optional<String> optContainsBinding = DrlxParseUtil.findBindingIdFromDotExpression(expression);
        final String bindingId = optContainsBinding.orElse(expression);
        Expression fromCall = ruleContext.hasDeclaration(bindingId) || packageModel.hasDeclaration(bindingId) ? createFromCall(expression, optContainsBinding, bindingId) : createUnitDataCall(optContainsBinding, bindingId);
        return Optional.of(fromCall);
    } else {
        return Optional.empty();
    }
}
Also used : Expression(org.drools.javaparser.ast.expr.Expression) FromDescr(org.drools.compiler.lang.descr.FromDescr)

Example 9 with FromDescr

use of org.drools.compiler.lang.descr.FromDescr in project drools by kiegroup.

the class SourceDescrBuilderImpl method expression.

public P expression(String expression) {
    FromDescr from = new FromDescr();
    from.setDataSource(new MVELExprDescr(expression));
    from.setResource(descr.getResource());
    descr.setSource(from);
    return parent;
}
Also used : FromDescr(org.drools.compiler.lang.descr.FromDescr) MVELExprDescr(org.drools.compiler.lang.descr.MVELExprDescr)

Example 10 with FromDescr

use of org.drools.compiler.lang.descr.FromDescr in project drools by kiegroup.

the class RuleParserTest method testFromComplexAcessor.

@Test
public void testFromComplexAcessor() throws Exception {
    String source = "rule \"Invalid customer id\" ruleflow-group \"validate\" lock-on-active true \n" + " when \n" + "     o: Order( ) \n" + "     not( Customer( ) from customerService.getCustomer(o.getCustomerId()) ) \n" + " then \n" + "     System.err.println(\"Invalid customer id found!\"); \n" + "     o.addError(\"Invalid customer id\"); \n" + "end \n";
    PackageDescr pkg = (PackageDescr) parse("compilationUnit", source);
    assertFalse(parser.getErrorMessages().toString(), parser.hasErrors());
    RuleDescr rule = (RuleDescr) pkg.getRules().get(0);
    assertEquals("Invalid customer id", rule.getName());
    assertEquals(2, rule.getLhs().getDescrs().size());
    NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1);
    PatternDescr customer = (PatternDescr) not.getDescrs().get(0);
    assertEquals("Customer", customer.getObjectType());
    assertEquals("customerService.getCustomer(o.getCustomerId())", ((FromDescr) customer.getSource()).getDataSource().getText());
}
Also used : NotDescr(org.drools.compiler.lang.descr.NotDescr) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) FromDescr(org.drools.compiler.lang.descr.FromDescr) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) Test(org.junit.Test)

Aggregations

FromDescr (org.drools.compiler.lang.descr.FromDescr)15 PatternDescr (org.drools.compiler.lang.descr.PatternDescr)11 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)11 Test (org.junit.Test)11 MVELExprDescr (org.drools.compiler.lang.descr.MVELExprDescr)7 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)6 NotDescr (org.drools.compiler.lang.descr.NotDescr)2 InputStreamReader (java.io.InputStreamReader)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 AnalysisResult (org.drools.compiler.compiler.AnalysisResult)1 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)1 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)1 XmlPackageReader (org.drools.compiler.compiler.xml.XmlPackageReader)1 AccumulateDescr (org.drools.compiler.lang.descr.AccumulateDescr)1 BaseDescr (org.drools.compiler.lang.descr.BaseDescr)1 CollectDescr (org.drools.compiler.lang.descr.CollectDescr)1 EntryPointDescr (org.drools.compiler.lang.descr.EntryPointDescr)1 ForallDescr (org.drools.compiler.lang.descr.ForallDescr)1 MVELDataProvider (org.drools.core.base.dataproviders.MVELDataProvider)1