org.kie.api.runtime.rule.QueryResultsRow Java Examples

The following examples show how to use org.kie.api.runtime.rule.QueryResultsRow. 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: QueryRulesJUnitTest.java    From drools-workshop with Apache License 2.0 6 votes vote down vote up
@Test
public void testQuery() {
    Assert.assertNotNull(kBase);
    KieSession kSession = kBase.newKieSession();
    System.out.println(" ---- Starting testQuery() Test ---");

    List<Person> generatePersons = generatePersons(100);
    for (Person p : generatePersons) {
        kSession.insert(p);
    }
    kSession.fireAllRules();
    QueryResults queryResults = kSession.getQueryResults("all persons older than", 50);
    for (QueryResultsRow row : queryResults) {
            System.out.println(" >>> Result : " + row.get("$p"));
    }

    System.out.println(" ---- Finished testQuery() Test ---");
    kSession.dispose();
}
 
Example #2
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testQuery() throws Exception {
    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("simple_query_test.drl"));
    KieSession session = createKieSession( kbase );

    final Cheese stilton = new Cheese( "stinky",
                                       5 );
    FactHandle factHandle = session.insert( stilton );
    session = SerializationHelper.getSerialisedStatefulKnowledgeSession(session, true);

    String queryName = "simple query";
    org.kie.api.runtime.rule.QueryResults results = getQueryResults(session, queryName);
    assertEquals( 1,
                  results.size() );

    QueryResultsRow row = results.iterator().next();
    if( row instanceof FlatQueryResultRow ) {
        FlatQueryResultRow flatRow = (FlatQueryResultRow) row;
        assertEquals( 0, flatRow.getIdentifiers().size() );
    } else if( row instanceof QueryResultsRowImpl ) {
        QueryResultsRowImpl rowImpl = (QueryResultsRowImpl) row;
        assertEquals( 0, rowImpl.getDeclarations().size() );
    }
}
 
Example #3
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryWithCollect() throws Exception {
    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_Query.drl"));
    KieSession session = createKieSession( kbase );
    session.fireAllRules();

    QueryResults results = getQueryResults( session, "collect objects" );
    assertEquals( 1,
                  results.size() );

    final QueryResultsRow row = results.iterator().next();
    final List list = (List) row.get( "$list" );

    assertEquals( 2,
                  list.size() );
}
 
Example #4
Source File: FoodRecommendationServiceImpl.java    From drools-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public Meal recommendMeal(Person person) throws BusinessException {
    StatelessKieSession kieSession = kContainer.newStatelessKieSession();

    InsertObjectCommand insertObjectCommand = new InsertObjectCommand(person);
    FireAllRulesCommand fireAllRulesCommand = new FireAllRulesCommand();
    QueryCommand queryCommand = new QueryCommand("results", "getMeal", (Object[]) null);
    List<GenericCommand<?>> commands = new ArrayList<GenericCommand<?>>();
    commands.add(insertObjectCommand);
    commands.add(fireAllRulesCommand);
    commands.add(queryCommand);
    BatchExecutionCommand batch = new BatchExecutionCommandImpl(commands);

    ExecutionResults results = kieSession.execute(batch);
    QueryResults queryResults = (QueryResults) results.getValue("results");
    Iterator<QueryResultsRow> iterator = queryResults.iterator();
    while (iterator.hasNext()) {
        Meal meal = (Meal) iterator.next().get("$m");
        if (meal != null) {
            System.out.println("Meal : " + meal);
            return meal;
        }
    }

    return null;
}
 
Example #5
Source File: ClinicalRulesJUnitTest.java    From drools-workshop with Apache License 2.0 6 votes vote down vote up
@Test
public void testPatientWithBloodPressureObservations() {

    printGeneratedDRL( ClinicalRulesJUnitTest.class.getResourceAsStream( "/rules/clinical-decision-table.xls" ), System.out );

    Assert.assertNotNull( kBase );
    KieSession kSession = kBase.newKieSession();

    kSession.insert( generatePatients( 1 ).get( 0 ) );

    List<Observation> observations = generateObservations( "headache", 4 );
    for ( Observation observation : observations ) {
        kSession.insert( observation );
    }

    Assert.assertEquals( 2, kSession.fireAllRules() );

    QueryResults queryResults = kSession.getQueryResults( "getAllRecommendations", ( Object ) null );
    for ( QueryResultsRow row : queryResults ) {
        Recommendation r = ( Recommendation ) row.get( "$r" );
        System.out.println( " >>> Result : " + r );
    }

    kSession.dispose();
}
 
Example #6
Source File: ConcurrentBasesParallelTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@ParameterizedConcurrentBasesParallelTest
public void testQueries(Parameters params) throws InterruptedException {
    final int numberOfObjects = 100;

    final TestExecutor exec = counter -> {
        final String query = "import " + BeanA.class.getCanonicalName() + ";\n" +
                "query Query " +
                "    bean : BeanA( seed == " + counter + " ) " +
                "end";

        final KieBase base = getKieBase(params, query);
        final KieSession session = base.newKieSession();

        try {
            final BeanA bean = new BeanA(counter);
            session.insert(bean);
            for (int i = 0; i < numberOfObjects; i++) {
                if (i != counter) {
                    session.insert(new BeanA(i));
                }
            }
            final QueryResults results = session.getQueryResults("Query");
            assertThat(results).hasSize(1);
            for (final QueryResultsRow row : results) {
                assertThat(row.get("bean")).isEqualTo(bean);
            }
            return true;
        } finally {
            session.dispose();
        }
    };

    parallelTest(NUMBER_OF_THREADS, exec);
}
 
Example #7
Source File: ConcurrentBasesParallelTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@ParameterizedConcurrentBasesParallelTest
public void testQueries2(Parameters params) throws InterruptedException {
    final int numberOfObjects = 100;

    final String queryTemplate = "import " + BeanA.class.getCanonicalName() + ";\n" +
            "query Query " +
            "    bean : BeanA( seed == ${seed} ) " +
            "end";

    final TestExecutor exec = counter -> {
        final int seed = counter % 2;
        final String seedString = "" + seed;
        final String queryDrl = queryTemplate.replace("${seed}", seedString);
        final KieBase base = getKieBase(params, queryDrl);
        final KieSession session = base.newKieSession();

        try {
            for (int i = 0; i < numberOfObjects; i++) {
                session.insert(new BeanA(seed));
            }
            final QueryResults results = session.getQueryResults("Query");
            assertThat(results).hasSize(numberOfObjects);
            for (final QueryResultsRow row : results) {
                final BeanA bean = (BeanA) row.get("bean");
                assertThat(bean.getSeed()).isEqualTo(seed);
            }
            return true;
        } finally {
            session.dispose();
        }
    };

    parallelTest(NUMBER_OF_THREADS, exec);
}
 
Example #8
Source File: BasicUpdateTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private <T> void verifyFactsWithQuery(final Class<T> expectedClassOfFacts, final String queryToGetFacts, final T... factsToVerify) {
    final QueryResults results = ksession.getQueryResults(queryToGetFacts);
    assertThat(results).isNotEmpty();
    final QueryResultsRow resultsRow = results.iterator().next();

    assertThat(resultsRow.get("$" + queryToGetFacts)).isInstanceOf(List.class);
    final List<Object> objects = (List<Object>) resultsRow.get("$" + queryToGetFacts);
    assertThat(objects).hasSize(factsToVerify.length);
    assertThat(objects).hasOnlyElementsOfType(expectedClassOfFacts);
    assertThat(objects).containsAll(Arrays.asList(factsToVerify));
}
 
Example #9
Source File: BasicUpdateTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void verifyWithQueryNoPersonsPresentInFacts() {
    QueryResults results = ksession.getQueryResults("persons");
    assertThat(results).isNotEmpty();

    results = ksession.getQueryResults("persons");
    assertThat(results).isNotEmpty();
    final QueryResultsRow resultsRow = results.iterator().next();
    assertThat(resultsRow.get("$persons")).isInstanceOf(List.class);
    final List<Object> persons = (List<Object>) resultsRow.get("$persons");
    assertThat(persons).isEmpty();
}
 
Example #10
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void runQueryListenerTest( QueryListenerOption option ) throws IOException, ClassNotFoundException {
    String str = "";
    str += "package org.drools.compiler.integrationtests\n";
    str += "import " + Cheese.class.getCanonicalName() + " \n";
    str += "query cheeses(String $type) \n";
    str += "    $cheese : Cheese(type == $type) \n";
    str += "end\n";

    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBaseFromString(str));
    KieSession ksession = createKieSession( kbase, option );

    // insert some data into the session
    for ( int i = 0; i < 10000; i++ ) {
        ksession.insert( new Cheese( i % 2 == 0 ? "stilton" : "brie" ) );
    }

    // query the session
    List<Cheese> cheeses;
    for ( int i = 0; i < 100; i++ ) {
        org.kie.api.runtime.rule.QueryResults queryResults = ksession.getQueryResults( "cheeses",
                                                                                      new Object[]{"stilton"} );
        cheeses = new ArrayList<Cheese>();
        for ( QueryResultsRow row : queryResults ) {
            cheeses.add( (Cheese) row.get( "$cheese" ) );
        }

        assertEquals( 5000,
                      cheeses.size() );
    }
}
 
Example #11
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryWithOptionalOr() {
    // DROOLS-1386
    String str =
            "package org.test\n" +
            "import " + Question.class.getCanonicalName() + "\n" +
            "import " + QuestionVisible.class.getCanonicalName() + "\n" +
            "query QuestionsKnowledge\n" +
            "    $question: Question()\n" +
            "    $visible: QuestionVisible(question == $question) or not QuestionVisible(question == $question)\n" +
            "end\n";

    KieSession ksession = new KieHelper().addContent( str, ResourceType.DRL ).build().newKieSession();
    Question question = new Question();
    ksession.insert( question );
    QueryResults results = ksession.getQueryResults("QuestionsKnowledge");
    assertEquals( 1, results.size() );
    QueryResultsRow row = results.iterator().next();
    assertSame( question, row.get( "$question" ) );

    QuestionVisible questionVisible = new QuestionVisible( question );
    ksession.insert( questionVisible );
    results = ksession.getQueryResults("QuestionsKnowledge");
    assertEquals( 1, results.size() );
    row = results.iterator().next();
    assertSame( question, row.get( "$question" ) );
    assertSame( questionVisible, row.get( "$visible" ) );
}
 
Example #12
Source File: ShoppingCartServiceImpl.java    From drools-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void removeItem(String id, Item item) throws BusinessException {
    if (shoppingCarts.get(id) == null) {
        throw new BusinessException("The cart Id is not valid!");
    }
    FactHandle factHandle = shoppingCarts.get(id).getFactHandle(item);
    shoppingCarts.get(id).delete(factHandle);
    QueryResults results = shoppingCarts.get(id).getQueryResults("Get All Cat Items", item);
    String[] keys = results.getIdentifiers();
    for(QueryResultsRow row : results){
        shoppingCarts.get(id).delete(row.getFactHandle(keys[0]));
    }
    shoppingCarts.get(id).fireAllRules();
}
 
Example #13
Source File: DeliveryServiceImpl.java    From drools-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public Delivery getDelivery(String deliveryId) throws BusinessException {
    KieSession kieSession = onGoingDeliveries.get(deliveryId);
    QueryResults queryResults = kieSession.getQueryResults("getDelivery", new Object[]{});
    for (QueryResultsRow qrr : queryResults) {
        return (Delivery) qrr.get("$d");
    }
    return null;
}
 
Example #14
Source File: LibraryClient.java    From rhpam-7-openshift-image with Apache License 2.0 5 votes vote down vote up
Suggestion getSuggestion(String keyword) {
    SuggestionRequest suggestionRequest = new SuggestionRequest();
    suggestionRequest.setKeyword(keyword);
    suggestionRequest.setKeyword("Zombie");
    List<Command<?>> cmds = new ArrayList<Command<?>>();
    cmds.add(commands.newInsert(suggestionRequest));
    cmds.add(commands.newFireAllRules());
    cmds.add(commands.newQuery("suggestion", "get suggestion"));
    BatchExecutionCommand batch = commands.newBatchExecution(cmds, "LibraryRuleSession");
    ExecutionResults execResults;
    if (appcfg.getKieSession() != null) {
        execResults = appcfg.getKieSession().execute(batch);
    } else {
        ServiceResponse<ExecutionResults> serviceResponse = appcfg.getRuleServicesClient().executeCommandsWithResults("rhpam-kieserver-library", batch);
        //logger.info(String.valueOf(serviceResponse));
        execResults = serviceResponse.getResult();
    }
    QueryResults queryResults = (QueryResults) execResults.getValue("suggestion");
    if (queryResults != null) {
        for (QueryResultsRow queryResult : queryResults) {
            SuggestionResponse suggestionResponse = (SuggestionResponse) queryResult.get("suggestionResponse");
            if (suggestionResponse != null) {
                return suggestionResponse.getSuggestion();
            }
        }
    }
    return null;
}
 
Example #15
Source File: QueryResultsImpl.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public QueryResultsRow next() {
    return new QueryResultsRowImpl( this.iterator.next(),
                            QueryResultsImpl.this.workingMemory,
                            QueryResultsImpl.this );
}
 
Example #16
Source File: FlatQueryResults.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public QueryResultsRow next() {
    return new FlatQueryResultRow( handleIterator.next(),
                                   iterator.next() );
}
 
Example #17
Source File: FlatQueryResults.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public Iterator<QueryResultsRow> iterator() {
    return new QueryResultsIterator( idFactHandleMaps.iterator(),
                                     idResultMaps.iterator() );
}
 
Example #18
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testQueryAPIs() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "import " + Abducible.class.getName() + "; \n" +

            "" +

            "declare Foo " +
            "   @Abducible " +
            "   id : String " +
            "end " +

            "query foo( String $s ) " +
            "   @Abductive( target=Foo.class ) \n" +
            "end \n "+

            "query bar( String $s, Foo $foo ) " +
            "   $foo := Foo() " +
            "end \n "+

            "rule MoveAround " +
            "when " +
            "   $s : String() " +
            "   $f : foo( $s ; ) " +
            "   bar( $s, $f ; ) " +
            "then " +
            "   delete( $s ); " +
            "   System.out.println( 'Foo ' + $f ); " +
            "end " +

            "";

    /////////////////////////////////////

    KieSession session = getSessionFromString( droolsSource );

    session.insert( "faa" );
    session.fireAllRules();

    for ( Object o : session.getObjects() ) {
        System.out.println( ">>> " + o );
    }
    assertEquals( 1, session.getObjects().size() );

    Query q1 = session.getKieBase().getQuery( "org.drools.abductive.test", "foo" );
    Query q2 = session.getKieBase().getQuery( "org.drools.abductive.test", "bar" );

    assertNotNull( q1 );
    assertNotNull( q2 );

    QueryResults q10res = new FlatQueryResults((QueryResultsImpl) session.getQueryResults( "foo", "foo", null ));
    QueryResults q11res = new FlatQueryResults((QueryResultsImpl) session.getQueryResults( "foo", "foo", Variable.v ));
    QueryResults q20res = new FlatQueryResults((QueryResultsImpl) session.getQueryResults( "bar", "foo", Variable.v ));

    assertEquals( 1, q10res.size() );
    assertEquals( 1, q11res.size() );
    assertEquals( 1, q20res.size() );

    QueryResultsRow row10 = q10res.iterator().next();
    QueryResultsRow row11 = q11res.iterator().next();
    QueryResultsRow row20 = q20res.iterator().next();

    assertEquals( "foo", row10.get( "$s" ) );
    assertEquals( "foo", row11.get( "$s" ) );
    assertEquals( "foo", row20.get( "$s" ) );

    Object foo = row20.get( "$foo" );
    assertSame( foo, session.getObjects().iterator().next() );

    // the implicit return argument, the abduced/retrieved fact, is hidden
    assertNull( row11.get( "" ) );

}
 
Example #19
Source File: QueryResultsImpl.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public Iterator<QueryResultsRow> iterator() {
    return new QueryResultsIterator( results.iterator() );
}
 
Example #20
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private static QueryResults getQueryResults(KieSession session, String queryName, Object... arguments ) throws Exception {
    QueryResultsImpl results = (QueryResultsImpl) session.getQueryResults( queryName, arguments );

    FlatQueryResults flatResults = new FlatQueryResults(results);

    assertEquals(results.size(), flatResults.size(), "Query results size");
    assertEquals(results.getIdentifiers().length, flatResults.getIdentifiers().length, "Query results identifiers");
    Set<String> resultIds = new TreeSet<String>(Arrays.asList(results.getIdentifiers()));
    Set<String> flatIds = new TreeSet<String>(Arrays.asList(flatResults.getIdentifiers()));
    assertArrayEquals(resultIds.toArray(), flatIds.toArray(), "Flat query results identifiers");

    FlatQueryResults copyFlatResults = roundTrip(flatResults);
    String [] identifiers = results.getIdentifiers();
    Iterator<QueryResultsRow> copyFlatIter = copyFlatResults.iterator();
    for( int i = 0; i < results.size(); ++i ) {
        QueryResultsRow row = results.get(i);
        assertTrue(copyFlatIter.hasNext(),  "Round-tripped flat query results contain less rows than original query results");
        QueryResultsRow copyRow = copyFlatIter.next();
        for( String id : identifiers ) {
            Object obj = row.get(id);
            if( obj != null ) {
                Object copyObj = copyRow.get(id);
                assertTrue(obj != null && obj.equals(copyObj), "Flat query result [" + i + "] does not contain result: '" + id + "': " + obj + "/" + copyObj);
            }
            FactHandle fh = row.getFactHandle(id);
            FactHandle copyFh = copyRow.getFactHandle(id);
            if( fh != null ) {
                assertNotNull(copyFh, "Flat query result [" + i + "] does not contain facthandle: '" + ((InternalFactHandle) fh).getId() + "'");
                String fhStr = fh.toExternalForm();
                fhStr = fhStr.substring(0, fhStr.lastIndexOf(":"));
                String copyFhStr = copyFh.toExternalForm();
                copyFhStr = copyFhStr.substring(0, copyFhStr.lastIndexOf(":"));
                assertEquals(fhStr, copyFhStr, "Unequal fact handles for fact handle '" + ((InternalFactHandle) fh).getId() + "':");
            }
        }
    }

    // check identifiers
    Set<String> copyFlatIds = new TreeSet<String>(Arrays.asList(copyFlatResults.getIdentifiers()));
    assertArrayEquals(flatIds.toArray(), copyFlatIds.toArray(), "Flat query results identifiers");
    return copyFlatResults;
}
 
Example #21
Source File: DroolsStatelessSession.java    From Decision with Apache License 2.0 3 votes vote down vote up
private void addResults(List r, ExecutionResults er, String name){

        Iterator<QueryResultsRow> rows = ((QueryResults) er.getValue(name)).iterator();
        while (rows.hasNext()) {
            QueryResultsRow row = rows.next();
            r.add( row.get(name));
        }


    }
 
Example #22
Source File: DroolsStatefulSession.java    From Decision with Apache License 2.0 3 votes vote down vote up
private void addResults(List r, String nameQuery, String nameResult){

        Iterator<QueryResultsRow> rows = session.getQueryResults(nameQuery).iterator();
        while (rows.hasNext()) {
            QueryResultsRow row = rows.next();
            r.add( row.get(nameResult));
        }


    }