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

The following examples show how to use org.kie.api.runtime.rule.QueryResults. 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: MoreBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 7 votes vote down vote up
@Test
public void testQuery() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("org/drools/compiler/integrationtests/simple_query_test.drl"), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    ksession = createKnowledgeSession(kbase);
    
    ksession.insert( new Cheese( "stinky", 5 ) );
    ksession.insert( new Cheese( "smelly", 7 ) );
    
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newQuery("numStinkyCheeses", "simple query"));
    Command<?> cmds = CommandFactory.newBatchExecution(commands);
    ExecutionResults result = (ExecutionResults) ksession.execute(cmds);
    assertNotNull(result, "Batch execution result is null!");

    Object queryResultsObject = result.getValue("numStinkyCheeses");
    assertTrue(queryResultsObject != null && queryResultsObject instanceof QueryResults, "Retrieved object is null or incorrect!");
    
    assertEquals( 1, ((QueryResults) queryResultsObject).size() );
}
 
Example #2
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 #3
Source File: Query3Test.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void doIt(Object o1,
                  Object o2,
                  String query,
                  int expected,
                  boolean doUpdate,
                  boolean doRetract) {
    KieSession knowledgeSession = knowledgeBase.newKieSession();
    try {
        knowledgeSession.insert( o1 );
        FactHandle handle2 = knowledgeSession.insert( o2 );
        if ( doUpdate ) {
            knowledgeSession.update( handle2,
                                     o2 );
        } else if ( doRetract ) {
            knowledgeSession.retract( handle2 );
            handle2 = knowledgeSession.insert( o2 );
        }
        QueryResults queryResults = knowledgeSession.getQueryResults( query );
        assertEquals( expected,
                      queryResults.size() );
    } finally {
        knowledgeSession.dispose();
    }
}
 
Example #4
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 #5
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 #6
Source File: OOPathQueriesTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryFromCode() {
    final String drl =
            "import org.drools.compiler.oopath.model.Thing;\n" +
                    "query isContainedIn( Thing $x, Thing $y )\n" +
                    "    $y := /$x/children\n" +
                    "or\n" +
                    "    ( $z := /$x/children and isContainedIn( $z, $y; ) )\n" +
                    "end\n";

    final Thing smartphone = new Thing("smartphone");
    final List<String> itemList = Arrays.asList(new String[] { "display", "keyboard", "processor" });
    itemList.stream().map(item -> new Thing(item)).forEach((thing) -> smartphone.addChild(thing));

    final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
            .build()
            .newKieSession();
    ksession.insert(smartphone);

    final QueryResults queryResults = ksession.getQueryResults("isContainedIn", new Object[] { smartphone, Variable.v });
    final List<String> resultList = StreamSupport.stream(queryResults.spliterator(), false)
            .map(row -> ((Thing) row.get("$y")).getName()).collect(Collectors.toList());
    assertThat(resultList).as("Query does not contain all items").containsAll(itemList);

    ksession.dispose();
}
 
Example #7
Source File: QueryCepFireUntilHaltTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void withNoResultTest() {
    secondEntryPoint.insert(new TestEvent("minusOne"));
    clock.advanceTime(5, TimeUnit.SECONDS);

    firstEntryPoint.insert(new TestEvent("zero"));
    secondEntryPoint.insert(new TestEvent("one"));
    clock.advanceTime(10, TimeUnit.SECONDS);

    secondEntryPoint.insert(new TestEvent("two"));
    // the following expires event "zero" and "one", causing the query to no longer match
    clock.advanceTime(10, TimeUnit.SECONDS); 

    secondEntryPoint.insert(new TestEvent("three"));
    QueryResults results = ksession.getQueryResults("ZeroToNineteenSeconds");
    
    assertEquals(0, results.size());
}
 
Example #8
Source File: QueryCepFireUntilHaltTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void withResultTest() {
    secondEntryPoint.insert(new TestEvent("minusOne"));
    clock.advanceTime(5, TimeUnit.SECONDS);

    firstEntryPoint.insert(new TestEvent("zero"));
    secondEntryPoint.insert(new TestEvent("one"));
    clock.advanceTime(10, TimeUnit.SECONDS);

    secondEntryPoint.insert(new TestEvent("two"));
    clock.advanceTime(5, TimeUnit.SECONDS);

    secondEntryPoint.insert(new TestEvent("three"));
    QueryResults results = ksession.getQueryResults("ZeroToNineteenSeconds");
    
    assertEquals(1, results.size());
}
 
Example #9
Source File: QueryCommand.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public QueryResults execute(Context context) {
    KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );

    if ( this.arguments == null || this.arguments.isEmpty() ) {
        this.arguments = Collections.emptyList();
    }

    for (int j = 0; j < arguments.size(); j++) {
        if (arguments.get(j) instanceof Variable) {
            arguments.set(j, Variable.v);
        }
    }

    QueryResults results = ksession.getQueryResults( name, this.arguments.toArray() );

    if ( this.outIdentifier != null ) {
        ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult( this.outIdentifier, new FlatQueryResults( (QueryResultsImpl) results) );
    }

    return results;
}
 
Example #10
Source File: QueryCepTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void withNoResultTest() {
    secondEntryPoint.insert(new TestEvent("minusOne"));
    clock.advanceTime(5, TimeUnit.SECONDS);

    firstEntryPoint.insert(new TestEvent("zero"));
    secondEntryPoint.insert(new TestEvent("one"));
    clock.advanceTime(10, TimeUnit.SECONDS);

    secondEntryPoint.insert(new TestEvent("two"));
    // the following expires event "zero" and "one", causing the query to no longer match
    clock.advanceTime(10, TimeUnit.SECONDS); 

    secondEntryPoint.insert(new TestEvent("three"));
    QueryResults results = ksession.getQueryResults("ZeroToNineteenSeconds");
    
    assertEquals(0, results.size());
}
 
Example #11
Source File: QueryCepTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void withResultTest() {
    secondEntryPoint.insert(new TestEvent("minusOne"));
    clock.advanceTime(5, TimeUnit.SECONDS);

    firstEntryPoint.insert(new TestEvent("zero"));
    secondEntryPoint.insert(new TestEvent("one"));
    clock.advanceTime(10, TimeUnit.SECONDS);

    secondEntryPoint.insert(new TestEvent("two"));
    clock.advanceTime(5, TimeUnit.SECONDS);

    secondEntryPoint.insert(new TestEvent("three"));
    QueryResults results = ksession.getQueryResults("ZeroToNineteenSeconds");
    
    assertEquals(1, results.size());
}
 
Example #12
Source File: DeleteTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteFactTwiceTest() {
    FactHandle george = ksession.insert(new Person("George", 19));
    QueryResults results = ksession.getQueryResults("countPerson");
    assertThat(results).isNotEmpty();
    assertThat(results.iterator().next().get("$personCount")).isEqualTo(1L);

    ksession.delete(george);
    results = ksession.getQueryResults("countPerson");
    assertThat(results).isNotEmpty();
    assertThat(results.iterator().next().get("$personCount")).isEqualTo(0L);

    ksession.delete(george);
    assertThat(results).isNotEmpty();
    assertThat(results.iterator().next().get("$personCount")).isEqualTo(0L);
}
 
Example #13
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 #14
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 #15
Source File: CommandBasedStatefulKnowledgeSession.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public QueryResults getQueryResults(String query,
                                    Object... arguments) {
    QueryCommand cmd = new QueryCommand( (String)null,
                                         query,
                                         arguments );
    return this.runner.execute( cmd );
}
 
Example #16
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 #17
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 #18
Source File: QueryInRHSCepTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void withResultOfSize0Test() {
	prepare1();
	clock.advanceTime(1, TimeUnit.SECONDS);
    ksession.insert(new SolicitFirePojo());
    int fired = ksession.fireAllRules();
    assertEquals(1, fired);
    assertEquals(1, myGlobal.size());
    assertEquals(0, ((QueryResults) myGlobal.get(0)).size());
}
 
Example #19
Source File: QueryInRHSCepTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void withResultOfSize1AnotherTest() {
	prepare1();
	clock.advanceTime(1, TimeUnit.SECONDS);
    ksession.insert(new SolicitFirePojo());
    ksession.insert(new QueryItemPojo());
    int fired = ksession.fireAllRules();
    assertEquals(1, fired);
    assertEquals(1, myGlobal.size());
    assertEquals(1, ((QueryResults) myGlobal.get(0)).size());
}
 
Example #20
Source File: QueryInRHSCepTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void withResultOfSize1Test() {
	prepare1();
	clock.advanceTime(1, TimeUnit.SECONDS);
    ksession.insert(new QueryItemPojo());
    ksession.insert(new SolicitFirePojo());
    int fired = ksession.fireAllRules();
    assertEquals(1, fired);
    assertEquals(1, myGlobal.size());
    assertEquals(1, ((QueryResults) myGlobal.get(0)).size());
}
 
Example #21
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 #22
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 #23
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 #24
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 #25
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testTwoQuerries() throws Exception {
    // @see JBRULES-410 More than one Query definition causes an incorrect
    // Rete network to be built.
    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_TwoQuerries.drl"));
    KieSession session = createKieSession( kbase );

    final Cheese stilton = new Cheese( "stinky",
                                       5 );
    session.insert( stilton );
    final Person per1 = new Person( "stinker",
                                    "smelly feet",
                                    70 );
    final Person per2 = new Person( "skunky",
                                    "smelly armpits",
                                    40 );

    session.insert( per1 );
    session.insert( per2 );

    QueryResults results = getQueryResults( session, "find stinky cheeses" );
    assertEquals( 1,
                  results.size() );

    results = getQueryResults( session, "find pensioners" );
    assertEquals( 1,
                  results.size() );
}
 
Example #26
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryWithParams() throws Exception {
    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_QueryWithParams.drl"));
    KieSession session = createKieSession( kbase );

    session.fireAllRules();

    String queryName = "assertedobjquery";
    String [] arguments = new String[]{"value1"};
    QueryResultsImpl resultsImpl = (QueryResultsImpl) session.getQueryResults( queryName, arguments );

    QueryResults results = getQueryResults( session, queryName, arguments );

    assertEquals( 1,
                  results.size() );
    InsertedObject value = new InsertedObject( "value1" );
    assertEquals( value,
                  ((InternalFactHandle) results.iterator().next().getFactHandle( "assertedobj" )).getObject()  );
    assertEquals( value,
                  results.iterator().next().get("assertedobj") );

    results = getQueryResults( session, "assertedobjquery", new String[]{"value3"}  );

    assertEquals( 0,
                  results.size() );

    results = getQueryResults( session, "assertedobjquery2", new String[]{null, "value2"}  );
    assertEquals( 1,
                  results.size() );
    assertEquals( new InsertedObject( "value2" ),
                  ((InternalFactHandle) results.iterator().next().getFactHandle( "assertedobj" )).getObject() );

    results = getQueryResults(session, "assertedobjquery2", new String[]{"value3", "value2"}  );

    assertEquals( 1,
                  results.size() );
    assertEquals( new InsertedObject( "value2" ),
                  ((InternalFactHandle) results.iterator().next().getFactHandle( "assertedobj" )).getObject()  );
}
 
Example #27
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery2() throws Exception {
    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_Query.drl"));
    KieSession session = createKieSession( kbase );

    session.fireAllRules();

    QueryResults results = getQueryResults(session, "assertedobjquery" );
    assertEquals( 1,
                  results.size() );
    assertEquals( new InsertedObject( "value1" ),
                  ((InternalFactHandle) results.iterator().next().getFactHandle( "assertedobj" )).getObject() );
}
 
Example #28
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 #29
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 #30
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();
}