org.kie.api.io.Resource Java Examples
The following examples show how to use
org.kie.api.io.Resource.
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 |
public static byte[] createKJar(KieServices ks, ReleaseId releaseId, Resource pom, Resource... resources) { KieFileSystem kfs = ks.newKieFileSystem(); if (pom != null) { kfs.write(pom); } else { kfs.generateAndWritePomXML(releaseId); } for (int i = 0; i < resources.length; i++) { if (resources[i] != null) { kfs.write(resources[i]); } } ks.newKieBuilder(kfs).buildAll(); InternalKieModule kieModule = (InternalKieModule) ks.getRepository() .getKieModule(releaseId); byte[] jar = kieModule.getBytes(); return jar; }
Example #2
Source File: KieLoggersTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testKieConsoleLogger() throws Exception { String drl = "package org.drools.integrationtests\n" + "import org.drools.compiler.Message;\n" + "rule \"Hello World\"\n" + " when\n" + " m : Message( myMessage : message )\n" + " then\n" + "end"; // get the resource Resource dt = ResourceFactory.newByteArrayResource( drl.getBytes() ).setTargetPath( "org/drools/integrationtests/hello.drl" ); // create the builder KieSession ksession = getKieSession( dt ); KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newConsoleLogger( ksession ); ksession.insert( new Message("Hello World") ); int fired = ksession.fireAllRules(); assertEquals( 1, fired ); logger.close(); }
Example #3
Source File: KieLoggersTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testKieConsoleLoggerStateless() throws Exception { String drl = "package org.drools.integrationtests\n" + "import org.drools.compiler.Message;\n" + "rule \"Hello World\"\n" + " when\n" + " m : Message( myMessage : message )\n" + " then\n" + "end"; // get the resource Resource dt = ResourceFactory.newByteArrayResource( drl.getBytes() ).setTargetPath("org/drools/integrationtests/hello.drl"); // create the builder StatelessKieSession ksession = getStatelessKieSession(dt); KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newConsoleLogger( ksession ); AgendaEventListener ael = mock( AgendaEventListener.class ); ksession.addEventListener( ael ); ksession.execute( new Message("Hello World") ); verify( ael ).afterMatchFired( any(AfterMatchFiredEvent.class) ); logger.close(); }
Example #4
Source File: KieBuilderTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testValidXsdTargetNamespace() { final String drl1 = "package org.drools.compiler\n" + "rule R1 when\n" + " $m : Message()\n" + "then\n" + "end\n"; final String kmodule = "<kmodule xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" + " xmlns=\"http://www.drools.org/xsd/kmodule\">\n" + " <kbase name=\"kbase1\">\n" + " <ksession name=\"ksession1\" default=\"true\"/>\n" + " </kbase>\n" + "</kmodule>"; final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" ); final Resource r1 = ResourceFactory.newByteArrayResource( drl1.getBytes() ).setResourceType( ResourceType.DRL ).setSourcePath( "kbase1/drl1.drl" ); final KieModule km = createAndDeployJar( ks, kmodule, releaseId1, r1); ks.newKieContainer( km.getReleaseId() ); }
Example #5
Source File: MVELDialect.java From kogito-runtimes with Apache License 2.0 | 6 votes |
public void addFunction(FunctionDescr functionDescr, TypeResolver typeResolver, Resource resource) { // Serializable s1 = compile( (String) functionDescr.getText(), // null, // null, // null, // null, // null ); // // final ParserContext parserContext = getParserContext( analysis, // outerDeclarations, // otherInputVariables, // context ); // return MVELCompilationUnit.compile( text, pkgBuilder.getRootClassLoader(), parserContext, languageLevel ); // // Map<String, org.mvel2.ast.Function> map = org.mvel2.util.CompilerTools.extractAllDeclaredFunctions( (org.mvel2.compiler.CompiledExpression) s1 ); // MVELDialectRuntimeData data = (MVELDialectRuntimeData) this.packageRegistry.getDialectRuntimeRegistry().getDialectData( getId() ); // for ( org.mvel2.ast.Function function : map.values() ) { // data.addFunction( function ); // } }
Example #6
Source File: TypeDeclarationTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
/** * 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 #7
Source File: KieContainerTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testGetDefaultKieSessionModelEmptyKmodule() { KieServices kieServices = KieServices.Factory.get(); String drl = "package org.drools.test\n" + "rule R1 when\n" + " $m : Object()\n" + "then\n" + "end\n"; Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" ); resource.setTargetPath("org/drools/test/rules.drl"); String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" + "</kmodule>"; // Create an in-memory jar for version 1.0.0 ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-testGetDefaultKieSessionModelEmptyKmodule", "1.0.0"); createAndDeployJar(kieServices, kmodule, releaseId, resource); KieContainer kieContainer = kieServices.newKieContainer(releaseId); KieSessionModel sessionModel = kieContainer.getKieSessionModel(null); assertNotNull(sessionModel); }
Example #8
Source File: KieAPITestUtils.java From hacep with Apache License 2.0 | 6 votes |
private static void buildRelease(ReleaseId releaseId, Resource pomResource, Resource kmodule, String... resources) { if (releases.contains(releaseId)) { ks.getRepository().removeKieModule(releaseId); } KieServices kieServices = KieServices.Factory.get(); KieFileSystem kfs = kieServices.newKieFileSystem(); kfs.write("pom.xml", pomResource); kfs.write("src/main/resources/META-INF/kmodule.xml", kmodule); for (String res : resources) { Resource resource = new ClassPathResource(res); kfs.write("src/main/resources/" + res, resource); } hasErrors(kieServices.newKieBuilder(kfs).buildAll().getResults()); releases.add(releaseId); }
Example #9
Source File: KieLoggersTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private StatelessKieSession getStatelessKieSession(Resource dt) { KieServices ks = populateKieFileSystem( dt ); // get the session StatelessKieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newStatelessKieSession(); return ksession; }
Example #10
Source File: ProcessFactoryTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@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 #11
Source File: DecisionTableConfigurationHandler.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public DecisionTableConfigurationHandler() { if ( (this.validParents == null) && (this.validPeers == null) ) { this.validParents = new HashSet( 1 ); this.validParents.add( Resource.class ); this.validPeers = new HashSet( 1 ); this.validPeers.add( null ); this.allowNesting = false; } }
Example #12
Source File: DecisionCodegen.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private static List<DMNResource> parseDecisions(Path path, List<Resource> resources) throws IOException { DMNRuntime dmnRuntime = DMNRuntimeBuilder.fromDefaults() .setRootClassLoader(null) .buildConfiguration() .fromResources(resources) .getOrElseThrow(e -> new RuntimeException("Error compiling DMN model(s)", e)); return dmnRuntime.getModels().stream().map( model -> new DMNResource( model, path )).collect( toList() ); }
Example #13
Source File: ProcessCodegen.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private static Collection<? extends Process> parseProcessFile(Resource r) { try { XmlProcessReader xmlReader = new XmlProcessReader( BPMN_SEMANTIC_MODULES, Thread.currentThread().getContextClassLoader()); return xmlReader.read(r.getReader()); } catch (SAXException | IOException e) { throw new ProcessParsingException("Could not parse file " + r.getSourcePath(), e); } }
Example #14
Source File: BigRuleSetCodegenTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void test() { // This test is used to check that compilation of large knowledge bases doesn't cause an Out Of Memory // We are not running the test with such a big kbase by default to avoid slowing down CI // Collection<Resource> resources = generateResourcesToBeCompiled(17, 1000); Collection<Resource> resources = generateResourcesToBeCompiled(2, 3); IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofResources(resources); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.generate(); System.out.println( generatedFiles.size() ); }
Example #15
Source File: DrlParser.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public PackageDescr parse(final boolean isEditor, final Resource resource, final InputStream is) throws DroolsParserException, IOException { this.resource = resource; String encoding = resource instanceof InternalResource ? ((InternalResource) resource).getEncoding() : null; lexer = buildLexer(is, encoding, languageLevel); DRLParser parser = buildParser(lexer, languageLevel); return compile(isEditor, parser); }
Example #16
Source File: StandaloneBPMNProcessTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testXXEProcessVulnerability() throws Exception { Resource processResource = ResourceFactory.newClassPathResource("xxe-protection/BPMN2-XXE-Process.bpmn2"); File dtdFile = new File("src/test/resources/xxe-protection/external.dtd"); assertThat(dtdFile).exists(); String dtdContent = IoUtils.readFileAsString(dtdFile); dtdContent = dtdContent.replaceAll("@@PATH@@", dtdFile.getParentFile().getAbsolutePath()); IoUtils.write(dtdFile, dtdContent.getBytes("UTF-8")); byte[] data = IoUtils.readBytesFromInputStream(processResource.getInputStream()); String processAsString = new String(data, "UTF-8"); // replace place holders with actual paths File testFiles = new File("src/test/resources/xxe-protection"); assertThat(testFiles).exists(); String path = testFiles.getAbsolutePath(); processAsString = processAsString.replaceAll("@@PATH@@", path); Resource resource = ResourceFactory.newReaderResource(new StringReader(processAsString)); resource.setSourcePath(processResource.getSourcePath()); resource.setTargetPath(processResource.getTargetPath()); KieBase kbase = createKnowledgeBaseFromResources(resource); KieSession ksession = createKnowledgeSession(kbase); ProcessInstance processInstance = ksession.startProcess("async-examples.bp1"); String var1 = getProcessVarValue(processInstance, "testScript1"); String var2 = getProcessVarValue(processInstance, "testScript2"); assertThat(var1).isNull(); assertThat(var2).isNull(); assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED); }
Example #17
Source File: ConstraintConnectiveDescr.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Override public void setResource(Resource resource) { super.setResource(resource); for( BaseDescr descr : descrs ) { descr.setResource(resource); } }
Example #18
Source File: KieBuilderTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testJavaSourceFileAndDrlDeploy() { final String java = "package org.drools.compiler;\n" + "public class JavaSourceMessage { }\n"; final String drl = "package org.drools.compiler;\n" + "import org.drools.compiler.JavaSourceMessage;" + "rule R1 when\n" + " $m : JavaSourceMessage()\n" + "then\n" + "end\n"; final String kmodule = "<kmodule xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" + " xmlns=\"http://www.drools.org/xsd/kmodule\">\n" + " <kbase name=\"kbase1\">\n" + " <ksession name=\"ksession1\" default=\"true\"/>\n" + " </kbase>\n" + "</kmodule>"; final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" ); final Resource javaResource = ResourceFactory.newByteArrayResource( java.getBytes() ).setResourceType( ResourceType.JAVA ) .setSourcePath( "org/drools/compiler/JavaSourceMessage.java" ); final Resource drlResource = ResourceFactory.newByteArrayResource( drl.getBytes() ).setResourceType( ResourceType.DRL ) .setSourcePath( "kbase1/drl1.drl" ); final KieModule km = createAndDeployJar( ks, kmodule, releaseId1, javaResource, drlResource); final KieContainer kieContainer = ks.newKieContainer(km.getReleaseId()); try { final Class<?> messageClass = kieContainer.getClassLoader().loadClass("org.drools.compiler.JavaSourceMessage"); assertNotNull(messageClass); } catch (final ClassNotFoundException e) { throw new IllegalStateException("Loading the java class failed.", e); } }
Example #19
Source File: ProcessValidatorRegistry.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public ProcessValidator getValidator(Process process, Resource resource) { if (!additionalValidators.isEmpty()) { for (ProcessValidator validator : additionalValidators) { boolean accepted = validator.accept(process, resource); if (accepted) { return validator; } } } return defaultValidators.get(process.getType()); }
Example #20
Source File: ProcessFactoryTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@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 #21
Source File: ProcessCodegen.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private static Process parseWorkflowFile(Resource r, String parser) { try { ServerlessWorkflowParser workflowParser = new ServerlessWorkflowParser(parser); return workflowParser.parseWorkFlow(r.getReader()); } catch (IOException e) { throw new ProcessParsingException("Could not parse file " + r.getSourcePath(), e); } }
Example #22
Source File: KieFileSystemImpl.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public KieFileSystem write(Resource resource) { try { String target = resource.getTargetPath() != null ? resource.getTargetPath() : resource.getSourcePath(); if( target != null ) { String prefix = resource.getResourceType() == ResourceType.JAVA ? JAVA_ROOT : RESOURCES_ROOT; int prefixPos = target.indexOf( prefix ); String path = prefixPos >= 0 ? target.substring( prefixPos ) : prefix + target; if (resource.getResourceType() == ResourceType.XSD) { write( path, (( InternalResource ) resource).getBytes() ); } else { write( path, resource ); } ResourceConfiguration conf = resource.getConfiguration(); if( conf != null ) { Properties prop = ResourceTypeImpl.toProperties(conf); ByteArrayOutputStream buff = new ByteArrayOutputStream(); prop.store( buff, "Configuration properties for resource: " + target ); write( path + ".properties", buff.toByteArray() ); } return this; } else { throw new RuntimeException( "Resource does not have neither a source nor a target path. Impossible to add it to the bundle. Please set either the source or target name of the resource before adding it." + resource.toString()); } } catch (IOException e) { throw new UncheckedIOException("Unable to write Resource: " + resource.toString(), e); } }
Example #23
Source File: KnowledgeBuilderImpl.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private ChangeSet parseChangeSet(Resource resource) throws IOException, SAXException { XmlChangeSetReader reader = new XmlChangeSetReader(this.configuration.getSemanticModules()); if (resource instanceof ClassPathResource) { reader.setClassLoader(((ClassPathResource) resource).getClassLoader(), ((ClassPathResource) resource).getClazz()); } else { reader.setClassLoader(this.configuration.getClassLoader(), null); } try (Reader resourceReader = resource.getReader()) { return reader.read(resourceReader); } }
Example #24
Source File: KnowledgeBuilderImpl.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Deprecated void addPackageForExternalType(Resource resource, ResourceType type, ResourceConfiguration configuration) throws Exception { KieAssemblers assemblers = ServiceRegistry.getInstance().get(KieAssemblers.class); assemblers.addResource(this, resource, type, configuration); }
Example #25
Source File: KnowledgePackageImpl.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public List<RuleImpl> removeRulesGeneratedFromResource(Resource resource) { List<RuleImpl> rulesToBeRemoved = getRulesGeneratedFromResource(resource); for (RuleImpl rule : rulesToBeRemoved) { removeRule(rule); } return rulesToBeRemoved; }
Example #26
Source File: RulesDeployer.java From flowable-engine with Apache License 2.0 | 5 votes |
@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 #27
Source File: KieRepositoryImpl.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public KieModule addKieModule(Resource resource, Resource... dependencies) { log.debug("Adding KieModule from resource: " + resource); KieModule kModule = getKieModule(resource); if (dependencies != null && dependencies.length > 0) { for (Resource depRes : dependencies) { InternalKieModule depKModule = (InternalKieModule) getKieModule(depRes); ((InternalKieModule) kModule).addKieDependency(depKModule); log.debug("Adding KieModule dependency from resource: " + resource); } } addKieModule(kModule); return kModule; }
Example #28
Source File: KnowledgeBuilderImpl.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public void addPackageFromGuidedScoreCard(final Resource resource) throws DroolsParserException, IOException { this.resource = resource; final String pmmlString = GuidedScoreCardFactory.getPMMLStringFromInputStream(resource.getInputStream()); if (pmmlString != null) { addPackageFromScoreCard(pmmlString, "guided_scorecard_generated.pmml"); } this.resource = null; }
Example #29
Source File: ResourceHandler.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public ResourceHandler() { if ( (this.validParents == null) && (this.validPeers == null) ) { this.validParents = new HashSet(1); this.validParents.add( Collection.class ); this.validPeers = new HashSet(2); this.validPeers.add( null ); this.validPeers.add( Resource.class ); this.allowNesting = true; } }
Example #30
Source File: KieBuilderTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testDeclarativeChannelRegistration() { final String drl1 = "package org.drools.compiler\n" + "rule R1 when\n" + " $m : Message()\n" + "then\n" + "end\n"; final String kmodule = "<kmodule xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" + " xmlns=\"http://www.drools.org/xsd/kmodule\">\n" + " <kbase name=\"kbase1\">\n" + " <ksession name=\"ksession1\" default=\"true\">\n" + " <channels>\n" + " <channel name=\"testChannel\" type=\"org.drools.compiler.integrationtests.KieBuilderTest$MockChannel\" />\n" + " </channels>\n" + " </ksession>" + " </kbase>\n" + "</kmodule>"; final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" ); final Resource r1 = ResourceFactory.newByteArrayResource( drl1.getBytes() ).setResourceType( ResourceType.DRL ).setSourcePath( "kbase1/drl1.drl" ); final KieModule km = createAndDeployJar( ks, kmodule, releaseId1, r1); KieContainer kieContainer = ks.newKieContainer( km.getReleaseId()); KieSession kieSession = kieContainer.newKieSession(); assertEquals(1, kieSession.getChannels().size()); assertTrue(kieSession.getChannels().keySet().contains("testChannel")); }