Java Code Examples for org.kie.internal.io.ResourceFactory#newByteArrayResource()

The following examples show how to use org.kie.internal.io.ResourceFactory#newByteArrayResource() . 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: KnowledgeBuilderImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void addPackageFromScoreCard(final String pmmlString, final String fileName) throws DroolsParserException, IOException  {
    final File dumpDir = this.configuration.getDumpDir();
    if (dumpDir != null) {
        final String dirName = dumpDir.getCanonicalPath().endsWith("/") ? dumpDir.getCanonicalPath() : dumpDir.getCanonicalPath() + "/";
        final String outputPath = dirName + fileName;
        try (final FileOutputStream fos = new FileOutputStream(outputPath)) {
            fos.write(pmmlString.getBytes());
        }
    }
    final Resource res = ResourceFactory.newByteArrayResource(pmmlString.getBytes());

    try {
        ResourceWithConfiguration resCon = new ResourceWithConfigurationImpl(res, null, null, null);
        addPackageForExternalType(ResourceType.PMML, Collections.singletonList(resCon));
    } catch (Exception e) {
        throw new DroolsParserException(e);
    }
}
 
Example 2
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
/**
 * The same resource (containing a type declaration) is added twice in the
 * kbuilder.
 */
@Test
public void testDuplicatedTypeDeclarationWith2FieldsInSameResource() {
    //same package, different resources
    String str1 = "";
    str1 += "package org.drools.compiler \n" +
    		"declare org.drools.ClassA \n" +
    		"    name : String \n" +
    		"    lastName : String \n" +
    		"end \n";

    Resource resource = ResourceFactory.newByteArrayResource( str1.getBytes());

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add( resource, ResourceType.DRL );

    kbuilder.add( resource, ResourceType.DRL );

    if ( kbuilder.hasErrors() ) {
       fail( kbuilder.getErrors().toString() );
    }

}
 
Example 3
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessFactory() throws Exception {
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .actionNode(2)
                .name("Action")
                .action("java",
                        "System.out.println(\"Action\");")
                .done()
            .endNode(3)
                .name("End")
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3);
    RuleFlowProcess process = factory.validate().getProcess();
    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    ksession.startProcess("org.jbpm.process");
    ksession.dispose();
}
 
Example 4
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(10)
public void testActionNodeIsDroolsAction() throws Exception {
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            .name("ActionNodeActionProcess")
            .version("1")
            .startNode(1)
                .name("Start")
                .done()
            .endNode(3)
                .name("End")
                .done()
            .actionNode(2)
                .name("printTextActionNode")
                .action("java",
                        "System.out.println(\"test print\");",
                        true)
                .done()
            .connection(1, 2)
            .connection(2, 3);
    RuleFlowProcess process = factory.validate().getProcess();

    assertNotNull(process);

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2");
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    ProcessInstance pi = ksession.startProcess("org.jbpm.process");

    assertNotNull(pi);

    assertEquals(ProcessInstance.STATE_COMPLETED,
                 pi.getState());

    ksession.dispose();
}
 
Example 5
Source File: RulesDeployer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void deploy(EngineDeployment deployment, Map<String, Object> deploymentSettings) {
    LOGGER.debug("Processing rules deployment {}", deployment.getName());

    KnowledgeBuilder knowledgeBuilder = null;

    DeploymentManager deploymentManager = CommandContextUtil.getProcessEngineConfiguration().getDeploymentManager();

    Map<String, EngineResource> resources = deployment.getResources();
    for (String resourceName : resources.keySet()) {
        if (resourceName.endsWith(".drl")) { // is only parsing .drls sufficient? what about other rule dsl's? (@see ResourceType)
            LOGGER.info("Processing rules resource {}", resourceName);
            if (knowledgeBuilder == null) {
                knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
            }
            EngineResource resourceEntity = resources.get(resourceName);
            byte[] resourceBytes = resourceEntity.getBytes();
            Resource droolsResource = ResourceFactory.newByteArrayResource(resourceBytes);
            knowledgeBuilder.add(droolsResource, ResourceType.DRL);
        }
    }

    if (knowledgeBuilder != null) {
        KieBase kieBase = knowledgeBuilder.newKieBase();
        deploymentManager.getKnowledgeBaseCache().add(deployment.getId(), kieBase);
    }
}
 
Example 6
Source File: RulesDeployer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void deploy(DeploymentEntity deployment, Map<String, Object> deploymentSettings) {
    LOGGER.debug("Processing deployment {}", deployment.getName());

    KnowledgeBuilder knowledgeBuilder = null;

    DeploymentManager deploymentManager = Context
            .getProcessEngineConfiguration()
            .getDeploymentManager();

    Map<String, ResourceEntity> resources = deployment.getResources();
    for (String resourceName : resources.keySet()) {
        LOGGER.info("Processing resource {}", resourceName);
        if (resourceName.endsWith(".drl")) { // is only parsing .drls sufficient? what about other rule dsl's? (@see ResourceType)
            if (knowledgeBuilder == null) {
                knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
            }
            ResourceEntity resourceEntity = resources.get(resourceName);
            byte[] resourceBytes = resourceEntity.getBytes();
            Resource droolsResource = ResourceFactory.newByteArrayResource(resourceBytes);
            knowledgeBuilder.add(droolsResource, ResourceType.DRL);
        }
    }

    if (knowledgeBuilder != null) {
        KieBase knowledgeBase = knowledgeBuilder.newKieBase();
        deploymentManager.getKnowledgeBaseCache().add(deployment.getId(), knowledgeBase);
    }
}
 
Example 7
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Disabled
    @Test
    public void testResourceMapping() throws Exception {
        ServiceRegistryImpl serviceRegistry = (ServiceRegistryImpl) ServiceRegistry.getInstance();
        serviceRegistry.reset();
/*
        ServiceDiscoveryImpl.getInstance().addService(PMMLCompiler.class.getCanonicalName(),
                                                      new PMMLCompiler() {
                                                          public String compile(InputStream stream, ClassLoader cl) {
                                                              return "rule R2 when then end";
                                                          }

                                                          @Override
                                                          public List<KnowledgeBuilderResult> getResults() {
                                                              return Collections.emptyList();
                                                          }

                                                          @Override
                                                          public void clearResults() {
                                                              //To change body of implemented methods use File | Settings | File Templates.
                                                          }

                                                          public Resource[] transform( Resource input, ClassLoader classLoader ) {
                                                              return new Resource[ 0 ];
                                                          }
                                                          
                                                          public String getCompilerVersion() {
                                                        	  return "KnowledgeBuilderTest";
                                                          }

														@Override
														public List<PMMLResource> precompile(InputStream stream,
																ClassLoader classLoader, KieBaseModel rootModel) {
															return Collections.emptyList();
														}

														@Override
														public List<PMMLResource> precompile(String fileName,
																ClassLoader classLoader, KieBaseModel rootModel) {
															return Collections.emptyList();
														}

														@Override
														public Map<String, String> getJavaClasses(InputStream stream) {
															return Collections.emptyMap();
														}

														@Override
														public Map<String, String> getJavaClasses(String fileName) {
															return Collections.emptyMap();
														}
                                                      } );
*/
        serviceRegistry.reload();

        String rule = "package org.drools.compiler.test\n" +
                "rule R1 when\n" +
                " \n" +
                "then\n" +
                "end\n";

        Resource res1 = ResourceFactory.newByteArrayResource( rule.getBytes() );
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( res1, ResourceType.DRL );
        assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

        KiePackage kp1 = kbuilder.getKnowledgePackages().iterator().next();
        assertEquals( 1, kp1.getRules().size() );
        Rule r = kp1.getRules().iterator().next();
        assertEquals( res1, ((RuleImpl) r).getResource() );

        String pmml = "<PMML version=\"4.0\"><Header/></PMML>";

        Resource res2 = ResourceFactory.newByteArrayResource( pmml.getBytes() );
        KnowledgeBuilder kbuilder2 = KnowledgeBuilderFactory.newKnowledgeBuilder();
        
        kbuilder2.add( res2, ResourceType.PMML );
        assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

        KiePackage kp2 = kbuilder2.getKnowledgePackages().iterator().next();
        assertEquals( 1, kp2.getRules().size() );
        Rule r2 = kp2.getRules().iterator().next();
        assertEquals( res2, ((RuleImpl) r2).getResource() );

    }
 
Example 8
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testCompositeNode() throws Exception {
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .compositeContextNode(2)
                .name("SubProcess")
                .startNode(1)
                    .name("SubProcess Start")
                    .done()
                .actionNode(2)
                    .name("SubProcess Action")
                    .action("java",
                            "System.out.println(\"SubProcess Action\");")
                    .done()
                .endNode(3)
                    .name("SubProcess End")
                    .terminate(true)
                    .done()
                .connection(1, 2)
                .connection(2, 3)
                .done()
            .endNode(3)
                .name("End")
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3);
    RuleFlowProcess process = factory.validate().getProcess();

    assertEquals("SubProcess",
                 process.getNode(2).getName());

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    ProcessInstance pi = ksession.startProcess("org.jbpm.process");

    assertEquals(ProcessInstance.STATE_COMPLETED,
                 pi.getState());

    ksession.dispose();
}
 
Example 9
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Timeout(10)
public void testBoundaryTimerTimeCycle() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("BoundaryTimerEvent",
                                                                                                        1);
    String timeCycle = "1s###5s";
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .humanTaskNode(2)
                .name("Task")
                .actorId("john")
                .taskName("MyTask")
                .done()
            .endNode(3)
                .name("End1")
                .terminate(false)
                .done()
            .boundaryEventNode(4)
                .name("BoundaryTimerEvent")
                .attachedTo(2)
                .metaData(TIME_CYCLE, timeCycle)
                .metaData(CANCEL_ACTIVITY, false)
                .eventType(EVENT_TYPE_TIMER, timeCycle)
                .done()
            .endNode(5)
                .name("End2")
                .terminate(false)
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3)
            .connection(4, 5);
    RuleFlowProcess process = factory.validate().getProcess();

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler testHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task",
                                                          testHandler);
    ksession.addEventListener(countDownListener);

    ProcessInstance pi = ksession.startProcess("org.jbpm.process");
    assertProcessInstanceActive(pi);

    countDownListener.waitTillCompleted(); // wait for boundary timer firing

    assertNodeTriggered(pi.getId(),
                        "End2");
    assertProcessInstanceActive(pi); // still active because CancelActivity = false

    ksession.getWorkItemManager().completeWorkItem(testHandler.getWorkItem().getId(),
                                                   null);
    assertProcessInstanceCompleted(pi);

    ksession.dispose();
}
 
Example 10
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Timeout(10)
public void testBoundaryTimerTimeDuration() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("BoundaryTimerEvent",
                                                                                                        1);
    String timeDuration = "1s";
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .humanTaskNode(2)
                .name("Task")
                .actorId("john")
                .taskName("MyTask")
                .done()
            .endNode(3)
                .name("End1")
                .terminate(false)
                .done()
            .boundaryEventNode(4)
                .name("BoundaryTimerEvent")
                .attachedTo(2)
                .metaData(TIME_DURATION, timeDuration)
                .metaData(CANCEL_ACTIVITY, false)
                .eventType(EVENT_TYPE_TIMER, timeDuration)
                .done()
            .endNode(5)
                .name("End2")
                .terminate(false)
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3)
            .connection(4, 5);
    RuleFlowProcess process = factory.validate().getProcess();

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler testHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task",
                                                          testHandler);
    ksession.addEventListener(countDownListener);

    ProcessInstance pi = ksession.startProcess("org.jbpm.process");
    assertProcessInstanceActive(pi);

    countDownListener.waitTillCompleted(); // wait for boundary timer firing

    assertNodeTriggered(pi.getId(),
                        "End2");
    assertProcessInstanceActive(pi); // still active because CancelActivity = false

    ksession.getWorkItemManager().completeWorkItem(testHandler.getWorkItem().getId(),
                                                   null);
    assertProcessInstanceCompleted(pi);

    ksession.dispose();
}