org.kie.api.builder.Message Java Examples

The following examples show how to use org.kie.api.builder.Message. 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 static byte[] createJar(KieServices ks, String kmoduleContent, Predicate<String> classFilter, ReleaseId releaseId, Resource... resources) {
    KieFileSystem kfs = ks.newKieFileSystem().generateAndWritePomXML(releaseId).writeKModuleXML(kmoduleContent);
    for (int i = 0; i < resources.length; i++) {
        if (resources[i] != null) {
            kfs.write(resources[i]);
        }
    }
    KieBuilder kieBuilder = ks.newKieBuilder(kfs);
    ((InternalKieBuilder) kieBuilder).buildAll(classFilter);
    Results results = kieBuilder.getResults();
    if (results.hasMessages(Message.Level.ERROR)) {
        throw new IllegalStateException(results.getMessages(Message.Level.ERROR).toString());
    }
    InternalKieModule kieModule = (InternalKieModule) ks.getRepository()
            .getKieModule(releaseId);
    byte[] jar = kieModule.getBytes();
    return jar;
}
 
Example #2
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooManyPositionalArguments() throws InstantiationException, IllegalAccessException {
    // DROOLS-559
    String drl = "package org.test;\n" +
                 "global java.util.List names;\n" +
                 "declare Person\n" +
                 "    name : String\n" +
                 "    age : int\n" +
                 "end\n" +
                 "rule R when \n" +
                 "    $p : Person( \"Mark\", 37, 42; )\n" +
                 "then\n" +
                 "    names.add( $p.getName() );\n" +
                 "end\n";

    KieBuilder kieBuilder = build(drl);

    assertTrue( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );
}
 
Example #3
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutOfRangePositions() throws InstantiationException, IllegalAccessException {
    // DROOLS-559
    String drl = "package org.test;\n" +
                 "global java.util.List names;\n" +
                 "declare Person\n" +
                 "    name : String @position(3)\n" +
                 "    age : int @position(1)\n" +
                 "end\n" +
                 "rule R when \n" +
                 "    $p : Person( 37, \"Mark\"; )\n" +
                 "then\n" +
                 "    names.add( $p.getName() );\n" +
                 "end\n";

    KieBuilder kieBuilder = build(drl);

    assertTrue( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );
}
 
Example #4
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDuplicatedPositions() throws InstantiationException, IllegalAccessException {
    // DROOLS-559
    String drl = "package org.test;\n" +
                 "global java.util.List names;\n" +
                 "declare Person\n" +
                 "    name : String @position(1)\n" +
                 "    age : int @position(1)\n" +
                 "end\n" +
                 "rule R when \n" +
                 "    $p : Person( 37, \"Mark\"; )\n" +
                 "then\n" +
                 "    names.add( $p.getName() );\n" +
                 "end\n";

    KieBuilder kieBuilder = build(drl);

    assertTrue( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );
}
 
Example #5
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnknownField() throws InstantiationException, IllegalAccessException {
    // DROOLS-546
    String drl = "package org.test; " +
                 "declare Pet" +
                 " " +
                 "end \n";

    KieBuilder kieBuilder = build(drl);

    assertFalse( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );
    KieBase kieBase = KieServices.Factory.get().newKieContainer( kieBuilder.getKieModule().getReleaseId() ).getKieBase();

    FactType factType = kieBase.getFactType("org.test", "Pet");
    Object instance = factType.newInstance();
    factType.get(instance, "unknownField");
    factType.set(instance, "unknownField", "myValue");
}
 
Example #6
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test()
public void testTraitExtendPojo() {
    //DROOLS-697
    final String s1 = "package test;\n" +

                      "declare Poojo " +
                      "end " +

                      "declare trait Mask extends Poojo " +
                      "end " +
                      "";

    KieHelper kh = new KieHelper();
    kh.addContent( s1, ResourceType.DRL );

    assertEquals( 1, kh.verify().getMessages( Message.Level.ERROR ).size() );
}
 
Example #7
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreventReflectionAPIsOnJavaClasses() {
    String drl = "package org.test; " +

                 // existing java class
                 "declare org.drools.compiler.Person " +
                 "  @role(event) " +
                 "end \n" +

                 "";

    KieBuilder kieBuilder = build(drl);

    assertFalse( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );
    KieBase kieBase = KieServices.Factory.get().newKieContainer( kieBuilder.getKieModule().getReleaseId() ).getKieBase();

    assertThrows(UnsupportedOperationException.class,
                 () -> kieBase.getFactType( "org.drools.compiler", "Person" ));

}
 
Example #8
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test()
public void testPojoExtendInterface() {
    // DROOLS-697
    // It is now allowed for a declared type to extend an interface
    // The interface itself will be added to the implements part of the generated class

    final String s1 = "package test;\n" +

                      "declare Poojo extends Mask " +
                      "end " +

                      "declare trait Mask " +
                      "end " +
                      "";

    KieHelper kh = new KieHelper();
    kh.addContent( s1, ResourceType.DRL );

    assertEquals( 0, kh.verify().getMessages( Message.Level.ERROR ).size() );
}
 
Example #9
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryWithWrongParamNumber() {
    String drl = "global java.util.List list; " +
                 "" +
                 "query foo( Integer $i ) end " +
                 "" +
                 "rule React \n" +
                 "when\n" +
                 "  $i : Integer() " +
                 "  $j : Integer() " +
                 "  foo( $i, $j ; ) " +
                "then\n" +
                 "end";

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    Results results = helper.verify();
    assertTrue( results.hasMessages( Message.Level.ERROR ) );
    assertEquals( 1, results.getMessages( Message.Level.ERROR ).size() );
}
 
Example #10
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryWithSyntaxError() {
    String drl = "global java.util.List list; " +
                 "" +
                 "query foo( Integer $i ) end " +
                 "" +
                 "rule React \n" +
                 "when\n" +
                 "  $i : Integer() " +
                 "  foo( $i ) " +   // missing ";" should result in 1 compilation error
                 "then\n" +
                 "end";

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    Results results = helper.verify();
    assertTrue( results.hasMessages( Message.Level.ERROR ) );
    assertEquals( 1, results.getMessages( Message.Level.ERROR ).size() );
}
 
Example #11
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryWithIncompatibleArgs() {
    String drl = "global java.util.List list; " +
                 "" +
                 "query foo( String $s, String $s, String $s ) end " +
                 "" +
                 "rule React \n" +
                 "when\n" +
                 "  $i : Integer() " +
                 "  foo( $i, $x, $i ; ) " +
                 "then\n" +
                 "end";

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    Results results = helper.verify();
    assertTrue( results.hasMessages( Message.Level.ERROR ) );
    assertEquals( 2, results.getMessages( Message.Level.ERROR ).size() );
}
 
Example #12
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeclareExtendsWithFullyQualifiedName() {
    String drl = "package org.drools.extends.test; \n" +
                 "" +
                 "declare org.drools.extends.test.Foo end \n" +
                 "declare org.drools.extends.test.Bar extends org.drools.extends.test.Foo end \n" +
                 "";
    KieServices kieServices = KieServices.Factory.get();
    KieFileSystem kfs = kieServices.newKieFileSystem();
    kfs.write( kieServices.getResources().newByteArrayResource( drl.getBytes() )
                       .setSourcePath( "test.drl" )
                       .setResourceType( ResourceType.DRL ) );
    KieBuilder kieBuilder = kieServices.newKieBuilder( kfs );
    kieBuilder.buildAll();

    assertFalse( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );

}
 
Example #13
Source File: DeleteTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() {
    KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
    kfs.write(KieServices.Factory.get().getResources()
            .newClassPathResource(DELETE_TEST_DRL, DeleteTest.class));

    KieBuilder kbuilder = KieServices.Factory.get().newKieBuilder(kfs);
    kbuilder.buildAll();

    List<Message> res = kbuilder.getResults().getMessages(Level.ERROR);
    assertThat(res).isEmpty();

    KieBase kbase = KieServices.Factory.get()
            .newKieContainer(kbuilder.getKieModule().getReleaseId())
            .getKieBase();

    ksession = kbase.newKieSession();
}
 
Example #14
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRedeclareWithInterfaceExtensionAndOverride() {
    final String s1 = "package test;\n" +

                      "declare trait " + Ext.class.getCanonicalName() + " extends " + Base.class.getCanonicalName() + " " +
                      " fld : String " +
                      "end " +

                      "declare trait " + Base.class.getCanonicalName() + " " +
                      "end " +
                      "";

    KieHelper kh = new KieHelper();
    kh.addContent( s1, ResourceType.DRL );

    assertEquals( 0, kh.verify().getMessages( Message.Level.ERROR ).size() );
}
 
Example #15
Source File: DslExpansionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDSLExpansion_NoExpansion() throws Exception {
    final KieServices ks = KieServices.Factory.get();
    final ReleaseId releaseId = ks.newReleaseId( "org.kie", "dsl-test", "1.0" );
    final KieModuleModel kproj = ks.newKieModuleModel();

    final KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML( kproj.toXML() )
            .writePomXML( generatePomXml( releaseId ) )
            .write( "src/main/resources/KBase1/test-dsl.dsl", createDSL() )
            .write( "src/main/resources/KBase1/test-rule.drl", createDRL() );

    final KieBuilder kieBuilder = ks.newKieBuilder( kfs );
    final List<Message> messages = kieBuilder.buildAll().getResults().getMessages();
    if ( !messages.isEmpty() ) {
        for ( final Message m : messages ) {
            System.out.println( m.getText() );
        }
    }
    assertFalse( messages.isEmpty() );
}
 
Example #16
Source File: DslExpansionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDSLExpansion_MessageImplNPE() throws Exception {
    final KieServices ks = KieServices.Factory.get();
    final ReleaseId releaseId = ks.newReleaseId( "org.kie", "dsl-test", "1.0" );
    final KieModuleModel kproj = ks.newKieModuleModel();

    final KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML( kproj.toXML() )
            .writePomXML( generatePomXml( releaseId ) )
            .write( "src/main/resources/KBase1/test-dsl.dsl", createDSL() )
            .write( "src/main/resources/KBase1/test-rule.dslr", createDRL() );

    final KieBuilder kieBuilder = ks.newKieBuilder( kfs );
    final List<Message> messages = kieBuilder.buildAll().getResults().getMessages();
    if ( !messages.isEmpty() ) {
        for ( final Message m : messages ) {
            System.out.println( m.getText() );
        }
    }
    assertTrue( messages.isEmpty() );
}
 
Example #17
Source File: RulesConfiguration.java    From cia with Apache License 2.0 6 votes vote down vote up
/**
 * Kie container.
 *
 * @return the kie container
 */
@Bean
public KieContainer kieContainer() {
	final KieServices kieServices = KieServices.Factory.get();

	final KieContainer kContainer = kieServices.getKieClasspathContainer();
	LOGGER.info("Using classloader {}, parent {}",kContainer.getClassLoader(),kContainer.getClassLoader().getParent());
	
	final Results verifyResults = kContainer.verify();
	for (final Message m : verifyResults.getMessages()) {
		LOGGER.warn("Kie container message: {}", m);
	}

	final KieBase kieBase = kContainer.getKieBase();
	for (final KiePackage kp : kieBase.getKiePackages()) {
		for (final Rule rule : kp.getRules()) {
			LOGGER.info("Loadded Rule: {} {}", kp, rule.getName());
		}
	}
	

	return kContainer;
}
 
Example #18
Source File: BaseTest.java    From iot-ocp with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    KieServices kieServices = KieServices.Factory.get();

    KieContainer kContainer = kieServices.getKieClasspathContainer();
    Results verifyResults = kContainer.verify();
    for (Message m : verifyResults.getMessages()) {
        LOG.debug("Kie container message: {}", m);
    }

    KieBase kieBase = kContainer.getKieBase();
    LOG.debug("Created kieBase");

    for ( KiePackage kp : kieBase.getKiePackages() ) {
        for (Rule rule : kp.getRules()) {
            LOG.debug("kp " + kp + " rule " + rule.getName());
        }
    }

    session = kieBase.newKieSession();
    LOG.info(session.getGlobals().toString());
    Logger kieLogger = LoggerFactory.getLogger(this.getClass());
   // session.setGlobal("logger",kieLogger);
}
 
Example #19
Source File: RulesManager.java    From hacep with Apache License 2.0 6 votes vote down vote up
public boolean updateToVersion(String version) {
    checkStatus();
    if (StringUtils.isEmpty(version)) {
        throw new IllegalArgumentException("Update to version cannot accept an empty version");
    }
    ReleaseId releaseId = kieServices.newReleaseId(
            rulesConfiguration.getGroupId(),
            rulesConfiguration.getArtifactId(),
            version);
    Results results = kieContainer.updateToVersion(releaseId);
    this.releaseId = kieContainer.getReleaseId();
    KieSessionUtils.logResults(results);
    if (results.hasMessages(Message.Level.ERROR)) {
        LOGGER.error("Update to version {} aborted due to errors", version);
        return false;
    }
    LOGGER.info("Update to version {} completed", version);
    return true;
}
 
Example #20
Source File: OOPathCastTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidCast() {
    final String drl =
            "import org.drools.compiler.oopath.model.*;\n" +
                    "global java.util.List list\n" +
                    "\n" +
                    "rule R when\n" +
                    "  Man( $toy: /wife/children#Man/toys )\n" +
                    "then\n" +
                    "  list.add( $toy.getName() );\n" +
                    "end\n";

    final KieServices ks = KieServices.Factory.get();
    final KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
    final Results results = ks.newKieBuilder( kfs ).buildAll().getResults();
    assertTrue( results.hasMessages( Message.Level.ERROR ) );
}
 
Example #21
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromString( String drlString, KieBaseConfiguration kbConf ) {
    KieHelper kieHelper = new KieHelper();
    kieHelper.addContent( drlString, ResourceType.DRL );

    Results res = kieHelper.verify();
    if ( res.hasMessages( Message.Level.ERROR ) ) {
        fail( res.getMessages( Message.Level.ERROR ).toString() );
    }

    if ( kbConf == null ) {
        kbConf = KieServices.Factory.get().newKieBaseConfiguration();
    }
    kbConf.setOption( EqualityBehaviorOption.EQUALITY );
    KieBase kieBase = kieHelper.build( kbConf );


    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );
    return kieBase.newKieSession( ksConf, null );
}
 
Example #22
Source File: OOPathReactiveTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidDoubleNonReactivePart() {
    final String drl =
            "import org.drools.compiler.oopath.model.*;\n" +
                    "global java.util.List list\n" +
                    "\n" +
                    "rule R when\n" +
                    "  Man( $toy: /wife?/children[age > 10]?/toys )\n" +
                    "then\n" +
                    "  list.add( $toy.getName() );\n" +
                    "end\n";

    final KieServices ks = KieServices.Factory.get();
    final KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
    final Results results = ks.newKieBuilder( kfs ).buildAll().getResults();
    assertTrue( results.hasMessages( Message.Level.ERROR ) );
}
 
Example #23
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static byte[] createJar(KieServices ks,
        ReleaseId releaseId,
        String... drls) {
    KieFileSystem kfs = ks.newKieFileSystem().generateAndWritePomXML(
            releaseId);
    for (int i = 0; i < drls.length; i++) {
        if (drls[i] != null) {
            kfs.write("src/main/resources/r" + i + ".drl", drls[i]);
        }
    }
    KieBuilder kb = ks.newKieBuilder(kfs).buildAll();
    assertFalse(kb.getResults().hasMessages(org.kie.api.builder.Message.Level.ERROR),
                kb.getResults().getMessages(org.kie.api.builder.Message.Level.ERROR).toString());
    InternalKieModule kieModule = (InternalKieModule) ks.getRepository()
            .getKieModule(releaseId);
    byte[] jar = kieModule.getBytes();
    return jar;
}
 
Example #24
Source File: ReloadDroolsRulesService.java    From drools-examples with Apache License 2.0 6 votes vote down vote up
private  KieContainer loadContainerFromString(List<Rule> rules) {
    long startTime = System.currentTimeMillis();
    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();
    KieFileSystem kfs = ks.newKieFileSystem();

    for (Rule rule:rules) {
        String  drl=rule.getContent();
        kfs.write("src/main/resources/" + drl.hashCode() + ".drl", drl);
    }

    KieBuilder kb = ks.newKieBuilder(kfs);

    kb.buildAll();
    if (kb.getResults().hasMessages(Message.Level.ERROR)) {
        throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
    }
    long endTime = System.currentTimeMillis();
    System.out.println("Time to build rules : " + (endTime - startTime)  + " ms" );
    startTime = System.currentTimeMillis();
    KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
    endTime = System.currentTimeMillis();
    System.out.println("Time to load container: " + (endTime - startTime)  + " ms" );
    return kContainer;
}
 
Example #25
Source File: DroolsUtils.java    From spring-boot-start-current with Apache License 2.0 6 votes vote down vote up
private static KieContainer buildKieContainer ( List< String > ruleContents ) {
    // 获取的各种对象来完成规则构建、管理和执行等操作
    KieServices kieServices = KieServices.Factory.get();
    // 用于以编程方式定义组成KieModule的资源
    KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
    for ( String ruleContent : ruleContents ) {
        kieFileSystem.write( "src/main/resources/" + System.currentTimeMillis() + ".drl" , ruleContent );
    }
    // KieBuilder是KieModule中包含的资源的构建者
    KieBuilder kieBuilder = kieServices.newKieBuilder( kieFileSystem ).buildAll();

    // 如果有错误
    if ( kieBuilder.getResults().hasMessages() ) {
        LogUtils.getLogger().warn( kieBuilder.getResults().getMessages() );
        if ( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) ) {
            throw new RuntimeException( kieBuilder.getResults()
                                                  .getMessages()
                                                  .parallelStream()
                                                  .map( Message::getText ).collect( Collectors.joining( "," ) )
            );
        }
    }
    // 用来访问KBase和KSession等信息
    return kieServices.newKieContainer( kieServices.getRepository().getDefaultReleaseId() );
}
 
Example #26
Source File: KieSessionUtils.java    From hacep with Apache License 2.0 6 votes vote down vote up
public static void logResults(Results results) {
    for (Message result : results.getMessages()) {
        switch (result.getLevel()) {
            case ERROR:
                LOGGER.error(result.toString());
                break;
            case WARNING:
                LOGGER.warn(result.toString());
                break;
            case INFO:
                LOGGER.info(result.toString());
                break;
            default:
                LOGGER.warn(result.toString());
        }
    }
}
 
Example #27
Source File: MessageImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static List<Message> filterMessages( List<Message> messages,
                                            Level... levels ) {
    List<Message> filteredMsgs = new ArrayList<Message>();
    if ( levels != null && levels.length > 0 ) {
        for ( Level level : levels ) {
            for ( Message msg : messages ) {
                if ( msg.getLevel() == level ) {
                    filteredMsgs.add( msg );
                }
            }
        }
    }
    return filteredMsgs;
}
 
Example #28
Source File: DroolsUtil.java    From qzr with Apache License 2.0 5 votes vote down vote up
private static String prettyBuildMessage(Message msg) {
    return "Message: {"
        + "id="+ msg.getId()
        + ", level=" + msg.getLevel()
        + ", path=" + msg.getPath()
        + ", line=" + msg.getLine()
        + ", column=" + msg.getColumn()
        + ", text=\"" + msg.getText() + "\""
        + "}";
}
 
Example #29
Source File: PhreakInspector.java    From drools-workshop with Apache License 2.0 5 votes vote down vote up
private void assertBuildResults(Results results) {
    if (results.hasMessages(Message.Level.WARNING, Message.Level.ERROR)) {
        List<Message> messages = results.getMessages(Message.Level.WARNING, Message.Level.ERROR);
        for (Message message : messages) {
            System.out.printf("[%s] - %s[%s,%s]: %s", message.getLevel(), message.getPath(), message.getLine(), message.getColumn(), message.getText());
        }

        throw new IllegalStateException("Compilation errors were found. Check the logs.");
    }
}
 
Example #30
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclarationOfClassWithNonStandardSetterAndFulllName() {
    final String s1 = "package test; " +
                      "import " + BeanishClass.class.getCanonicalName() + "; " +

                      "declare " + BeanishClass.class.getName() + " @propertyReactive end " +

                      "rule Check when BeanishClass() @watch( foo ) then end ";

    KieHelper kh = new KieHelper();
    kh.addContent( s1, ResourceType.DRL );

    assertEquals( 0, kh.verify().getMessages( Message.Level.ERROR ).size() );
}