Search in sources :

Example 1 with FactTemplate

use of org.drools.core.facttemplates.FactTemplate in project drools by kiegroup.

the class PatternBuilder method getFieldReadAccessor.

public static InternalReadAccessor getFieldReadAccessor(final RuleBuildContext context, final BaseDescr descr, final Pattern pattern, final ObjectType objectType, String fieldName, final AcceptsReadAccessor target, final boolean reportError) {
    // reportError is needed as some times failure to build accessor is not a failure, just an indication that building is not possible so try something else.
    InternalReadAccessor reader;
    if (ValueType.FACTTEMPLATE_TYPE.equals(objectType.getValueType())) {
        // @todo use accessor cache
        final FactTemplate factTemplate = ((FactTemplateObjectType) objectType).getFactTemplate();
        reader = new FactTemplateFieldExtractor(factTemplate, factTemplate.getFieldTemplateIndex(fieldName));
        if (target != null) {
            target.setReadAccessor(reader);
        }
        return reader;
    }
    boolean isGetter = getterRegexp.matcher(fieldName).matches();
    if (isGetter) {
        fieldName = fieldName.substring(3, fieldName.indexOf('(')).trim();
    }
    if (isGetter || identifierRegexp.matcher(fieldName).matches()) {
        Declaration decl = context.getDeclarationResolver().getDeclarations(context.getRule()).get(fieldName);
        if (decl != null && decl.getExtractor() instanceof ClassFieldReader && "this".equals(((ClassFieldReader) decl.getExtractor()).getFieldName())) {
            return decl.getExtractor();
        }
        try {
            reader = context.getPkg().getClassFieldAccessorStore().getReader(objectType.getClassName(), fieldName, target);
        } catch (final Exception e) {
            if (reportError && context.isTypesafe()) {
                DialectUtil.copyErrorLocation(e, descr);
                registerDescrBuildError(context, descr, e, "Unable to create Field Extractor for '" + fieldName + "'" + e.getMessage());
            }
            // if there was an error, set the reader back to null
            reader = null;
        } finally {
            if (reportError) {
                Collection<KnowledgeBuilderResult> results = context.getPkg().getClassFieldAccessorStore().getWiringResults(objectType.getClassType(), fieldName);
                if (!results.isEmpty()) {
                    for (KnowledgeBuilderResult res : results) {
                        if (res.getSeverity() == ResultSeverity.ERROR) {
                            context.addError(new DroolsErrorWrapper(res));
                        } else {
                            context.addWarning(new DroolsWarningWrapper(res));
                        }
                    }
                }
            }
        }
    } else {
        // we need MVEL extractor for expressions
        Dialect dialect = context.getDialect();
        try {
            MVELDialect mvelDialect = (MVELDialect) context.getDialect("mvel");
            context.setDialect(mvelDialect);
            final AnalysisResult analysis = context.getDialect().analyzeExpression(context, descr, fieldName, new BoundIdentifiers(pattern, context, Collections.EMPTY_MAP, objectType.getClassType()));
            if (analysis == null) {
                // something bad happened
                if (reportError) {
                    registerDescrBuildError(context, descr, "Unable to analyze expression '" + fieldName + "'");
                }
                return null;
            }
            final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
            if (!usedIdentifiers.getDeclrClasses().isEmpty()) {
                if (reportError && descr instanceof BindingDescr) {
                    registerDescrBuildError(context, descr, "Variables can not be used inside bindings. Variable " + usedIdentifiers.getDeclrClasses().keySet() + " is being used in binding '" + fieldName + "'");
                }
                return null;
            }
            reader = context.getPkg().getClassFieldAccessorStore().getMVELReader(context.getPkg().getName(), objectType.getClassName(), fieldName, context.isTypesafe(), ((MVELAnalysisResult) analysis).getReturnType());
            MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
            ((MVELCompileable) reader).compile(data, context.getRule());
            data.addCompileable((MVELCompileable) reader);
        } catch (final Exception e) {
            int dotPos = fieldName.indexOf('.');
            String varName = dotPos > 0 ? fieldName.substring(0, dotPos).trim() : fieldName;
            if (context.getKnowledgeBuilder().getGlobals().containsKey(varName)) {
                return null;
            }
            if (reportError) {
                DialectUtil.copyErrorLocation(e, descr);
                registerDescrBuildError(context, descr, e, "Unable to create reader for '" + fieldName + "':" + e.getMessage());
            }
            // if there was an error, set the reader back to null
            reader = null;
        } finally {
            context.setDialect(dialect);
        }
    }
    return reader;
}
Also used : FactTemplateFieldExtractor(org.drools.core.facttemplates.FactTemplateFieldExtractor) BindingDescr(org.drools.compiler.lang.descr.BindingDescr) MVELCompileable(org.drools.core.base.mvel.MVELCompileable) DroolsErrorWrapper(org.drools.compiler.compiler.DroolsErrorWrapper) MVELDialect(org.drools.compiler.rule.builder.dialect.mvel.MVELDialect) DroolsParserException(org.drools.compiler.compiler.DroolsParserException) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) MVELAnalysisResult(org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) MVELAnalysisResult(org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult) ClassFieldReader(org.drools.core.base.ClassFieldReader) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) Dialect(org.drools.compiler.compiler.Dialect) MVELDialect(org.drools.compiler.rule.builder.dialect.mvel.MVELDialect) JavaDialect(org.drools.compiler.rule.builder.dialect.java.JavaDialect) FactTemplateObjectType(org.drools.core.facttemplates.FactTemplateObjectType) DroolsWarningWrapper(org.drools.compiler.compiler.DroolsWarningWrapper) Declaration(org.drools.core.rule.Declaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration) FactTemplate(org.drools.core.facttemplates.FactTemplate) KnowledgeBuilderResult(org.kie.internal.builder.KnowledgeBuilderResult)

Example 2 with FactTemplate

use of org.drools.core.facttemplates.FactTemplate in project drools by kiegroup.

the class Misc2Test method testFactTemplates.

@Test
public void testFactTemplates() {
    // DROOLS-600
    String drl = "package com.testfacttemplate;" + " rule \"test rule\" " + " dialect \"mvel\" " + " when " + " $test : TestFactTemplate( status == 1 ) " + " then " + " System.out.println( \"Hello World\" ); " + " end ";
    KnowledgePackageImpl kPackage = new KnowledgePackageImpl("com.testfacttemplate");
    FieldTemplate fieldTemplate = new FieldTemplateImpl("status", 0, Integer.class);
    FactTemplate factTemplate = new FactTemplateImpl(kPackage, "TestFactTemplate", new FieldTemplate[] { fieldTemplate });
    KnowledgeBuilder kBuilder = new KnowledgeBuilderImpl(kPackage);
    StringReader rule = new StringReader(drl);
    try {
        ((KnowledgeBuilderImpl) kBuilder).addPackageFromDrl(rule);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : FactTemplateImpl(org.drools.core.facttemplates.FactTemplateImpl) FieldTemplate(org.drools.core.facttemplates.FieldTemplate) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) FieldTemplateImpl(org.drools.core.facttemplates.FieldTemplateImpl) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) StringReader(java.io.StringReader) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) DroolsParserException(org.drools.compiler.compiler.DroolsParserException) FactTemplate(org.drools.core.facttemplates.FactTemplate) Test(org.junit.Test)

Example 3 with FactTemplate

use of org.drools.core.facttemplates.FactTemplate in project drools by kiegroup.

the class PatternTest method testDeclarationsFactTemplate.

@Test
public void testDeclarationsFactTemplate() throws Exception {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.store");
    final FieldTemplate cheeseName = new FieldTemplateImpl("name", 0, String.class);
    final FieldTemplate cheesePrice = new FieldTemplateImpl("price", 1, Integer.class);
    final FieldTemplate[] fields = new FieldTemplate[] { cheeseName, cheesePrice };
    final FactTemplate cheese = new FactTemplateImpl(pkg, "Cheese", fields);
    final ObjectType type = new FactTemplateObjectType(cheese);
    final Pattern col = new Pattern(0, type, "foo");
    final Declaration dec = col.getDeclaration();
    final InternalReadAccessor ext = dec.getExtractor();
    assertEquals(Fact.class, ext.getExtractToClass());
    final Fact stilton = cheese.createFact(10);
    stilton.setFieldValue("name", "stilton");
    stilton.setFieldValue("price", new Integer(200));
    assertEquals(stilton, dec.getValue(null, stilton));
}
Also used : FactTemplateImpl(org.drools.core.facttemplates.FactTemplateImpl) FieldTemplate(org.drools.core.facttemplates.FieldTemplate) FieldTemplateImpl(org.drools.core.facttemplates.FieldTemplateImpl) Fact(org.drools.core.facttemplates.Fact) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) FactTemplateObjectType(org.drools.core.facttemplates.FactTemplateObjectType) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) FactTemplateObjectType(org.drools.core.facttemplates.FactTemplateObjectType) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) FactTemplate(org.drools.core.facttemplates.FactTemplate) Test(org.junit.Test)

Aggregations

FactTemplate (org.drools.core.facttemplates.FactTemplate)3 DroolsParserException (org.drools.compiler.compiler.DroolsParserException)2 KnowledgePackageImpl (org.drools.core.definitions.impl.KnowledgePackageImpl)2 FactTemplateImpl (org.drools.core.facttemplates.FactTemplateImpl)2 FactTemplateObjectType (org.drools.core.facttemplates.FactTemplateObjectType)2 FieldTemplate (org.drools.core.facttemplates.FieldTemplate)2 FieldTemplateImpl (org.drools.core.facttemplates.FieldTemplateImpl)2 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)2 Test (org.junit.Test)2 StringReader (java.io.StringReader)1 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)1 AnalysisResult (org.drools.compiler.compiler.AnalysisResult)1 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)1 Dialect (org.drools.compiler.compiler.Dialect)1 DroolsErrorWrapper (org.drools.compiler.compiler.DroolsErrorWrapper)1 DroolsWarningWrapper (org.drools.compiler.compiler.DroolsWarningWrapper)1 BindingDescr (org.drools.compiler.lang.descr.BindingDescr)1 JavaDialect (org.drools.compiler.rule.builder.dialect.java.JavaDialect)1 MVELAnalysisResult (org.drools.compiler.rule.builder.dialect.mvel.MVELAnalysisResult)1 MVELDialect (org.drools.compiler.rule.builder.dialect.mvel.MVELDialect)1