protected KnowledgeBase readKnowledgeBase() { if (knowledgeBasesCache.containsKey(task.getId())) { return knowledgeBasesCache.get(task.getId()).getKnowledgeBase(); } // Creating agent with default KnowledgeAgentConfiguration for scanning files and directories KnowledgeAgent kAgent = KnowledgeAgentFactory.newKnowledgeAgent("Knowledge agent for task#" + task.getId()); // Adding resources for observing by KnowledgeAgent and creating KnowledgeBase. // Current version of api (5.0.1) does not implement adding resources from KnowledgeBase, // that was mentioned in api documentation (may be bug in source code). // So, we use other aproach for configuring KnowledgeAgent // Now agent interface allowes defining resources and directories for observing // only through ChangeSet from Resource (usually xml config file) // We create needed configuration dynamically as string // from task parameters information kAgent.applyChangeSet( new ByteArrayResource(createChangeSetStringFromTaskParameters().getBytes())); // Cache agent for further usage without recreation knowledgeBasesCache.put(task.getId(), kAgent); // Start scanning services for automatical updates of cached agents startRulesScannerIfNeeded(); return kAgent.getKnowledgeBase(); }
/** * Reading rules from Guvnor * * @return KnowledgeBase - the Guvnor knowledge Base */ private static KnowledgeBase readRemoteKnowledgeBase() { KnowledgeAgentConfiguration kaconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); kaconf.setProperty("drools.agent.scanDirectories", "false"); KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("test agent", kaconf); kagent.applyChangeSet(ResourceFactory.newClassPathResource("guvnor.xml")); return kagent.getKnowledgeBase(); }
public void testDroolsGeneration(int i) throws Exception { String filename = (i % 2 == 0) ? "/drools/stress1.drl" : "/drools/stress2.drl"; InputStreamReader reader = new InputStreamReader(DroolsKnowledgeBaseTest.class.getResourceAsStream(filename)); KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); aconf.setProperty("drools.agent.newInstance", "false"); aconf.setProperty("drools.agent.monitorChangeSetEvents", "false"); aconf.setProperty("drools.agent.scanResources", "false"); KnowledgeBuilder builder = compileRules(reader); KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("Success Correspondence Agent", aconf); KnowledgeBase kbase = kagent.getKnowledgeBase(); kbase.addKnowledgePackages(builder.getKnowledgePackages()); // kagent.monitorResourceChangeEvents(false); Rule rule1 = kbase.getRule("com.rosettastone.succor", "Equal rule 1"); Rule rule5 = kbase.getRule("com.rosettastone.succor", "Equal rule 5"); Rule rule6 = kbase.getRule("com.rosettastone.succor", "Equal rule 6"); StatelessKnowledgeSession session = kbase.newStatelessKnowledgeSession(); if (i % 2 == 0) { Assert.assertNotNull(rule1); Assert.assertNotNull(rule5); Assert.assertNull(rule6); testRulesFirst(session); } else { Assert.assertNull(rule1); Assert.assertNotNull(rule5); Assert.assertNotNull(rule6); testRulesSecond(session); } }
@Override public StatefulKnowledgeSession newStatefulKnowledgeSession( final KnowledgeSessionConfiguration conf, final Environment env) { StatefulKnowledgeSession returnValue = null; if (this.cm == null) { final KnowledgeAgent ka = this.getKnowledgeAgent(); assert ka != null; final KnowledgeBase kb = ka.getKnowledgeBase(); if (kb != null) { throw new IllegalStateException("KnowledgeAgent.getKnowledgeBase() == null"); } returnValue = kb.newStatefulKnowledgeSession(conf, env); } else { if (this.creator == null) { throw new IllegalStateException("this.creator == null"); } try { returnValue = (StatefulKnowledgeSession) this.cm.allocateConnection( this.creator, new StatefulKnowledgeSessionConfiguration(conf, env)); } catch (final ResourceException kaboom) { throw new RuntimeDroolsException(kaboom); } if (returnValue instanceof AbstractKnowledgeSessionUserConnection && cm instanceof LazyAssociatableConnectionManager) { ((AbstractKnowledgeSessionUserConnection) returnValue) .setLazyAssociatableConnectionManager((LazyAssociatableConnectionManager) cm); } } return returnValue; }
protected void addResource(StatefulKnowledgeSession kSession, Resource res) { KnowledgeBase kbase = kSession.getKnowledgeBase(); ChangeSetImpl cs = new ChangeSetImpl(); cs.setResourcesAdded(Arrays.asList(res)); KnowledgeAgentConfiguration kaConfig = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); kaConfig.setProperty("drools.agent.newInstance", "false"); KnowledgeAgent kAgent = KnowledgeAgentFactory.newKnowledgeAgent(" adder ", kbase, kaConfig); kAgent.applyChangeSet(cs); }
/** * Check if all fields are initialized properly. * * <p>In this class, this method will check if the servicePeriodSplitDates contains null. * * @throws OPMConfigurationException if any needed field is not initialized properly. * @since 1.1 OPM - Rules Engine - Scenarios Conversion 2 - Deduction Update Assembly */ @Override @PostConstruct public void checkConfiguration() { super.checkConfiguration(); if (this.entityManager == null) { throw new OPMConfigurationException("entityManager cannot be null."); } if (servicePeriodSplitDates != null) { for (Date date : servicePeriodSplitDates) { if (date == null) { throw new OPMConfigurationException( "Items in servicePeriodSplitDates list cannot be null."); } } } if (this.deductionTableTemplate == null) { throw new OPMConfigurationException("deductionTableTemplate cannot be null."); } try { // Generate deduction table this.generateDeductionTable(); // Initialize knowledge agent KnowledgeAgentConfiguration config = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); // We have to set the newInstance property to false so that the knowledge base changes can be // reflected config.setProperty("drools.agent.newInstance", "false"); KnowledgeAgent knowledgeAgent = KnowledgeAgentFactory.newKnowledgeAgent("deductionKnowledgeAgent", config); // Substitute the classpath resource location with the file system resource location String changeSet = ServiceHelper.inputStreamToString( ResourceFactory.newClassPathResource("deduction-change-set.xml").getInputStream()); changeSet = changeSet.replace( "classpath:rules/deduction_table.xls", "file:" + this.deductionTableTemplate.getDecisionTableFile()); knowledgeAgent.applyChangeSet( ResourceFactory.newByteArrayResource(changeSet.getBytes("utf-8"))); this.setKnowledgeAgent(knowledgeAgent); } catch (IOException e) { throw new OPMConfigurationException("Failed to initialize KnowledgeAgent."); } }
private KnowledgeBase getKnowledgeBase() { if (kagent == null) { kagent = KnowledgeAgentSingleton.getInstance().getKagent(); } // KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); // kbuilder.add( ResourceFactory.newClassPathResource("xpath-rules.drl"), ResourceType.DRL); // if ( kbuilder.hasErrors() ) { // throw new ActionLifecycleException("Error building rules: // "+kbuilder.getErrors().toString()); // } // return kagent.getKnowledgeBase(); }
/** {@inheritDoc} */ @Override public void destroy() { _kbase = null; _taskHandlers.clear(); _taskHandlerModels.clear(); _actionModels.clear(); _messageContentInName = null; _messageContentOutName = null; _processId = null; if (_kagent != null) { try { _kagent.dispose(); } finally { _kagent = null; } } }
/** {@inheritDoc} */ @Override public void init(QName qname, BPMComponentImplementationModel model) { _processId = model.getProcessId(); _messageContentInName = model.getMessageContentInName(); if (_messageContentInName == null) { _messageContentInName = MESSAGE_CONTENT_IN; } _messageContentOutName = model.getMessageContentOutName(); if (_messageContentOutName == null) { _messageContentOutName = MESSAGE_CONTENT_OUT; } ComponentModel cm = model.getComponent(); _targetNamespace = cm != null ? cm.getTargetNamespace() : null; _taskHandlerModels.addAll(model.getTaskHandlers()); ClassLoader loader = Classes.getClassLoader(getClass()); ResourceType.install(loader); ComponentImplementationConfig cic = new ComponentImplementationConfig(model, loader); Map<String, Object> env = new HashMap<String, Object>(); // env.put(EnvironmentName.ENTITY_MANAGER_FACTORY, // Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa")); // env.put(EnvironmentName.TRANSACTION_MANAGER, // AS7TransactionManagerLookup.getTransactionManager()); cic.setEnvironmentOverrides(env); Properties props = new Properties(); // props.setProperty("drools.processInstanceManagerFactory", // JPAProcessInstanceManagerFactory.class.getName()); // props.setProperty("drools.processSignalManagerFactory", // JPASignalManagerFactory.class.getName()); cic.setPropertiesOverrides(props); Resource procDef = model.getProcessDefinition(); if (procDef.getType() == null) { procDef = new SimpleResource(procDef.getLocation(), "BPMN2"); } if (model.isAgent()) { _kagent = Agents.newAgent(cic, procDef); _kbase = _kagent.getKnowledgeBase(); } else { _kbase = Bases.newBase(cic, procDef); } _ksessionConfig = Configs.getSessionConfiguration(cic); _environment = Environments.getEnvironment(cic); _audit = model.getAudit(); for (ProcessActionModel pam : model.getProcessActions()) { _actionModels.put(pam.getName(), pam); } }
private final KnowledgeBase getKnowledgeBase() { final KnowledgeAgent ka = this.getKnowledgeAgent(); assert ka != null; return ka.getKnowledgeBase(); }
public DiagramInfo getDiagramInfo(String processId) { if (kbase == null) { GuvnorConnectionUtils guvnorUtils = new GuvnorConnectionUtils(); if (guvnorUtils.guvnorExists()) { try { KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("Guvnor default"); kagent.applyChangeSet(ResourceFactory.newReaderResource(guvnorUtils.createChangeSet())); kagent.monitorResourceChangeEvents(false); kbase = kagent.getKnowledgeBase(); } catch (Throwable t) { logger.error("Could not build kbase from Guvnor assets: " + t.getMessage()); } } else { logger.warn("Could not connect to Guvnor."); } if (kbase == null) { kbase = KnowledgeBaseFactory.newKnowledgeBase(); } String directory = System.getProperty("jbpm.console.directory"); if (directory == null) { logger.error("jbpm.console.directory property not found"); } else { File file = new File(directory); if (!file.exists()) { throw new IllegalArgumentException("Could not find " + directory); } if (!file.isDirectory()) { throw new IllegalArgumentException(directory + " is not a directory"); } ProcessBuilderFactory.setProcessBuilderFactoryService( new ProcessBuilderFactoryServiceImpl()); ProcessMarshallerFactory.setProcessMarshallerFactoryService( new ProcessMarshallerFactoryServiceImpl()); ProcessRuntimeFactory.setProcessRuntimeFactoryService( new ProcessRuntimeFactoryServiceImpl()); BPMN2ProcessFactory.setBPMN2ProcessProvider(new BPMN2ProcessProviderImpl()); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); for (File subfile : file.listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".bpmn") || name.endsWith("bpmn2"); } })) { kbuilder.add(ResourceFactory.newFileResource(subfile), ResourceType.BPMN2); } kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); } } Process process = kbase.getProcess(processId); if (process == null) { return null; } DiagramInfo result = new DiagramInfo(); // TODO: diagram width and height? result.setWidth(932); result.setHeight(541); List<DiagramNodeInfo> nodeList = new ArrayList<DiagramNodeInfo>(); if (process instanceof WorkflowProcess) { addNodesInfo(nodeList, ((WorkflowProcess) process).getNodes(), "id="); } result.setNodeList(nodeList); return result; }