Java Code Examples for org.kie.internal.builder.KnowledgeBuilder#getErrors()

The following examples show how to use org.kie.internal.builder.KnowledgeBuilder#getErrors() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieSession genSession(String[] sources, int numerrors)  {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    for (String source : sources)
        kbuilder.add( ResourceFactory.newClassPathResource(source, getClass()), ResourceType.DRL );
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if ( kbuilder.getErrors().size() > 0 ) {
        for ( KnowledgeBuilderError error : kbuilder.getErrors() ) {
            System.err.println( error );
        }
    }
    assertEquals(numerrors, errors.size() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    kbase.addPackages( kbuilder.getKnowledgePackages() );

    return createKnowledgeSession(kbase);

}
 
Example 2
Source File: JBRULESTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testJBRULES2872() {
    final String str = "package org.drools.compiler.test\n" +
            "import org.drools.compiler.FactA\n" +
            "rule X\n" +
            "when\n" +
            "    FactA( enumVal == TestEnum.ONE || == TestEnum.TWO )\n" +
            "then\n" +
            "end\n";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    assertTrue(kbuilder.hasErrors());
    final KnowledgeBuilderErrors errors = kbuilder.getErrors();
    assertEquals(1, errors.size());
    final KnowledgeBuilderError error = errors.iterator().next();
    assertEquals(5, error.getLines()[0]);
}
 
Example 3
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallActivity() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-CallActivity.bpmn2"), ResourceType.BPMN2);
    kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-CallActivitySubProcess.bpmn2"), ResourceType.BPMN2);
    if (!kbuilder.getErrors().isEmpty()) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
            logger.error("{}", error);
        }
        throw new IllegalArgumentException("Errors while parsing knowledge base");
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession ksession = createKnowledgeSession(kbase);
    
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("x", "oldValue");
    ProcessInstance processInstance = ksession.startProcess("ParentProcess", params);
    assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED);
    assertThat(((WorkflowProcessInstance) processInstance).getVariable("y")).isEqualTo("new value");
}
 
Example 4
Source File: KieBuilderSetImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private Set<String> findResourcesWithErrors(KnowledgeBuilder kBuilder) {
    if ( kBuilder.hasErrors() ) {
        Set<String> resourcesWithErrors = new HashSet<String>();
        for ( KnowledgeBuilderError error : kBuilder.getErrors() ) {
            resourcesWithErrors.add(error.getResource().getSourcePath());
        }
        return resourcesWithErrors;
    }
    return Collections.emptySet();
}
 
Example 5
Source File: StrEvaluatorTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBase readKnowledgeBase() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newInputStreamResource(getClass().getResourceAsStream("strevaluator_test.drl")),
            ResourceType.DRL );
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (errors.size() > 0) {
        for (KnowledgeBuilderError error: errors) {
            System.err.println(error);
        }
        throw new IllegalArgumentException("Could not parse knowledge." + errors.toArray());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    return kbase;
}
 
Example 6
Source File: DroolsDeclaredTypeSequenceFlowExpressionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclaredTypesInSequenceFlowDroolsExpression() {
	//DROOLS-1327	
	
	String drl = "package org.drools.test;" 
		+ "declare TestFact \n"
		+ "value: Integer\n"
		+ "end\n";
	
	KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
	CompositeKnowledgeBuilder ckbuilder = kbuilder.batch();		
	
	Resource drlResource = new InputStreamResource(new ByteArrayInputStream(drl.getBytes(StandardCharsets.UTF_8))); 
	Resource bpmn2Resource = new ClassPathResource("BPMN2-DroolsDeclaredTypeSequenceFlowExpressionTest.bpmn2");
	
	ckbuilder.add(drlResource, ResourceType.DRL);
	ckbuilder.add(bpmn2Resource, ResourceType.BPMN2);
	
	ckbuilder.build();
	
	//Assert that we don't have any issues in the build.
	if (kbuilder.hasErrors()) {
		KnowledgeBuilderErrors kbErrors = kbuilder.getErrors();
		for (KnowledgeBuilderError nextError: kbErrors) {
			fail(nextError.getMessage());
		}	
	}
	
	if(kbuilder.hasResults(ResultSeverity.WARNING)) {
		KnowledgeBuilderResults kbResults = kbuilder.getResults(ResultSeverity.WARNING);
		for (KnowledgeBuilderResult nextResult: kbResults) {
			fail(nextResult.getMessage());
		}
	}
}
 
Example 7
Source File: JavaDialectTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testEvalDetectionInAlphaNode() {
    // Tests evals are generated and executed with Java dialect
    String drl = "";
    drl += "package org.drools.compiler.test\n";
    drl += "import org.drools.compiler.Person\n";
    drl += "global java.util.List list\n";
    drl += "rule test1\n";
    drl += "when\n";
    drl += "   $p1 : Person( eval( name \n != null ), name == ( new String(\"xxx\") ) )\n";
    drl += "then\n";
    drl += "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newReaderResource(new StringReader(drl)),
                  ResourceType.DRL );
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    assertFalse( kbuilder.hasErrors() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    
    List<ObjectTypeNode> nodes = ((KnowledgeBaseImpl)kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for ( ObjectTypeNode n : nodes ) {
        if ( ((ClassObjectType)n.getObjectType()).getClassType() == Person.class ) {
            node = n;
            break;
        }
    }
    
    AlphaNode alphanode = (AlphaNode) node.getObjectSinkPropagator().getSinks()[0];
    PredicateConstraint c = ( PredicateConstraint ) alphanode.getConstraint();
    assertTrue( c.getPredicateExpression() instanceof PredicateExpression );
    assertTrue( c.getPredicateExpression() instanceof CompiledInvoker );

    alphanode = (AlphaNode) alphanode.getObjectSinkPropagator().getSinks()[0];
    AlphaNodeFieldConstraint constraint = alphanode.getConstraint();

    if (constraint instanceof MvelConstraint) {
        FieldValue fieldVal = (( MvelConstraint ) constraint).getField();
        assertEquals( "xxx", fieldVal.getValue() );
    }
}
 
Example 8
Source File: JavaDialectTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testEvalDetectionInBetaNode() {
    // Tests evals are generated and executed with Java dialect
    
    String drl = "";
    drl += "package org.drools.compiler.test\n";
    drl += "import org.drools.compiler.Person\n";
    drl += "global java.util.List list\n";
    drl += "rule test1\n";
    drl += "when\n";
    drl += "   $s  : String()\n";
    drl += "   $p1 : Person( eval( name \n != $s ), name == ( new String($s+\"xxx\") ) )\n";
    drl += "then\n";
    drl += "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newReaderResource( new StringReader( drl ) ),
                  ResourceType.DRL );
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    assertFalse( kbuilder.hasErrors() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    
    List<ObjectTypeNode> nodes = ((KnowledgeBaseImpl)kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for ( ObjectTypeNode n : nodes ) {
        if ( ((ClassObjectType)n.getObjectType()).getClassType() == Person.class ) {
            node = n;
            break;
        }
    }
    
    BetaNode betaanode = (BetaNode) node.getObjectSinkPropagator().getSinks()[0];
    BetaNodeFieldConstraint[] constraint = betaanode.getConstraints();
    PredicateConstraint c = ( PredicateConstraint ) constraint[0];
    assertTrue( c.getPredicateExpression() instanceof PredicateExpression );
    assertTrue( c.getPredicateExpression() instanceof CompiledInvoker );
}
 
Example 9
Source File: DrlParserTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private void assertHasNoErrors(KnowledgeBuilder kbuilder) {
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    assertEquals(0, errors.size(),  "Expected no build errors, but got: " + errors.toString());
}
 
Example 10
Source File: ProcessSplitTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSplitWithProcessInstanceConstraint2() {
	KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    Reader source = new StringReader(
        "<process xmlns=\"http://drools.org/drools-5.0/process\"" +
        "         xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"" +
        "         xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"" +
        "         type=\"RuleFlow\" name=\"ruleflow\" id=\"org.jbpm.process-split\" package-name=\"org.jbpm\" >" +
        "" +
        "  <header>" +
        "    <imports>" +
        "      <import name=\"org.jbpm.integrationtests.test.Person\" />" +
        "      <import name=\"org.kie.api.runtime.process.WorkflowProcessInstance\" />" +
        "    </imports>" +
        "    <globals>" +
        "      <global identifier=\"list\" type=\"java.util.List\" />" +
        "    </globals>" +
        "    <variables>\n" +
        "      <variable name=\"name\" >\n" +
        "        <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
        "      </variable>\n" +
        "    </variables>\n" +
        "  </header>" +
        "" +
        "  <nodes>" +
        "    <actionNode id=\"2\" name=\"Action\" >" +
        "        <action type=\"expression\" dialect=\"mvel\" >insert(kcontext.getProcessInstance());</action>" +
        "    </actionNode>" +
        "    <split id=\"4\" name=\"Split\" type=\"2\" >" +
        "      <constraints>" +
        "        <constraint toNodeId=\"8\" toType=\"DROOLS_DEFAULT\" priority=\"2\" type=\"rule\" dialect=\"mvel\" >eval(true)</constraint>" +
        "        <constraint toNodeId=\"6\" toType=\"DROOLS_DEFAULT\" name=\"constraint\" priority=\"1\" type=\"rule\" dialect=\"mvel\" >processInstance: WorkflowProcessInstance()" +
        "Person( name == ( processInstance.getVariable(\"name\") ) )</constraint>" +
        "      </constraints>" +
        "    </split>" +
        "    <end id=\"8\" name=\"End\" />" +
        "    <actionNode id=\"6\" name=\"Action\" >" +
        "        <action type=\"expression\" dialect=\"mvel\" >list.add(kcontext.getProcessInstance().getId());</action>" +
        "    </actionNode>" +
        "    <start id=\"1\" name=\"Start\" />" +
        "    <end id=\"3\" name=\"End\" />" +
        "  </nodes>" +
        "  <connections>" +
        "    <connection from=\"1\" to=\"2\" />" +
        "    <connection from=\"2\" to=\"4\" />" +
        "    <connection from=\"4\" to=\"8\" />" +
        "    <connection from=\"4\" to=\"6\" />" +
        "    <connection from=\"6\" to=\"3\" />" +
        "  </connections>" +
        "" +
        "</process>");
    kbuilder.add( ResourceFactory.newReaderResource( source ), ResourceType.DRF );
    for (KnowledgeBuilderError error: kbuilder.getErrors()) {
        logger.error(error.toString());
    }
    
    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kpkgs );        
    KieSession ksession = kbase.newKieSession();
    List<Long> list = new ArrayList<Long>();
    ksession.setGlobal("list", list);

    Person john = new Person("John Doe", 20);
    Person jane = new Person("Jane Doe", 20);
    Person julie = new Person("Julie Doe", 20);
    ksession.insert(john);
    ksession.insert(jane);
    
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("name", john.getName());
    ProcessInstance processInstance1 =
        ksession.startProcess("org.jbpm.process-split", params);
    
    params = new HashMap<String, Object>();
    params.put("name", jane.getName());
    ProcessInstance processInstance2 =
    	ksession.startProcess("org.jbpm.process-split", params);
    
    params = new HashMap<String, Object>();
    params.put("name", julie.getName());
    ProcessInstance processInstance3 =
        ksession.startProcess("org.jbpm.process-split", params);
    
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance1.getState());
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance2.getState());
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance3.getState());
    assertEquals(2, list.size());
}
 
Example 11
Source File: DdLoadTest.java    From drools-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	//rule,rule2可以放在数据库中,有个唯一code和他们对于,代码要执行规则的时候,根据code从数据库获取出来就OK了,这样自己开发的规则管理系统那边对数据库里的规则进行维护就行了
	String rule = "package com.neo.drools\r\n";
	rule += "import com.neo.drools.model.Message;\r\n";
	rule += "rule \"rule1\"\r\n";
	rule += "\twhen\r\n";
	rule += "Message( status == 1, myMessage : msg )";
	rule += "\tthen\r\n";
	rule += "\t\tSystem.out.println( 1+\":\"+myMessage );\r\n";
	rule += "end\r\n";


	String rule2 = "package com.neo.drools\r\n";
	rule += "import com.neo.drools.model.Message;\r\n";

	rule += "rule \"rule2\"\r\n";
	rule += "\twhen\r\n";
	rule += "Message( status == 2, myMessage : msg )";
	rule += "\tthen\r\n";
	rule += "\t\tSystem.out.println( 2+\":\"+myMessage );\r\n";
	rule += "end\r\n";


	StatefulKnowledgeSession kSession = null;
	try {


		KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder();
		//装入规则,可以装入多个
		kb.add(ResourceFactory.newByteArrayResource(rule.getBytes("utf-8")), ResourceType.DRL);
		kb.add(ResourceFactory.newByteArrayResource(rule2.getBytes("utf-8")), ResourceType.DRL);

		KnowledgeBuilderErrors errors = kb.getErrors();
		for (KnowledgeBuilderError error : errors) {
			System.out.println(error);
		}
		KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
		kBase.addKnowledgePackages(kb.getKnowledgePackages());

		kSession = kBase.newStatefulKnowledgeSession();


		Message message1 = new Message();
		message1.setStatus(1);
		message1.setMsg("hello world!");

		Message message2 = new Message();
		message2.setStatus(2);
		message2.setMsg("hi world!");

		kSession.insert(message1);
		kSession.insert(message2);
		kSession.fireAllRules();

	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	} finally {
		if (kSession != null)
			kSession.dispose();
	}

}