refactoring and adding camel business proxy

This commit is contained in:
Nicolas Héron 2018-12-29 23:05:41 +01:00
commit a474dcf891
876 changed files with 1692 additions and 1038 deletions

View file

@ -0,0 +1,73 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime;
import com.google.common.base.Throwables;
import org.apache.commons.beanutils.BeanMap;
import org.chtijbug.drools.entity.DroolsFactObject;
import org.chtijbug.drools.entity.DroolsFactObjectAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Bertrand Gressier
* @since 27 déc. 2011
*/
public class DroolsFactObjectFactory {
private static Logger logger = LoggerFactory.getLogger(DroolsFactObjectFactory.class);
protected DroolsFactObjectFactory() {
}
public static DroolsFactObject createFactObject(Object o) {
return createFactObject(o, 0);
}
public static DroolsFactObject createFactObject(Object o, int version) {
logger.debug(">> createFactObject", o, version);
DroolsFactObject createFactObject = null;
try {
if (o != null) {
createFactObject = new DroolsFactObject(o, version);
createFactObject.setFullClassName(o.getClass().getCanonicalName());
createFactObject.setHashCode(o.hashCode());
BeanMap m = new BeanMap(o);
for (Object para : m.keySet()) {
if (!para.toString().equals("class")) {
if (m.get(para) != null) {
DroolsFactObjectAttribute attribute = new DroolsFactObjectAttribute(para.toString(), m.get(para).toString(), m.get(para).getClass().getSimpleName());
createFactObject.getListfactObjectAttributes().add(attribute);
} else {
DroolsFactObjectAttribute attribute = new DroolsFactObjectAttribute(para.toString(), "null", "null");
createFactObject.getListfactObjectAttributes().add(attribute);
}
}
}
}
return createFactObject;
} catch (Exception e) {
logger.error("Not possible to introspect {} for reason {}", o, e);
throw Throwables.propagate(e);
} finally {
logger.debug("<< createFactObject", createFactObject);
}
}
}

View file

@ -0,0 +1,116 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime;
import org.chtijbug.drools.runtime.impl.RuleBaseCommandSingleton;
import org.chtijbug.drools.runtime.impl.RuleBaseSingleton;
import org.chtijbug.drools.runtime.listener.HistoryListener;
import org.chtijbug.drools.runtime.resource.FileKnowledgeResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* @author nheron
*/
public abstract class RuleBaseBuilder {
/**
* Class Logger
*/
private static Logger logger = LoggerFactory.getLogger(RuleBaseBuilder.class);
public static RuleBasePackage createRemoteStandardRestBasePackage(String containerId, String url,String username,String password) throws DroolsChtijbugException {
logger.debug(">> createWorkbenchRuleBasePackage()");
RuleBaseCommandSingleton newRuleBasePackage = new RuleBaseCommandSingleton(RuleBaseSingleton.DEFAULT_RULE_THRESHOLD,containerId,url,username,password);
try {
newRuleBasePackage.connectKBase();
//_____ Returning the result
return newRuleBasePackage;
} finally {
logger.debug("<< createWorkbenchRuleBasePackage", newRuleBasePackage);
}
}
public static RuleBasePackage createWorkbenchRuleBasePackage(Long ruleBaseId, HistoryListener historyListener, String groupId, String artifactId, String version, String workbenchUrl, String username, String password) throws DroolsChtijbugException {
logger.debug(">> createWorkbenchRuleBasePackage()");
RuleBaseSingleton newRuleBasePackage = new RuleBaseSingleton(ruleBaseId, RuleBaseSingleton.DEFAULT_RULE_THRESHOLD, historyListener, groupId, artifactId, version);
try {
newRuleBasePackage.createKBase(workbenchUrl, username, password);
//_____ Returning the result
return newRuleBasePackage;
} finally {
logger.debug("<< createWorkbenchRuleBasePackage", newRuleBasePackage);
}
}
public static RuleBasePackage createRuleBasePackage(Long ruleBaseId, String modulePackage, String moduleName, String version, String... files) throws DroolsChtijbugException {
return RuleBaseBuilder.createRuleBasePackage(ruleBaseId, null, modulePackage, moduleName, version, files);
}
public static RuleBasePackage createRuleBasePackage(Long ruleBaseId, HistoryListener historyListener, String groupId, String artifactId, String version, String... files) throws DroolsChtijbugException {
logger.debug(">>createRuleBasePackage");
List<FileKnowledgeResource> fileKnowledgeResources = new ArrayList<>();
for (String s : files) {
if (s.contains("bpmn2")) {
FileKnowledgeResource fileKnowledgeResource = FileKnowledgeResource.createBPMN2ClassPathResource(s);
fileKnowledgeResources.add(fileKnowledgeResource);
} else {
FileKnowledgeResource fileKnowledgeResource = FileKnowledgeResource.createDRLClassPathResource(s);
fileKnowledgeResources.add(fileKnowledgeResource);
}
}
RuleBaseSingleton ruleBasePackage = new RuleBaseSingleton(ruleBaseId, RuleBaseSingleton.DEFAULT_RULE_THRESHOLD, historyListener, artifactId, groupId, version);
try {
ruleBasePackage.createKBase(fileKnowledgeResources);
//_____ Returning the result
return ruleBasePackage;
} finally {
logger.debug("<<createRuleBasePackage", ruleBasePackage);
}
}
public static RuleBasePackage createRuleBasePackage(Long ruleBaseId, HistoryListener historyListener, ClassLoader... classLoader) throws DroolsChtijbugException {
logger.debug(">>createRuleBasePackage");
RuleBaseSingleton ruleBasePackage = new RuleBaseSingleton(ruleBaseId, RuleBaseSingleton.DEFAULT_RULE_THRESHOLD, historyListener);
try {
ruleBasePackage.createKBase(classLoader);
//_____ Returning the result
return ruleBasePackage;
} finally {
logger.debug("<<createRuleBasePackage", ruleBasePackage);
}
}
public static RuleBasePackage createRuleBasePackage(String rulebaseName, HistoryListener historyListener, ClassLoader... classLoader) throws DroolsChtijbugException {
logger.debug(">>createRuleBasePackage");
RuleBaseSingleton ruleBasePackage = new RuleBaseSingleton(rulebaseName, RuleBaseSingleton.DEFAULT_RULE_THRESHOLD, historyListener);
try {
ruleBasePackage.createKBase(classLoader);
//_____ Returning the result
return ruleBasePackage;
} finally {
logger.debug("<<createRuleBasePackage", ruleBasePackage);
}
}
}

View file

@ -0,0 +1,42 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime;
import org.chtijbug.drools.runtime.listener.HistoryListener;
/**
* @author nheron
*/
public interface RuleBasePackage {
RuleBaseSession createRuleBaseSession() throws DroolsChtijbugException;
RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute) throws DroolsChtijbugException;
RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute, HistoryListener sessionHistoryListener) throws DroolsChtijbugException;
RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute, HistoryListener sessionHistoryListener, String sessionName) throws DroolsChtijbugException;
void loadKBase(String version) throws DroolsChtijbugException;
HistoryListener getHistoryListener();
Long getRuleBaseID();
void dispose();
}

View file

@ -0,0 +1,101 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime;
import org.chtijbug.drools.entity.DroolsFactObject;
import org.chtijbug.drools.entity.DroolsRuleObject;
import org.chtijbug.drools.entity.history.HistoryContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.ObjectFilter;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItemHandler;
import java.util.Collection;
import java.util.Map;
/**
* @author nheron
*/
public interface RuleBaseSession {
/**
* This method injects the newObject parameter into this session.
* No deep insertion(using relfection) is done
*
* @param newObject - object to insert into this session
*/
public void insertObject(Object newObject);
/**
* This method injects the newObject parameter into this session.
* No deep insertion(using relfection) is done
*
* @param newObject - object to insert into this session. all nested objects will be also inserted
* @throws org.chtijbug.drools.runtime.DroolsChtijbugException
*/
public void insertByReflection(Object newObject) throws DroolsChtijbugException;
/**
* This method helps for introducing a global object into the RuleBaseSession
*
* @param identifier - the key of the global variable to inject
* @param value - the value of the global variable to inject
*/
void setGlobal(String identifier, Object value);
void updateObject(Object updatedObject);
void retractObject(Object oldObject);
void fireAllRules() throws DroolsChtijbugException;
Object fireAllRulesAndStartProcess(Object inputObject, String processName) throws DroolsChtijbugException;
Object fireAllRulesAndStartProcessWithParam(Object inputObject, String processName) throws DroolsChtijbugException;
void startProcess(String processName);
void dispose();
HistoryContainer getHistoryContainer();
String getHistoryContainerXML();
Collection<DroolsFactObject> listLastVersionObjects();
String listLastVersionObjectsXML();
Collection<DroolsRuleObject> listRules();
int getNumberRulesExecuted();
Long getSessionId();
Long getRuleBaseID();
KieSession getKnowledgeSession();
Collection<? extends Object> getObjects(ObjectFilter objectFilter);
void completeWorkItem(long processId, Map<String, Object> vars);
void abortWorkItem(long processId);
void registerWorkItemHandler(String workItemName, WorkItemHandler workItemHandler);
ProcessInstance startProcess(String processName, Map<String, Object> vars);
}

View file

@ -0,0 +1,98 @@
package org.chtijbug.drools.runtime;
import org.chtijbug.drools.logging.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nheron on 11/06/15.
*/
public class SessionContext {
private SessionExecution sessionExecution;
private ProcessExecution processExecution;
private List<RuleflowGroup> ruleflowGroups = new ArrayList<>();
private RuleExecution ruleExecution;
private FireAllRulesExecution fireAllRulesExecution;
private Fact fact;
public SessionExecution getSessionExecution() {
return sessionExecution;
}
public void setSessionExecution(SessionExecution sessionExecution) {
this.sessionExecution = sessionExecution;
}
public ProcessExecution getProcessExecution() {
return processExecution;
}
public void setProcessExecution(ProcessExecution processExecution) {
this.processExecution = processExecution;
}
public List<RuleflowGroup> getRuleflowGroups() {
return ruleflowGroups;
}
public void setRuleflowGroups(List<RuleflowGroup> ruleflowGroups) {
this.ruleflowGroups = ruleflowGroups;
}
public RuleflowGroup findRuleFlowGroup(String name) {
RuleflowGroup result = null;
for (RuleflowGroup r : ruleflowGroups) {
if (r.getRuleflowGroup() != null && r.getRuleflowGroup().equals(name)) {
result = r;
}
}
return result;
}
public RuleExecution getRuleExecution() {
return ruleExecution;
}
public void setRuleExecution(RuleExecution ruleExecution) {
this.ruleExecution = ruleExecution;
}
public Fact getFact() {
return fact;
}
public void setFact(Fact fact) {
this.fact = fact;
}
public FireAllRulesExecution getFireAllRulesExecution() {
return fireAllRulesExecution;
}
public void setFireAllRulesExecution(FireAllRulesExecution fireAllRulesExecution) {
this.fireAllRulesExecution = fireAllRulesExecution;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("SessionContext{");
sb.append("sessionExecution=").append(sessionExecution);
sb.append(", processExecution=").append(processExecution);
sb.append(", ruleExecution=").append(ruleExecution);
sb.append(", fireAllRulesExecution=").append(fireAllRulesExecution);
sb.append(", fact=").append(fact);
sb.append('}');
return sb.toString();
}
}

View file

@ -0,0 +1,124 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime.impl;
import org.chtijbug.drools.entity.DroolsFactObject;
import org.chtijbug.drools.entity.history.fact.DeletedFactHistoryEvent;
import org.chtijbug.drools.entity.history.fact.FactHistoryEvent;
import org.chtijbug.drools.entity.history.fact.InsertedFactHistoryEvent;
import org.chtijbug.drools.entity.history.fact.UpdatedFactHistoryEvent;
import org.chtijbug.drools.runtime.DroolsFactObjectFactory;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.event.rule.impl.RuleRuntimeEventImpl;
import org.drools.core.spi.PropagationContext;
import org.kie.api.event.rule.ObjectDeletedEvent;
import org.kie.api.event.rule.ObjectInsertedEvent;
import org.kie.api.event.rule.ObjectUpdatedEvent;
import org.kie.api.event.rule.RuleRuntimeEventListener;
import org.kie.api.runtime.rule.FactHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FactHandlerListener implements RuleRuntimeEventListener {
private static Logger logger = LoggerFactory.getLogger(FactHandlerListener.class);
private final RuleBaseStatefulSession ruleBaseSession;
public FactHandlerListener(RuleBaseStatefulSession ruleBaseSession) {
this.ruleBaseSession = ruleBaseSession;
}
@Override
public void objectInserted(ObjectInsertedEvent event) {
logger.debug(">>objectInserted", event);
try {
//____ Updating reference into the facts map from knowledge Session
//((RuleTerminalNode)((RuleTerminalNodeLeftTuple)((org.drools.common.DefaultFactHandle)event.getFactHandle()).getFirstLeftTuple()).getSink()).getRule().getRuleFlowGroup()
FactHandle f = event.getFactHandle();
Object newObject = event.getObject();
DroolsFactObject ff = DroolsFactObjectFactory.createFactObject(newObject);
ruleBaseSession.setData(f, newObject, ff);
//____ Adding the Insert Event from the History Container
InsertedFactHistoryEvent insertFactHistoryEvent = new InsertedFactHistoryEvent(this.ruleBaseSession.nextEventId(), ff, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
if (insertFactHistoryEvent.getRuleName() == null && event instanceof RuleRuntimeEventImpl) {
PropagationContext propagationContext = ((RuleRuntimeEventImpl) event).getPropagationContext();
this.updateRuleDetailFromPropagationContext(propagationContext, insertFactHistoryEvent);
}
this.ruleBaseSession.addHistoryElement(insertFactHistoryEvent);
} finally
{
logger.debug("<<objectInserted");
}
}
@Override
public void objectUpdated(ObjectUpdatedEvent event) {
logger.debug(">>objectUpdated", event);
try {
//____ Updating FactHandle Object reference from the knwoledge session
FactHandle f = event.getFactHandle();
Object oldValue = event.getOldObject();
Object newValue = event.getObject();
DroolsFactObject factOldValue = this.ruleBaseSession.getLastFactObjectVersion(oldValue);
DroolsFactObject factNewValue = DroolsFactObjectFactory.createFactObject(newValue, factOldValue.getNextObjectVersion());
ruleBaseSession.setData(f, newValue, factNewValue);
//____ Adding the Update Event from the History Container
UpdatedFactHistoryEvent updatedFactHistoryEvent = new UpdatedFactHistoryEvent(this.ruleBaseSession.nextEventId(), factOldValue, factNewValue, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
if (updatedFactHistoryEvent.getRuleName() == null && event instanceof RuleRuntimeEventImpl) {
PropagationContext propagationContext = ((RuleRuntimeEventImpl) event).getPropagationContext();
this.updateRuleDetailFromPropagationContext(propagationContext, updatedFactHistoryEvent);
}
this.ruleBaseSession.addHistoryElement(updatedFactHistoryEvent);
} finally {
logger.debug("<<objectUpdated");
}
}
@Override
public void objectDeleted(ObjectDeletedEvent event) {
logger.debug(">>objectRetracted", event);
try {
//____ Removing FactHandle from the KnowledgeBase
FactHandle f = event.getFactHandle();
Object newObject = event.getOldObject();
DroolsFactObject deletedFact = this.ruleBaseSession.getLastFactObjectVersion(newObject);
ruleBaseSession.unsetData(f, newObject);
//____ Adding a Delete Event from the HistoryContainer
DeletedFactHistoryEvent deleteFactEvent = new DeletedFactHistoryEvent(this.ruleBaseSession.nextEventId(), deletedFact, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
if (event instanceof RuleRuntimeEventImpl) {
PropagationContext propagationContext = ((RuleRuntimeEventImpl) event).getPropagationContext();
this.updateRuleDetailFromPropagationContext(propagationContext, deleteFactEvent);
this.ruleBaseSession.addHistoryElement(deleteFactEvent);
}
} finally {
logger.debug("<<objectRetracted");
}
}
private void updateRuleDetailFromPropagationContext(PropagationContext propagationContext, FactHistoryEvent historyEvent) {
if (propagationContext.getRuleOrigin() instanceof RuleImpl) {
RuleImpl ruleOrigin = (RuleImpl) propagationContext.getRuleOrigin();
historyEvent.setRuleName(ruleOrigin.getName());
historyEvent.setRulePackageName(ruleOrigin.getPackageName());
historyEvent.setRuleflowGroup(ruleOrigin.getRuleFlowGroup());
}
}
}

View file

@ -0,0 +1,21 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime.impl;
public enum JavaDialect {
ECLIPSE, JANINO
}

View file

@ -0,0 +1,187 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime.impl;
import org.chtijbug.drools.entity.DroolsJbpmVariableObject;
import org.chtijbug.drools.entity.DroolsNodeInstanceObject;
import org.chtijbug.drools.entity.DroolsProcessInstanceObject;
import org.chtijbug.drools.entity.DroolsProcessObject;
import org.chtijbug.drools.entity.history.process.*;
import org.kie.api.event.process.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author nheron
*/
public class ProcessHandlerListener implements ProcessEventListener {
/**
* Class logger
*/
private static Logger logger = LoggerFactory.getLogger(ProcessHandlerListener.class);
/**
* The knowledge session sending event
*/
private final RuleBaseStatefulSession ruleBaseSession;
public ProcessHandlerListener(RuleBaseStatefulSession ruleBaseSession) {
this.ruleBaseSession = ruleBaseSession;
}
@Override
public void beforeProcessStarted(ProcessStartedEvent event) {
logger.debug(">>beforeProcessStarted", event);
try {
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
BeforeProcessStartHistoryEvent beforeProcessStart = new BeforeProcessStartHistoryEvent(this.ruleBaseSession.nextEventId(), droolsProcessInstanceObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
ruleBaseSession.addHistoryElement(beforeProcessStart);
} finally {
logger.debug("<<beforeProcessStarted");
}
}
@Override
public void afterProcessStarted(ProcessStartedEvent event) {
logger.debug(">>afterProcessStarted", event);
try {
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
AfterProcessStartHistoryEvent afterProcessStart = new AfterProcessStartHistoryEvent(this.ruleBaseSession.nextEventId(), droolsProcessInstanceObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
ruleBaseSession.addHistoryElement(afterProcessStart);
} finally {
logger.debug("<<afterProcessStarted");
}
}
@Override
public void beforeProcessCompleted(ProcessCompletedEvent event) {
logger.debug(">>beforeProcessCompleted", event);
try {
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
BeforeProcessEndHistoryEvent beforeProcessEndHistoryEvent = new BeforeProcessEndHistoryEvent(this.ruleBaseSession.nextEventId(), droolsProcessInstanceObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
ruleBaseSession.addHistoryElement(beforeProcessEndHistoryEvent);
} finally {
logger.debug("<<beforeProcessCompleted");
}
}
@Override
public void afterProcessCompleted(ProcessCompletedEvent event) {
logger.debug(">>afterProcessCompleted", event);
try {
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
AfterProcessEndHistoryEvent AfterProcessStart = new AfterProcessEndHistoryEvent(this.ruleBaseSession.nextEventId(), droolsProcessInstanceObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
ruleBaseSession.addHistoryElement(AfterProcessStart);
} finally {
logger.debug("<<afterProcessCompleted");
}
}
@Override
public void beforeNodeTriggered(ProcessNodeTriggeredEvent event) {
logger.debug(">>beforeNodeTriggered", event);
try {
DroolsNodeInstanceObject droolsNodeInstanceObject = ruleBaseSession.getDroolsNodeInstanceObject(event.getNodeInstance());
BeforeNodeInstanceTriggeredHistoryEvent beforeNodeInstanceTriggeredHistoryEvent = new BeforeNodeInstanceTriggeredHistoryEvent(this.ruleBaseSession.nextEventId(), droolsNodeInstanceObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
beforeNodeInstanceTriggeredHistoryEvent.setProcessInstance(droolsProcessInstanceObject);
ruleBaseSession.addHistoryElement(beforeNodeInstanceTriggeredHistoryEvent);
} finally {
logger.debug("<<beforeNodeTriggered");
}
}
@Override
public void afterNodeTriggered(ProcessNodeTriggeredEvent event) {
logger.debug(">>afterNodeTriggered", event);
try {
DroolsNodeInstanceObject droolsNodeInstanceObject = ruleBaseSession.getDroolsNodeInstanceObject(event.getNodeInstance());
AfterNodeInstanceTriggeredHistoryEvent afterNodeInstanceTriggeredHistoryEvent = new AfterNodeInstanceTriggeredHistoryEvent(this.ruleBaseSession.nextEventId(), droolsNodeInstanceObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
afterNodeInstanceTriggeredHistoryEvent.setProcessInstance(droolsProcessInstanceObject);
ruleBaseSession.addHistoryElement(afterNodeInstanceTriggeredHistoryEvent);
} finally {
logger.debug("<<afterNodeTriggered");
}
}
@Override
public void beforeNodeLeft(ProcessNodeLeftEvent event) {
logger.debug(">>beforeNodeLeft", event);
try {
DroolsNodeInstanceObject droolsNodeInstanceObject = ruleBaseSession.getDroolsNodeInstanceObject(event.getNodeInstance());
BeforeNodeLeftHistoryEvent afterHistoryEvent = new BeforeNodeLeftHistoryEvent(this.ruleBaseSession.nextEventId(), droolsNodeInstanceObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
afterHistoryEvent.setProcessInstance(droolsProcessInstanceObject);
ruleBaseSession.addHistoryElement(afterHistoryEvent);
} finally {
logger.debug("<<beforeNodeLeft");
}
}
@Override
public void afterNodeLeft(ProcessNodeLeftEvent event) {
logger.debug(">>afterNodeLeft", event);
try {
DroolsNodeInstanceObject droolsNodeInstanceObject = ruleBaseSession.getDroolsNodeInstanceObject(event.getNodeInstance());
AfterNodeLeftHistoryEvent afterHistoryEvent = new AfterNodeLeftHistoryEvent(this.ruleBaseSession.nextEventId(), droolsNodeInstanceObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
afterHistoryEvent.setProcessInstance(droolsProcessInstanceObject);
ruleBaseSession.addHistoryElement(afterHistoryEvent);
} finally {
logger.debug("<<afterNodeLeft");
}
}
@Override
public void beforeVariableChanged(ProcessVariableChangedEvent event) {
logger.debug(">>beforeVariableChanged", event);
try {
DroolsJbpmVariableObject oldValue = new DroolsJbpmVariableObject(event.getVariableId(), event.getVariableInstanceId(), event.getOldValue());
DroolsProcessObject droolsProcessObject = new DroolsProcessObject(String.valueOf(event.getProcessInstance().getId()), event.getProcessInstance().getProcessName(), event.getProcessInstance().getProcess().getPackageName(), event.getProcessInstance().getProcess().getType(), event.getProcessInstance().getProcess().getVersion());
BeforeVariableChangeChangedHistoryEvent beforeVariableChangeChangedHistoryEvent = new BeforeVariableChangeChangedHistoryEvent(this.ruleBaseSession.nextEventId(), droolsProcessObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId(), oldValue);
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
beforeVariableChangeChangedHistoryEvent.setProcessInstance(droolsProcessInstanceObject);
ruleBaseSession.addHistoryElement(beforeVariableChangeChangedHistoryEvent);
} finally {
logger.debug("<<beforeVariableChanged");
}
}
@Override
public void afterVariableChanged(ProcessVariableChangedEvent event) {
logger.debug(">>afterVariableChanged", event);
try {
DroolsJbpmVariableObject oldValue = new DroolsJbpmVariableObject(event.getVariableId(), event.getVariableInstanceId(), event.getOldValue());
DroolsJbpmVariableObject newValue = new DroolsJbpmVariableObject(event.getVariableId(), event.getVariableInstanceId(), event.getNewValue());
DroolsProcessObject droolsProcessObject = new DroolsProcessObject(String.valueOf(event.getProcessInstance().getId()), event.getProcessInstance().getProcessName(), event.getProcessInstance().getProcess().getPackageName(), event.getProcessInstance().getProcess().getType(), event.getProcessInstance().getProcess().getVersion());
AfterVariableChangeChangedHistoryEvent afterVariableChangeChangedHistoryEvent = new AfterVariableChangeChangedHistoryEvent(this.ruleBaseSession.nextEventId(), droolsProcessObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId(), oldValue, newValue);
DroolsProcessInstanceObject droolsProcessInstanceObject = ruleBaseSession.getDroolsProcessInstanceObject(event.getProcessInstance());
afterVariableChangeChangedHistoryEvent.setProcessInstance(droolsProcessInstanceObject);
ruleBaseSession.addHistoryElement(afterVariableChangeChangedHistoryEvent);
} finally {
logger.debug("<<afterVariableChanged");
}
}
}

View file

@ -0,0 +1,221 @@
package org.chtijbug.drools.runtime.impl;
import org.chtijbug.drools.common.reflection.ReflectionUtils;
import org.chtijbug.drools.entity.DroolsFactObject;
import org.chtijbug.drools.entity.DroolsRuleObject;
import org.chtijbug.drools.entity.history.HistoryContainer;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.kie.api.KieServices;
import org.kie.api.command.BatchExecutionCommand;
import org.kie.api.command.Command;
import org.kie.api.command.KieCommands;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.ObjectFilter;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.server.api.model.ServiceResponse;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.RuleServicesClient;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Created by nheron on 07/06/2016.
*/
public class RuleBaseCommandSession implements RuleBaseSession {
private List<Command<?>> commands = new ArrayList<Command<?>>();
private KieCommands commandsFactory = KieServices.Factory.get().getCommands();
private int maxNumberRuleToExecute = 2000;
private KieServicesClient kieServicesClient;
private String containerId;
public RuleBaseCommandSession(int maxNumberRuleToExecute,KieServicesClient kieServicesClient,String containerId) {
this.maxNumberRuleToExecute = maxNumberRuleToExecute;
this.kieServicesClient=kieServicesClient;
this.containerId = containerId;
}
@Override
public void insertObject(Object newObject) {
commands.add(commandsFactory.newInsert(newObject, newObject.toString()));
}
@Override
public void insertByReflection(Object newObject) throws DroolsChtijbugException {
if (newObject.getClass().getPackage().getName().startsWith("java.")) {
return;
}
//____ Then foreach getters insert item by reflection
for (Method method : newObject.getClass().getMethods()) {
//____ only manage getters
if (!ReflectionUtils.IsGetter(method)) {
continue;
}
Object getterValue;
try {
getterValue = method.invoke(newObject, (Object[]) null);
} catch (Exception e) {
throw new DroolsChtijbugException(DroolsChtijbugException.insertByReflection, "getterValue = method.invoke(newObject, (Object[]) null);", e);
}
if (getterValue == null)
continue;
//____ If returned value is not a collection, insert it in the ksession
if (!(getterValue instanceof Iterable)) {
this.insertByReflection(getterValue);
} else {
Iterable<?> iterable = (Iterable) getterValue;
for (Object item : iterable) {
this.insertByReflection(item);
}
}
}
this.insertObject(newObject);
}
@Override
public void setGlobal(String identifier, Object value) {
commands.add(commandsFactory.newSetGlobal(identifier, value));
}
@Override
public void updateObject(Object updatedObject) {
// Not Possible
}
@Override
public void retractObject(Object oldObject) {
// Not Possible
}
@Override
public void fireAllRules() throws DroolsChtijbugException {
commands.add(commandsFactory.newFireAllRules(maxNumberRuleToExecute));
}
@Override
public Object fireAllRulesAndStartProcess(Object inputObject, String processName) throws DroolsChtijbugException {
Object outputObject=null;
if (inputObject != null) {
//this.insertObject(inputObject);
this.insertByReflection(inputObject);
}
if (processName != null && processName.length() > 0) {
this.startProcess(processName);
}
this.fireAllRules();
commands.add(commandsFactory.newGetObjects(inputObject.getClass().getName()));
RuleServicesClient ruleClient = kieServicesClient.getServicesClient(RuleServicesClient.class);
BatchExecutionCommand batchCommand = commandsFactory.newBatchExecution(commands);
ServiceResponse<ExecutionResults> response = ruleClient.executeCommandsWithResults(this.containerId, batchCommand);
if (response.equals(ServiceResponse.ResponseType.SUCCESS)){
ExecutionResults actualData = response.getResult();
Collection<String> identifiers = actualData.getIdentifiers();
for (String id : identifiers){
outputObject=actualData.getValue(id);
}
}
return outputObject;
}
@Override
public Object fireAllRulesAndStartProcessWithParam(Object inputObject, String processName) throws DroolsChtijbugException {
//commands.add(commandsFactory.newFireAllRules(maxNumberRuleToExecute));
return this.fireAllRulesAndStartProcess(inputObject,processName);
}
@Override
public void startProcess(String processName) {
commands.add(commandsFactory.newStartProcess(processName));
}
@Override
public void dispose() {
}
@Override
public HistoryContainer getHistoryContainer() {
return null;
}
@Override
public String getHistoryContainerXML() {
return null;
}
@Override
public Collection<DroolsFactObject> listLastVersionObjects() {
return null;
}
@Override
public String listLastVersionObjectsXML() {
return null;
}
@Override
public Collection<DroolsRuleObject> listRules() {
return null;
}
@Override
public int getNumberRulesExecuted() {
return 0;
}
@Override
public Long getSessionId() {
return null;
}
@Override
public Long getRuleBaseID() {
return null;
}
@Override
public KieSession getKnowledgeSession() {
return null;
}
@Override
public Collection<? extends Object> getObjects(ObjectFilter objectFilter) {
return null;
}
@Override
public void completeWorkItem(long processId, Map<String, Object> vars) {
commands.add(commandsFactory.newCompleteWorkItem(processId, vars));
}
@Override
public void abortWorkItem(long processId) {
commands.add(commandsFactory.newAbortWorkItem(processId));
}
@Override
public void registerWorkItemHandler(String workItemName, WorkItemHandler workItemHandler) {
commands.add(commandsFactory.newRegisterWorkItemHandlerCommand(workItemHandler, workItemName));
}
@Override
public ProcessInstance startProcess(String processName, Map<String, Object> vars) {
commands.add(commandsFactory.newStartProcess(processName, vars));
return null;
}
public List<Command<?>> getCommands() {
return commands;
}
}

View file

@ -0,0 +1,127 @@
package org.chtijbug.drools.runtime.impl;
import org.chtijbug.drools.entity.history.EventCounter;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBasePackage;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.chtijbug.drools.runtime.listener.HistoryListener;
import org.kie.server.api.marshalling.MarshallingFormat;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.KieServicesConfiguration;
import org.kie.server.client.KieServicesFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Semaphore;
/**
* Created by nheron on 07/06/2016.
*/
public class RuleBaseCommandSingleton implements RuleBasePackage {
/**
* default rule threshold
*/
public static int DEFAULT_RULE_THRESHOLD = 2000;
/**
* Class Logger
*/
private static Logger logger = LoggerFactory.getLogger(RuleBaseCommandSingleton.class);
/**
* unique ID of the RuleBase in the JVM
*/
protected EventCounter eventCounter = EventCounter.newCounter();
protected EventCounter sessionCounter = EventCounter.newCounter();
private int maxNumberRuleToExecute = DEFAULT_RULE_THRESHOLD;
/**
* Semaphore used to void concurrent access to the singleton
*/
private Semaphore lockKbase = new Semaphore(1);
/**
* History Listener
*/
private String containerId;
private String url;
private String username;
private String password;
private KieServicesClient kieServicesClient;
public RuleBaseCommandSingleton(int maxNumberRuleToExecute) {
this.maxNumberRuleToExecute = maxNumberRuleToExecute;
}
public RuleBaseCommandSingleton(int defaultRuleThreshold, String containerId,String url, String username, String password) {
this(defaultRuleThreshold);
this.containerId=containerId;
this.url=url;
this.username=username;
this.password=password;
}
@Override
public RuleBaseSession createRuleBaseSession() throws DroolsChtijbugException {
logger.debug(">>createRuleBaseSession");
try {
//____ Creating new Rule Base Session using default rule threshold
return this.createRuleBaseSession(this.maxNumberRuleToExecute);
} finally {
logger.debug("<<createRuleBaseSession");
}
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute) throws DroolsChtijbugException {
return this.createRuleBaseSession(maxNumberRulesToExecute, null);
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute, HistoryListener sessionHistoryListener) throws DroolsChtijbugException {
logger.debug(">>createRuleBaseSession", maxNumberRulesToExecute);
RuleBaseSession newRuleBaseSession = null;
try {
//_____ Wrapping the knowledge Session
newRuleBaseSession = new RuleBaseCommandSession(maxNumberRulesToExecute,this.kieServicesClient,this.containerId);
//_____ Release semaphore
lockKbase.release();
return newRuleBaseSession;
} finally {
logger.debug("<<createRuleBaseSession", newRuleBaseSession);
}
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute, HistoryListener sessionHistoryListener, String sessionName) throws DroolsChtijbugException {
return this.createRuleBaseSession(maxNumberRulesToExecute, sessionHistoryListener);
}
@Override
public void loadKBase(String version) throws DroolsChtijbugException {
//
}
@Override
public HistoryListener getHistoryListener() {
return null;
}
@Override
public Long getRuleBaseID() {
return null;
}
@Override
public void dispose() {
}
public void connectKBase() {
KieServicesConfiguration config;
config = KieServicesFactory.newRestConfiguration(url, username, password);
MarshallingFormat marshallingFormat = MarshallingFormat.XSTREAM;
config.setMarshallingFormat(marshallingFormat);
this.kieServicesClient = KieServicesFactory.newKieServicesClient(config);
}
}

View file

@ -0,0 +1,332 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime.impl;
import org.chtijbug.drools.entity.history.EventCounter;
import org.chtijbug.drools.entity.history.knowledge.*;
import org.chtijbug.drools.kieserver.extension.KieServerAddOnElement;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBasePackage;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.chtijbug.drools.runtime.listener.HistoryListener;
import org.chtijbug.drools.runtime.resource.FileKnowledgeResource;
import org.chtijbug.drools.runtime.resource.KnowledgeModule;
import org.chtijbug.drools.runtime.resource.WorkbenchClient;
import org.kie.api.builder.ReleaseId;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
import static com.google.common.base.Throwables.propagate;
/**
* @author Bertrand Gressier
*/
public class RuleBaseSingleton implements RuleBasePackage {
/**
* default rule threshold
*/
public static int DEFAULT_RULE_THRESHOLD = 2000;
/**
* Class Logger
*/
private static Logger logger = LoggerFactory.getLogger(RuleBaseSingleton.class);
/**
* unique ID of the RuleBase in the JVM
*/
protected EventCounter eventCounter = EventCounter.newCounter();
protected EventCounter sessionCounter = EventCounter.newCounter();
/**
* Rule Base ID
*/
private String ruleBaseName;
private Long ruleBaseID;
private KieContainer kieContainer;
private ReleaseId releaseId;
private String groupId;
private String artifactId;
private String version;
private KnowledgeModule knowledgeModule;
/**
* Max rule to be fired threshold.
*/
private int maxNumberRuleToExecute = DEFAULT_RULE_THRESHOLD;
/**
* Semaphore used to void concurrent access to the singleton
*/
private Semaphore lockKbase = new Semaphore(1);
/**
* History Listener
*/
private HistoryListener historyListener = null;
/**
* Global Maps
*/
Map<String, Object> globals = new HashMap<>();
/**
* extensions Points
*/
private KieServerAddOnElement kieServerAddOnElement = null;
/**
* @param kieContainer
* @param maxNumberRulesToExecute
*/
public RuleBaseSingleton(KieContainer kieContainer, int maxNumberRulesToExecute) {
this.kieContainer = kieContainer;
this.maxNumberRuleToExecute = maxNumberRulesToExecute;
}
public RuleBaseSingleton(KieContainer kieContainer, int maxNumberRulesToExecute, KieServerAddOnElement kieServerAddOnElement) {
this.kieServerAddOnElement = kieServerAddOnElement;
this.kieContainer = kieContainer;
this.maxNumberRuleToExecute = maxNumberRulesToExecute;
}
public RuleBaseSingleton(KieContainer kieContainer, int maxNumberRulesToExecute, HistoryListener historyListener) {
this.kieContainer = kieContainer;
this.maxNumberRuleToExecute = maxNumberRulesToExecute;
this.historyListener = historyListener;
}
public RuleBaseSingleton(Long ruleBaseID, int maxNumberRulesToExecute, HistoryListener historyListener, String groupId, String artifactId, String version) throws DroolsChtijbugException {
this.ruleBaseID = ruleBaseID;
this.maxNumberRuleToExecute = maxNumberRulesToExecute;
this.historyListener = historyListener;
if (this.historyListener != null) {
KnowledgeBaseCreatedEvent knowledgeBaseCreatedEvent = new KnowledgeBaseCreatedEvent(eventCounter.next(), new Date(), ruleBaseID);
this.historyListener.fireEvent(knowledgeBaseCreatedEvent);
}
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.knowledgeModule = new KnowledgeModule(this.ruleBaseID, this.historyListener, groupId, artifactId, version, eventCounter);
}
public RuleBaseSingleton(String ruleBaseName, int maxNumberRulesToExecute, HistoryListener historyListener) throws DroolsChtijbugException {
this.ruleBaseName = ruleBaseName;
this.maxNumberRuleToExecute = maxNumberRulesToExecute;
this.historyListener = historyListener;
if (this.historyListener != null) {
KnowledgeBaseCreatedEvent knowledgeBaseCreatedEvent = new KnowledgeBaseCreatedEvent(eventCounter.next(), new Date(), ruleBaseID);
this.historyListener.fireEvent(knowledgeBaseCreatedEvent);
}
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.knowledgeModule = new KnowledgeModule(this.ruleBaseName, this.historyListener, eventCounter);
}
public RuleBaseSingleton(Long ruleBaseID, int maxNumberRulesToExecute, HistoryListener historyListener) throws DroolsChtijbugException {
this.ruleBaseID = ruleBaseID;
this.maxNumberRuleToExecute = maxNumberRulesToExecute;
this.historyListener = historyListener;
if (this.historyListener != null) {
KnowledgeBaseCreatedEvent knowledgeBaseCreatedEvent = new KnowledgeBaseCreatedEvent(eventCounter.next(), new Date(), ruleBaseID);
this.historyListener.fireEvent(knowledgeBaseCreatedEvent);
}
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.knowledgeModule = new KnowledgeModule(this.ruleBaseID, this.historyListener, eventCounter);
}
@Override
public RuleBaseSession createRuleBaseSession() throws DroolsChtijbugException {
logger.debug(">>createRuleBaseSession");
try {
//____ Creating new Rule Base Session using default rule threshold
return this.createRuleBaseSession(this.maxNumberRuleToExecute);
} finally {
logger.debug("<<createRuleBaseSession");
}
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute) throws DroolsChtijbugException {
return this.createRuleBaseSession(maxNumberRulesToExecute, this.historyListener);
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute, HistoryListener sessionHistoryListener) throws DroolsChtijbugException {
return this.createRuleBaseSession(maxNumberRulesToExecute, sessionHistoryListener, null);
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute, HistoryListener sessionHistoryListener, String sessionName) throws DroolsChtijbugException {
logger.debug(">>createRuleBaseSession", maxNumberRulesToExecute);
RuleBaseSession newRuleBaseSession = null;
try {
if (kieContainer != null) {
//____ Acquire semaphore
try {
lockKbase.acquire();
} catch (Exception e) {
throw new DroolsChtijbugException(DroolsChtijbugException.KbaseAcquire, "", e);
}
//_____ Now we can create a new stateful session using KnowledgeBase
//_____ Now we can create a new stateful session using KnowledgeBase
KieSession newDroolsSession = null;
if (sessionName == null) {
if (ruleBaseName != null && ruleBaseName.length() > 0) {
newDroolsSession = this.kieContainer.getKieBase(ruleBaseName).newKieSession();
} else {
newDroolsSession = this.kieContainer.getKieBase().newKieSession();
}
} else {
newDroolsSession = this.kieContainer.newKieSession(sessionName);
}
for (String globalVariableName : globals.keySet()) {
if (globals.get(globalVariableName) != null) {
newDroolsSession.setGlobal(globalVariableName, globals.get(globalVariableName));
}
}
Long sessionId = this.sessionCounter.next();
if (sessionHistoryListener != null) {
KnowledgeBaseCreateSessionEvent knowledgeBaseCreateSessionEvent = new KnowledgeBaseCreateSessionEvent(eventCounter.next(), new Date(), this.ruleBaseID);
knowledgeBaseCreateSessionEvent.setSessionId(sessionId);
sessionHistoryListener.fireEvent(knowledgeBaseCreateSessionEvent);
}
//_____ Wrapping the knowledge Session
newRuleBaseSession = new RuleBaseStatefulSession(this.ruleBaseID, sessionId, newDroolsSession, maxNumberRulesToExecute, sessionHistoryListener);
//_____ Release semaphore
lockKbase.release();
} else {
throw new DroolsChtijbugException(DroolsChtijbugException.KbaseNotInitialised, "", null);
}
//____ return the wrapped KnowledgeSession
return newRuleBaseSession;
} finally {
logger.debug("<<createRuleBaseSession", newRuleBaseSession);
}
}
public synchronized void createKBase(String workbenchUrl, String username, String password) throws DroolsChtijbugException {
if (kieContainer != null) {
if (this.historyListener != null) {
this.historyListener.fireEvent(new KnowledgeBaseReloadedEvent(eventCounter.next(), new Date(), this.ruleBaseID));
}
// TODO dispose all elements
} else {
if (this.historyListener != null) {
this.historyListener.fireEvent(new KnowledgeBaseInitialLoadEvent(eventCounter.next(), new Date(), this.ruleBaseID));
}
}
try {
//___ TODO add URI Resource
this.knowledgeModule.addWorkbenchResource(workbenchUrl, username, password);
kieContainer = this.knowledgeModule.build();
} catch (Exception e) {
logger.error("error to load Agent", e);
throw new DroolsChtijbugException(DroolsChtijbugException.ErrorToLoadAgent, "", e);
}
}
@Override
public void loadKBase(String version) throws DroolsChtijbugException {
if (this.knowledgeModule.getWorkbenchClient() != null) {
try {
WorkbenchClient client = this.knowledgeModule.getWorkbenchClient();
lockKbase.acquire();
//this.releaseId = kieServices.newReleaseId(this.releaseId.getGroupId(), this.releaseId.getArtifactId(), version);
this.version = version;
kieContainer = null;
this.knowledgeModule = null;
this.knowledgeModule = new KnowledgeModule(this.ruleBaseID, this.historyListener, groupId, artifactId, version, eventCounter);
this.createKBase(client.getWorkbenchUrl(), client.getUsername(), client.getPassword());
lockKbase.release();
if (this.historyListener != null) {
// TODO change the following event...
this.historyListener.fireEvent(new KnowledgeBaseAddResourceEvent(eventCounter.next(), new Date(), this.ruleBaseID));
}
} catch (InterruptedException e) {
throw propagate(e);
}
}
}
@Override
public HistoryListener getHistoryListener() {
return historyListener;
}
public Long getRuleBaseID() {
return ruleBaseID;
}
@Override
public void dispose() {
if (this.historyListener != null) {
try {
this.historyListener.fireEvent(new KnowledgeBaseDisposeEvent(eventCounter.next(), new Date(), this.ruleBaseID));
} catch (DroolsChtijbugException e) {
throw propagate(e);
}
}
this.kieContainer = null;
}
public void createKBase(List<FileKnowledgeResource> files) {
try {
if (this.historyListener != null) {
this.historyListener.fireEvent(new KnowledgeBaseInitialLoadEvent(eventCounter.next(), new Date(), this.ruleBaseID));
}
lockKbase.acquire();
this.knowledgeModule.addAllFiles(files);
kieContainer = this.knowledgeModule.build();
lockKbase.release();
} catch (InterruptedException | DroolsChtijbugException e) {
propagate(e);
}
}
public void createKBase(ClassLoader... classLoaders) {
try {
if (this.historyListener != null) {
this.historyListener.fireEvent(new KnowledgeBaseInitialLoadEvent(eventCounter.next(), new Date(), this.ruleBaseID));
}
lockKbase.acquire();
if (classLoaders.length == 0) {
kieContainer = this.knowledgeModule.buildFromClassPath();
} else {
kieContainer = this.knowledgeModule.buildFromClassPath(classLoaders[0]);
}
lockKbase.release();
} catch (InterruptedException | DroolsChtijbugException e) {
propagate(e);
}
}
}

View file

@ -0,0 +1,558 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime.impl;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import org.chtijbug.drools.common.reflection.ReflectionUtils;
import org.chtijbug.drools.entity.*;
import org.chtijbug.drools.entity.history.EventCounter;
import org.chtijbug.drools.entity.history.HistoryContainer;
import org.chtijbug.drools.entity.history.HistoryEvent;
import org.chtijbug.drools.entity.history.fact.InsertedByReflectionFactEndHistoryEvent;
import org.chtijbug.drools.entity.history.fact.InsertedByReflectionFactStartHistoryEvent;
import org.chtijbug.drools.entity.history.session.*;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.DroolsFactObjectFactory;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.chtijbug.drools.runtime.listener.HistoryListener;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.jbpm.workflow.core.node.RuleSetNode;
import org.jbpm.workflow.instance.node.*;
import org.kie.api.definition.rule.Rule;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.ObjectFilter;
import org.kie.api.runtime.process.NodeInstance;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.api.runtime.rule.FactHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author nheron
*/
public class RuleBaseStatefulSession implements RuleBaseSession {
/**
* Class Logger
*/
private static Logger logger = LoggerFactory.getLogger(RuleBaseStatefulSession.class);
/**
* All objects inserted into the session as fact
*/
private final Map<FactHandle, Object> listObject;
private final Map<Object, FactHandle> listFact;
private final Map<Object, List<DroolsFactObject>> listFactObjects;
private final HistoryContainer historyContainer;
/**
* All the
*/
private final Map<String, DroolsRuleObject> listRules;
private final Map<String, DroolsProcessObject> processList;
private final Map<String, DroolsProcessInstanceObject> processInstanceList;
/**
* The wrapped Drools KnowledgeSession
*/
private KieSession knowledgeSession = null;
// Listeners can be dispose ...
private FactHandlerListener factListener;
private RuleHandlerListener ruleHandlerListener;
private ProcessHandlerListener processHandlerListener;
private int maxNumberRuleToExecute;
private XStream xstream = new XStream(new JettisonMappedXmlDriver());
private Long ruleBaseID;
private Long sessionId;
private HistoryListener historyListener;
private EventCounter eventCounter = EventCounter.newCounter();
public RuleBaseStatefulSession(Long ruleBaseID, Long sessionId, KieSession knowledgeSession, int maxNumberRuleToExecute, HistoryListener historyListener) throws DroolsChtijbugException {
this.ruleBaseID = ruleBaseID;
this.sessionId = sessionId;
this.knowledgeSession = knowledgeSession;
this.maxNumberRuleToExecute = maxNumberRuleToExecute;
this.factListener = new FactHandlerListener(this);
this.ruleHandlerListener = new RuleHandlerListener(this);
this.processHandlerListener = new ProcessHandlerListener(this);
this.historyContainer = new HistoryContainer(sessionId, historyListener);
this.listFactObjects = new HashMap<>();
this.listFact = new HashMap<>();
this.listObject = new HashMap<>();
this.listRules = new HashMap<>();
this.processList = new HashMap<>();
this.processInstanceList = new HashMap<>();
knowledgeSession.addEventListener(factListener);
knowledgeSession.addEventListener(ruleHandlerListener);
knowledgeSession.addEventListener(processHandlerListener);
this.historyListener = historyListener;
if (this.historyListener != null) {
SessionCreatedEvent sessionCreatedEvent = new SessionCreatedEvent(eventCounter.next(), this.ruleBaseID, this.sessionId);
this.addHistoryElement(sessionCreatedEvent);
}
}
public int getMaxNumberRuleToExecute() {
return maxNumberRuleToExecute;
}
public DroolsProcessInstanceObject getDroolsProcessInstanceObject(ProcessInstance processInstance) {
DroolsProcessInstanceObject droolsProcessInstanceObject = processInstanceList.get(Long.toString(processInstance.getId()));
if (droolsProcessInstanceObject == null) {
DroolsProcessObject droolsProcessObject = processList.get(processInstance.getProcess().getId());
if (droolsProcessObject == null) {
droolsProcessObject = DroolsProcessObject.createDroolsProcessObject(processInstance.getProcess().getId(),
processInstance.getProcess().getName(),
processInstance.getProcess().getPackageName(), processInstance.getProcess().getType(), processInstance.getProcess().getVersion());
processList.put(processInstance.getProcess().getId(), droolsProcessObject);
}
droolsProcessInstanceObject = DroolsProcessInstanceObject.createDroolsProcessInstanceObject(String.valueOf(processInstance.getId()), droolsProcessObject);
processInstanceList.put(droolsProcessInstanceObject.getId(), droolsProcessInstanceObject);
}
return droolsProcessInstanceObject;
}
public DroolsNodeInstanceObject getDroolsNodeInstanceObject(NodeInstance nodeInstance) {
DroolsNodeType nodeType = DroolsNodeType.Other;
String ruleFlowGroupName = null;
if (nodeInstance instanceof StartNodeInstance) {
nodeType = DroolsNodeType.StartNode;
} else if (nodeInstance instanceof RuleSetNodeInstance) {
nodeType = DroolsNodeType.RuleNode;
RuleSetNode ruleSetNode = this.getRuleSetNode(nodeInstance);
if (ruleSetNode != null) {
ruleFlowGroupName = ruleSetNode.getRuleFlowGroup();
}
} else if (nodeInstance instanceof SplitInstance) {
nodeType = DroolsNodeType.SplitNode;
} else if (nodeInstance instanceof JoinInstance) {
nodeType = DroolsNodeType.JoinNode;
} else if (nodeInstance instanceof EndNodeInstance) {
nodeType = DroolsNodeType.EndNode;
}
DroolsProcessInstanceObject droolsProcessInstanceObject = processInstanceList.get(Long.toString(nodeInstance.getProcessInstance().getId()));
if (droolsProcessInstanceObject == null) {
droolsProcessInstanceObject = this.getDroolsProcessInstanceObject(nodeInstance.getProcessInstance());
}
DroolsNodeInstanceObject droolsNodeInstanceObject = droolsProcessInstanceObject.getDroolsNodeInstanceObjet(String.valueOf(nodeInstance.getId()));
if (droolsNodeInstanceObject == null) {
DroolsNodeObject droolsNodeObject = DroolsNodeObject.createDroolsNodeObject(String.valueOf(nodeInstance.getNode().getId()), nodeType);
droolsProcessInstanceObject.getProcess().addDroolsNodeObject(droolsNodeObject);
droolsNodeObject.setRuleflowGroupName(ruleFlowGroupName);
droolsNodeInstanceObject = DroolsNodeInstanceObject.createDroolsNodeInstanceObject(String.valueOf(nodeInstance.getId()), droolsNodeObject);
droolsProcessInstanceObject.addDroolsNodeInstanceObject(droolsNodeInstanceObject);
}
return droolsNodeInstanceObject;
}
public DroolsRuleObject getDroolsRuleObject(Rule rule) {
DroolsRuleObject droolsRuleObject = listRules.get(rule.toString());
RuleImpl ruleInstance = (RuleImpl) rule;
if (droolsRuleObject == null) {
droolsRuleObject = DroolsRuleObject.createDroolRuleObject(rule.getName(), rule.getPackageName());
droolsRuleObject.setRuleFlowGroup(ruleInstance.getRuleFlowGroup());
addDroolsRuleObject(droolsRuleObject);
}
return droolsRuleObject;
}
public void addDroolsRuleObject(DroolsRuleObject droolsRuleObject) {
listRules.put(droolsRuleObject.getRulePackageName() + droolsRuleObject.getRuleName(), droolsRuleObject);
}
public DroolsFactObject getLastFactObjectVersion(Object searchO) {
int lastVersion = listFactObjects.get(searchO).size() - 1;
DroolsFactObject result = getFactObjectVersion(searchO, lastVersion);
try {
result.updateRealObjectFromJSON();
} catch (ClassNotFoundException e) {
logger.error("getLastFactObjectVersion",e);
} catch (IOException e) {
logger.error("getLastFactObjectVersion",e);
}
return result;
}
public DroolsFactObject getFactObjectVersion(Object search0, int version) {
return listFactObjects.get(search0).get(version);
}
public DroolsFactObject getLastFactObjectVersionFromFactHandle(FactHandle factToFind) {
Object searchObject = this.listObject.get(factToFind);
if (searchObject == null) {
return null;
}
List<DroolsFactObject> facto = listFactObjects.get(searchObject);
if (facto == null) {
logger.error("List of FactObject can not be null for FactHandle {}", factToFind);
return null;
}
int lastVersion = facto.size() - 1;
return listFactObjects.get(searchObject).get(lastVersion);
}
@Override
public HistoryContainer getHistoryContainer() {
return historyContainer;
}
@Override
public String getHistoryContainerXML() {
String result = null;
if (historyContainer != null) {
xstream.setMode(XStream.NO_REFERENCES);
result = xstream.toXML(historyContainer);
}
return result;
}
@Override
public Collection<DroolsFactObject> listLastVersionObjects() {
Collection<DroolsFactObject> list = new ArrayList<>();
for (Object o : this.listFact.keySet()) {
FactHandle factHandle = this.listFact.get(o);
list.add(this.getLastFactObjectVersionFromFactHandle(factHandle));
}
return list;
}
@Override
public String listLastVersionObjectsXML() {
String result = null;
Collection<DroolsFactObject> list = this.listLastVersionObjects();
if (list != null) {
xstream.setMode(XStream.NO_REFERENCES);
result = xstream.toXML(list);
}
return result;
}
public void setData(FactHandle f, Object o, DroolsFactObject fObject) {
Object objectSearch = listObject.containsKey(f);
listFact.remove(objectSearch);
listObject.put(f, o);
listFact.put(o, f);
if (!listFactObjects.containsKey(o)) {
List<DroolsFactObject> newList = new LinkedList<>();
newList.add(fObject);
listFactObjects.put(o, newList);
} else {
listFactObjects.get(o).add(fObject);
}
}
public void unsetData(FactHandle f, Object o) {
listObject.remove(f);
listFact.remove(o);
}
@Override
public void dispose() {
knowledgeSession.removeEventListener(factListener);
knowledgeSession.removeEventListener(ruleHandlerListener);
knowledgeSession.removeEventListener(processHandlerListener);
for (FactHandle f : listObject.keySet()) {
knowledgeSession.delete(f);
}
factListener = null;
ruleHandlerListener = null;
processHandlerListener = null;
knowledgeSession.dispose();
knowledgeSession = null;
if (this.historyListener != null) {
try {
SessionDisposedEvent sessionDisposedEvent = new SessionDisposedEvent(eventCounter.next(), this.ruleBaseID, this.sessionId);
this.addHistoryElement(sessionDisposedEvent);
} catch (Exception e) {
logger.error("Exception in calling historyEvent", e);
}
}
}
@Override
public void insertObject(Object newObject) {
FactHandle newFactHandle = this.knowledgeSession.insert(newObject);
listFact.put(newObject, newFactHandle);
}
@Override
public void insertByReflection(Object newObject) throws DroolsChtijbugException {
// Avoid inserting java.* classes
if (newObject.getClass().getPackage().getName().startsWith("java.")) {
return;
}
if (this.historyListener != null) {
DroolsFactObject topDroolsObject = DroolsFactObjectFactory.createFactObject(newObject);
InsertedByReflectionFactStartHistoryEvent insertedByReflectionFactStartHistoryEvent = new InsertedByReflectionFactStartHistoryEvent(eventCounter.next(), topDroolsObject, this.ruleBaseID, this.sessionId);
this.addHistoryElement(insertedByReflectionFactStartHistoryEvent);
}
//____ First insert the root object
insertObject(newObject);
//____ Then foreach getters insert item by reflection
for (Method method : newObject.getClass().getMethods()) {
//____ only manage getters
if (!ReflectionUtils.IsGetter(method)) {
continue;
}
Object getterValue;
try {
getterValue = method.invoke(newObject, (Object[]) null);
} catch (Exception e) {
throw new DroolsChtijbugException(DroolsChtijbugException.insertByReflection, "getterValue = method.invoke(newObject, (Object[]) null);", e);
}
if (getterValue == null)
continue;
//____ If returned value is not a collection, insert it in the ksession
if (!(getterValue instanceof Iterable)) {
this.insertByReflection(getterValue);
} else {
Iterable<?> iterable = (Iterable) getterValue;
for (Object item : iterable) {
this.insertByReflection(item);
}
}
}
if (this.historyListener != null) {
InsertedByReflectionFactEndHistoryEvent insertedByReflectionFactEndHistoryEvent = new InsertedByReflectionFactEndHistoryEvent(eventCounter.next(), this.ruleBaseID, this.sessionId);
this.addHistoryElement(insertedByReflectionFactEndHistoryEvent);
}
}
@Override
public void setGlobal(String identifier, Object value) {
this.knowledgeSession.setGlobal(identifier, value);
}
@Override
public void updateObject(Object updatedObject) {
FactHandle factToUpdate = listFact.get(updatedObject);
this.knowledgeSession.update(factToUpdate, updatedObject);
}
@Override
public void retractObject(Object oldObject) {
FactHandle factToDelete = listFact.get(oldObject);
this.knowledgeSession.delete(factToDelete);
}
@Override
public Object fireAllRulesAndStartProcess(Object inputObject, String processName) throws DroolsChtijbugException {
DroolsFactObject inputDroolsObject = null;
DroolsFactObject outputDroolsObject = null;
if (inputObject != null) {
this.insertByReflection(inputObject);
inputDroolsObject = DroolsFactObjectFactory.createFactObject(inputObject);
}
if (processName != null && processName.length() > 0) {
this.startProcess(processName);
}
this.fireAllRules();
if (inputDroolsObject != null) {
outputDroolsObject = DroolsFactObjectFactory.createFactObject(inputObject);
}
if (this.historyListener != null) {
SessionFireAllRulesAndStartProcess sessionFireAllRulesAndStartProcess = new SessionFireAllRulesAndStartProcess(eventCounter.next(), this.ruleBaseID, this.sessionId, inputDroolsObject, outputDroolsObject);
this.addHistoryElement(sessionFireAllRulesAndStartProcess);
}
return inputObject;
}
@Override
public void fireAllRules() throws DroolsChtijbugException {
if (this.historyListener != null) {
SessionFireAllRulesBeginEvent sessionFireAllRulesBeginEvent = new SessionFireAllRulesBeginEvent(eventCounter.next(), this.ruleBaseID, this.sessionId);
this.addHistoryElement(sessionFireAllRulesBeginEvent);
}
long startTime = System.currentTimeMillis();
long beforeNumberRules = ruleHandlerListener.getNbRuleFired();
try {
this.knowledgeSession.fireAllRules();
} catch (Exception e) {
throw new DroolsChtijbugException(DroolsChtijbugException.fireAllRules, "", e);
}
long stopTime = System.currentTimeMillis();
long afterNumberRules = ruleHandlerListener.getNbRuleFired();
if (ruleHandlerListener.isMaxNumerExecutedRulesReached()) {
if (this.historyListener != null) {
SessionFireAllRulesMaxNumberReachedEvent sessionFireAllRulesMaxNumberReachedEvent = new SessionFireAllRulesMaxNumberReachedEvent(eventCounter.next(), ruleHandlerListener.getNbRuleFired(), maxNumberRuleToExecute, this.ruleBaseID, this.sessionId);
this.addHistoryElement(sessionFireAllRulesMaxNumberReachedEvent);
}
throw new DroolsChtijbugException(DroolsChtijbugException.MaxNumberRuleExecutionReached, "nbRulesExecuted" + afterNumberRules + " and MaxNumberRules for the session is set to " + maxNumberRuleToExecute, null);
}
if (this.historyListener != null) {
SessionFireAllRulesEndEvent sessionFireAllRulesEndEvent = new SessionFireAllRulesEndEvent(eventCounter.next(), this.ruleBaseID, this.sessionId, stopTime - startTime, afterNumberRules - beforeNumberRules);
this.addHistoryElement(sessionFireAllRulesEndEvent);
}
}
@Override
public void startProcess(String processName) {
if (this.historyListener != null) {
try {
SessionStartProcessBeginEvent sessionStartProcessBeginEvent = new SessionStartProcessBeginEvent(eventCounter.next(), processName, this.ruleBaseID, this.sessionId);
this.addHistoryElement(sessionStartProcessBeginEvent);
} catch (Exception e) {
logger.error("Exception in calling historyEvent", e);
}
}
ProcessInstance processInstance = this.knowledgeSession.startProcess(processName);
if (this.historyListener != null) {
try {
SessionStartProcessEndEvent sessionStartProcessEndEvent = new SessionStartProcessEndEvent(eventCounter.next(), processName, this.ruleBaseID, this.sessionId, processInstance.getProcessId());
this.addHistoryElement(sessionStartProcessEndEvent);
} catch (Exception e) {
logger.error("Exception in calling historyEvent", e);
}
}
}
@Override
public Collection<DroolsRuleObject> listRules() {
return listRules.values();
}
@Override
public int getNumberRulesExecuted() {
int result = 0;
if (this.ruleHandlerListener != null) {
result = this.ruleHandlerListener.getNbRuleFired();
}
return result;
}
public void addHistoryElement(HistoryEvent newHistoryElement) {
this.historyContainer.addHistoryElement(this.ruleBaseID, this.sessionId, newHistoryElement);
}
public Long getSessionId() {
return sessionId;
}
public Long getRuleBaseID() {
return ruleBaseID;
}
@Override
public KieSession getKnowledgeSession() {
return knowledgeSession;
}
@Override
public Collection<? extends java.lang.Object> getObjects(ObjectFilter objectFilter) {
return this.knowledgeSession.getObjects(objectFilter);
}
@Override
public void completeWorkItem(long processId, Map<String, Object> vars) {
if (this.knowledgeSession != null && this.knowledgeSession.getWorkItemManager() != null) {
this.knowledgeSession.getWorkItemManager().completeWorkItem(processId, vars);
}
}
@Override
public void abortWorkItem(long processId) {
if (this.knowledgeSession != null && this.knowledgeSession.getWorkItemManager() != null) {
this.knowledgeSession.getWorkItemManager().abortWorkItem(processId);
}
}
@Override
public void registerWorkItemHandler(String workItemName, WorkItemHandler workItemHandler) {
if (this.knowledgeSession != null && this.knowledgeSession.getWorkItemManager() != null) {
this.knowledgeSession.getWorkItemManager().registerWorkItemHandler(workItemName, workItemHandler);
}
}
@Override
public ProcessInstance startProcess(String processName, Map<String, Object> vars) {
if (this.knowledgeSession != null && this.knowledgeSession.getWorkItemManager() != null) {
return this.knowledgeSession.startProcess(processName, vars);
}
return null;
}
private RuleSetNode getRuleSetNode(NodeInstance nodeInstance) {
RuleSetNode ruleSetNode = null;
if (nodeInstance instanceof RuleSetNodeInstance) {
if (nodeInstance.getNode() instanceof RuleSetNode) {
ruleSetNode = (RuleSetNode) nodeInstance.getNode();
}
}
return ruleSetNode;
}
public Long nextEventId() {
return this.eventCounter.next();
}
@Override
public Object fireAllRulesAndStartProcessWithParam(Object inputObject, String processName) throws DroolsChtijbugException {
DroolsFactObject inputDroolsObject = null;
DroolsFactObject outputDroolsObject = null;
if (inputObject != null) {
this.insertByReflection(inputObject);
inputDroolsObject = DroolsFactObjectFactory.createFactObject(inputObject);
}
Map<String, Object> maps = new HashMap<String, Object>();
maps.put("inputObject", inputObject);
if (processName != null && processName.length() > 0) {
this.startProcess(processName, maps);
}
this.fireAllRules();
if (inputDroolsObject != null) {
outputDroolsObject = DroolsFactObjectFactory.createFactObject(inputObject);
}
if (this.historyListener != null) {
SessionFireAllRulesAndStartProcess sessionFireAllRulesAndStartProcess = new SessionFireAllRulesAndStartProcess(eventCounter.next(), this.ruleBaseID, this.sessionId, inputDroolsObject, outputDroolsObject);
this.addHistoryElement(sessionFireAllRulesAndStartProcess);
}
return inputObject;
}
}

View file

@ -0,0 +1,180 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime.impl;
import org.chtijbug.drools.entity.DroolsFactObject;
import org.chtijbug.drools.entity.DroolsRuleFlowGroupObject;
import org.chtijbug.drools.entity.DroolsRuleObject;
import org.chtijbug.drools.entity.history.rule.AfterRuleFiredHistoryEvent;
import org.chtijbug.drools.entity.history.rule.AfterRuleFlowActivatedHistoryEvent;
import org.chtijbug.drools.entity.history.rule.AfterRuleFlowDeactivatedHistoryEvent;
import org.chtijbug.drools.entity.history.rule.BeforeRuleFiredHistoryEvent;
import org.chtijbug.drools.entity.history.session.SessionFireAllRulesMaxNumberReachedEvent;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.reteoo.InitialFactImpl;
import org.kie.api.event.rule.*;
import org.kie.api.runtime.KieRuntime;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.Match;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* @author nheron
*/
public class RuleHandlerListener extends DefaultAgendaEventListener {
/**
* Class logger
*/
private static Logger logger = LoggerFactory.getLogger(RuleHandlerListener.class);
/**
* The Knowledge sessions sending events
*/
private final RuleBaseStatefulSession ruleBaseSession;
/**
* The rule fired count
*/
private int nbRuleFired = 0;
/**
* the RuleFLowGroup count
*/
private int nbRuleFlowGroupUsed = 0;
/**
* The rule fire limit
*/
private int maxNumberRuleToExecute;
/**
* IfMaxNumberRulewasReached
*/
private boolean maxNumerExecutedRulesReached = false;
public RuleHandlerListener(RuleBaseStatefulSession ruleBaseSession) {
this.ruleBaseSession = ruleBaseSession;
this.maxNumberRuleToExecute = ruleBaseSession.getMaxNumberRuleToExecute();
}
public boolean isMaxNumerExecutedRulesReached() {
return maxNumerExecutedRulesReached;
}
@Override
public void beforeMatchFired(BeforeMatchFiredEvent event) {
logger.debug(">>beforeActivationFired", event);
try {
Match match = event.getMatch();
List<? extends FactHandle> listFact = match.getFactHandles();
//____ Getting the Rule object summary from the session
DroolsRuleObject droolsRuleObject = ruleBaseSession.getDroolsRuleObject(match.getRule());
//____ Creating the specific History event for history managment
BeforeRuleFiredHistoryEvent newBeforeRuleEvent = new BeforeRuleFiredHistoryEvent(this.ruleBaseSession.nextEventId(), this.nbRuleFired + 1, droolsRuleObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
//____ Adding all objects info contained in the Activation object into the history Events
for (FactHandle h : listFact) {
if (h instanceof InternalFactHandle) {
InternalFactHandle defaultFactHandle = (InternalFactHandle) h;
//System.out.println(defaultFactHandle.toString());
if (defaultFactHandle.getObject() instanceof InitialFactImpl) {
// org.drools.reteoo.InitialFactImpl initialFact = (org.drools.reteoo.InitialFactImpl)defaultFactHandle.getObject();
//TODO in case of NOT, OR, etc..
} else {
DroolsFactObject sourceFactObject = ruleBaseSession.getLastFactObjectVersionFromFactHandle(h);
newBeforeRuleEvent.getWhenObjects().add(sourceFactObject);
}
}
}
//_____ Add Event into the History Container
ruleBaseSession.addHistoryElement(newBeforeRuleEvent);
} finally {
logger.debug("<<beforeActivationFired");
}
}
@Override
public void afterMatchFired(AfterMatchFiredEvent event) {
logger.debug(">>afterActivationFired", event);
try {
//____ Increment the global rule fired count
nbRuleFired++;
Match match = event.getMatch();
//____ Getting the Rule Object Summary from the session
DroolsRuleObject droolsRuleObject = ruleBaseSession.getDroolsRuleObject(match.getRule());
//____ Creating the specific "After Rule Fired" History Event
AfterRuleFiredHistoryEvent newAfterRuleEvent = new AfterRuleFiredHistoryEvent(this.ruleBaseSession.nextEventId(), this.nbRuleFired, droolsRuleObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
ruleBaseSession.addHistoryElement(newAfterRuleEvent);
//____ If the max number rule able to be executed threshold is raised, stop the session execution
if (nbRuleFired >= maxNumberRuleToExecute) {
logger.warn(String.format("%d rules have been fired. This is the limit.", maxNumberRuleToExecute));
logger.warn("The session execution will be stop");
KieRuntime runtime = event.getKieRuntime();
this.maxNumerExecutedRulesReached = true;
//(int eventID, int sessionId, int numberOfRulesExecuted, int maxNumberOfRulesForSession)
SessionFireAllRulesMaxNumberReachedEvent sessionFireAllRulesMaxNumberReachedEvent = new SessionFireAllRulesMaxNumberReachedEvent(this.ruleBaseSession.nextEventId(), nbRuleFired, maxNumberRuleToExecute, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
ruleBaseSession.addHistoryElement(sessionFireAllRulesMaxNumberReachedEvent);
runtime.halt();
}
logger.debug("nbre RDG Fired ==> ", nbRuleFired);
} finally {
logger.debug("<<afterActivationFired");
}
}
@Override
public void afterRuleFlowGroupActivated(RuleFlowGroupActivatedEvent ruleFlowGroupActivatedEvent) {
logger.debug(">>afterRuleFlowGroupActivated", ruleFlowGroupActivatedEvent);
try {
String ruleFlowGroupName = null;
//____ Filling the event with the rule flow group name activated
if (ruleFlowGroupActivatedEvent.getRuleFlowGroup() != null && ruleFlowGroupActivatedEvent.getRuleFlowGroup().getName() != null) {
ruleFlowGroupName = ruleFlowGroupActivatedEvent.getRuleFlowGroup().getName();
}
DroolsRuleFlowGroupObject droolsRuleFlowGroupObject = new DroolsRuleFlowGroupObject(this.nbRuleFlowGroupUsed + 1, ruleFlowGroupName);
//____ Creating history event
AfterRuleFlowActivatedHistoryEvent afterRuleFlowActivatedHistoryEvent = new AfterRuleFlowActivatedHistoryEvent(this.ruleBaseSession.nextEventId(), droolsRuleFlowGroupObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
//____ Adding into the History container
ruleBaseSession.addHistoryElement(afterRuleFlowActivatedHistoryEvent);
} finally {
logger.debug("<<afterRuleFlowGroupActivated");
}
}
@Override
public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent ruleFlowGroupDeactivatedEvent) {
logger.debug(">>afterRuleFlowGroupDeactivated", ruleFlowGroupDeactivatedEvent);
try {
String ruleFlowGroupName = null;
if (ruleFlowGroupDeactivatedEvent.getRuleFlowGroup() != null && ruleFlowGroupDeactivatedEvent.getRuleFlowGroup().getName() != null) {
ruleFlowGroupName = ruleFlowGroupDeactivatedEvent.getRuleFlowGroup().getName();
}
this.nbRuleFlowGroupUsed++;
DroolsRuleFlowGroupObject droolsRuleFlowGroupObject = new DroolsRuleFlowGroupObject(this.nbRuleFlowGroupUsed, ruleFlowGroupName);
//____ Creating history event
AfterRuleFlowDeactivatedHistoryEvent afterRuleFlowGroupDeactivated = new AfterRuleFlowDeactivatedHistoryEvent(this.ruleBaseSession.nextEventId(), droolsRuleFlowGroupObject, this.ruleBaseSession.getRuleBaseID(), this.ruleBaseSession.getSessionId());
//_____ Adding the event to the History container
ruleBaseSession.addHistoryElement(afterRuleFlowGroupDeactivated);
} finally {
logger.debug("<<afterRuleFlowGroupDeactivated");
}
}
public int getNbRuleFired() {
return nbRuleFired;
}
}

View file

@ -0,0 +1,135 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime.resource;
import com.google.common.base.Throwables;
import org.apache.commons.io.IOUtils;
import org.chtijbug.drools.entity.history.KnowledgeResource;
import org.kie.api.io.Resource;
import org.kie.internal.io.ResourceFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by IntelliJ IDEA.
* Date: 23/01/14
* Time: 15:40
* To change this template use File | Settings | File Templates.
*/
public class FileKnowledgeResource implements Serializable, KnowledgeResource {
private String content;
private String path;
private boolean bpmn2;
private Resource resource;
public FileKnowledgeResource(String content, String path, boolean bpmn2, Resource resource) {
this.content = content;
this.path = path;
this.bpmn2 = bpmn2;
this.resource = resource;
}
public FileKnowledgeResource(Resource resource, String path, String fileContent) {
this.content = fileContent;
this.path = path;
this.resource = resource;
this.bpmn2 = true;
}
public FileKnowledgeResource() {
}
public static FileKnowledgeResource createFileSystemPathResource(String path) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
String fileContent = IOUtils.toString(inputStream);
return new FileKnowledgeResource(ResourceFactory.newFileResource(path), path, fileContent);
} catch (IOException ex) {
Logger.getLogger(FileKnowledgeResource.class.getName()).log(Level.SEVERE, null, ex);
throw Throwables.propagate(ex);
}
}
public static FileKnowledgeResource createBPMN2ClassPathResource(String path) {
FileKnowledgeResource bpmn2Resource = createDRLClassPathResource(path);
bpmn2Resource.setBpmn2(true);
return bpmn2Resource;
}
public static FileKnowledgeResource createDRLClassPathResource(String path) {
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
InputStream inputStream;
if (classLoader == null) {
inputStream = FileKnowledgeResource.class.getResourceAsStream("/" + path);
} else {
inputStream = classLoader.getResourceAsStream(path);
}
String fileContent = null;
try {
fileContent = IOUtils.toString(inputStream);
} catch (IOException ex) {
Logger.getLogger(FileKnowledgeResource.class.getName()).log(Level.SEVERE, null, ex);
throw Throwables.propagate(ex);
}
return new FileKnowledgeResource(ResourceFactory.newClassPathResource(path), path, fileContent);
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isBpmn2() {
return bpmn2;
}
public void setBpmn2(boolean bpmn2) {
this.bpmn2 = bpmn2;
}
public Resource getResource() {
return resource;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("DrlRessourceFile{");
sb.append("fileName='").append(path).append('\'');
sb.append(", content='").append(content).append('\'');
sb.append('}');
return sb.toString();
}
}

View file

@ -0,0 +1,154 @@
package org.chtijbug.drools.runtime.resource;
import org.chtijbug.drools.entity.history.EventCounter;
import org.chtijbug.drools.entity.history.knowledge.KnowledgeBaseAddResourceEvent;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.listener.HistoryListener;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.io.KieResources;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import java.util.Date;
import java.util.List;
import static com.google.common.base.Throwables.propagate;
public class KnowledgeModule {
private final String groupId;
private final String artifactId;
private final String version;
private final KieServices kieServices;
private String ruleBaseName;
private final KieResources kieResources;
private final KieFileSystem kieFileSystem;
private final KieRepository kieRepository;
private final HistoryListener historyListener;
private final EventCounter sharedCounter;
private final Long ruleBaseId;
private ReleaseId releaseId;
private boolean fileBaseModule = false;
private WorkbenchClient workbenchClient;
public KnowledgeModule(Long ruleBaseId, HistoryListener historyListener, String groupId, String artifactId, String version, EventCounter sharedCounter) {
this.ruleBaseId = ruleBaseId;
this.historyListener = historyListener;
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.kieServices = KieServices.Factory.get();
this.kieRepository = kieServices.getRepository();
this.kieResources = kieServices.getResources();
this.kieFileSystem = kieServices.newKieFileSystem();
this.sharedCounter = sharedCounter;
}
public KnowledgeModule(String ruleBaseName, HistoryListener historyListener, EventCounter sharedCounter) {
this.ruleBaseName = ruleBaseName;
this.historyListener = historyListener;
this.groupId = null;
this.artifactId = null;
this.version = null;
this.kieServices = KieServices.Factory.get();
this.kieRepository = kieServices.getRepository();
this.kieResources = kieServices.getResources();
this.kieFileSystem = kieServices.newKieFileSystem();
this.sharedCounter = sharedCounter;
this.ruleBaseId = 1L;
}
public KnowledgeModule(Long ruleBaseId, HistoryListener historyListener, EventCounter sharedCounter) {
this.ruleBaseId = ruleBaseId;
this.historyListener = historyListener;
this.groupId = null;
this.artifactId = null;
this.version = null;
this.kieServices = KieServices.Factory.get();
this.kieRepository = kieServices.getRepository();
this.kieResources = kieServices.getResources();
this.kieFileSystem = kieServices.newKieFileSystem();
this.sharedCounter = sharedCounter;
}
public void addAllFiles(List<FileKnowledgeResource> files) {
for (FileKnowledgeResource file : files) {
addRuleFile(groupId + ".rules", file);
}
}
public void addRuleFile(String packageName, FileKnowledgeResource ruleResource) {
this.fileBaseModule = true;
packageName = packageName.replace(".", "/");
String resourcePath = "src/main/resources/" + packageName + "/" + ruleResource.getPath();
kieFileSystem.write(resourcePath, ruleResource.getResource());
if (historyListener != null)
try {
historyListener.fireEvent(
new KnowledgeBaseAddResourceEvent(
sharedCounter.next(), new Date(), this.ruleBaseId, ruleResource));
} catch (DroolsChtijbugException e) {
throw propagate(e);
}
}
public KieContainer build() {
this.releaseId = kieServices.newReleaseId(groupId, artifactId, version);
if (fileBaseModule) {
this.kieFileSystem.generateAndWritePomXML(releaseId);
KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
kb.buildAll();
if (kb.getResults().hasMessages(Message.Level.ERROR)) {
throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
}
}
return this.kieServices.newKieContainer(releaseId);
}
public KieContainer buildFromClassPath(ClassLoader classLoader) {
return this.kieServices.getKieClasspathContainer(classLoader);
}
public KieContainer buildFromClassPath() {
return this.kieServices.getKieClasspathContainer();
}
public void addWorkbenchResource(String workbenchUrl, String username, String password) {
try (WorkbenchClient client = new WorkbenchClient(workbenchUrl, username, password)) {
this.workbenchClient = client;
Resource resource = kieServices.getResources().newInputStreamResource(client.getWorkbenchResource(this));
this.kieRepository.addKieModule(resource);
if (historyListener != null)
try {
WorkbenchKnowledgeResource workbenchRuleResource = new WorkbenchKnowledgeResource(workbenchUrl, this.groupId, this.artifactId, this.version);
historyListener.fireEvent(
new KnowledgeBaseAddResourceEvent(
sharedCounter.next(), new Date(), this.ruleBaseId,
workbenchRuleResource));
} catch (DroolsChtijbugException e) {
throw propagate(e);
}
}
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
public WorkbenchClient getWorkbenchClient() {
return workbenchClient;
}
}

View file

@ -0,0 +1,75 @@
package org.chtijbug.drools.runtime.resource;
import com.google.common.base.Throwables;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import static org.apache.http.client.utils.HttpClientUtils.closeQuietly;
public class WorkbenchClient implements Closeable {
private final CloseableHttpClient httpClient;
private final String workbenchUrl;
private CloseableHttpResponse response;
private String username;
private String password;
public WorkbenchClient(String workbenchUrl, String username, String password) {
this.workbenchUrl = workbenchUrl;
this.username = username;
this.password = password;
try {
URI submittedURI = new URI(workbenchUrl);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(submittedURI.getHost(), submittedURI.getPort()),
new UsernamePasswordCredentials(username, password)
);
this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
} catch (URISyntaxException e) {
throw Throwables.propagate(e);
}
}
public InputStream getWorkbenchResource(KnowledgeModule knowledgeModule) {
// Build up url
String url = workbenchUrl + "maven2/" + knowledgeModule.getGroupId().replaceAll("\\.", "/") + "/" + knowledgeModule.getArtifactId() + "/" + knowledgeModule.getVersion() + "/" + knowledgeModule.getArtifactId() + "-" + knowledgeModule.getVersion() + ".jar";
HttpGet httpget = new HttpGet(url);
this.response = null;
try {
response = httpClient.execute(httpget);
return response.getEntity().getContent();
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
public void close() {
closeQuietly(this.response);
closeQuietly(this.httpClient);
}
public String getWorkbenchUrl() {
return workbenchUrl;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}

View file

@ -0,0 +1,121 @@
/*
* Copyright 2014 Pymma Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime.resource;
import org.chtijbug.drools.entity.history.KnowledgeResource;
import java.io.Serializable;
/**
* Created by IntelliJ IDEA.
* Date: 23/01/14
* Time: 15:40
* To change this template use File | Settings | File Templates.
*/
public class WorkbenchKnowledgeResource implements Serializable, KnowledgeResource {
private String guvnor_url;
private String groupId;
private String artifactID;
private String version;
private String userName;
private String password;
public WorkbenchKnowledgeResource(String guvnor_url, String groupId, String artifactID, String version) {
this.guvnor_url = guvnor_url;
this.groupId = groupId;
this.artifactID = artifactID;
this.version = version;
}
public WorkbenchKnowledgeResource(String guvnor_url, String groupId, String artifactId, String version, String userName, String password) {
this(guvnor_url, groupId, artifactId, version);
this.userName = userName;
this.password = password;
}
public WorkbenchKnowledgeResource() {
}
public static WorkbenchKnowledgeResource createGuvnorRessource(String guvnor_url, String groupId, String artifactID, String version) {
return new WorkbenchKnowledgeResource(guvnor_url, groupId, artifactID, version);
}
public static WorkbenchKnowledgeResource createGuvnorRessource(String guvnor_url, String groupId, String artifactID, String version, String userName, String password) {
return new WorkbenchKnowledgeResource(guvnor_url, groupId, artifactID, version, userName, password);
}
public String getGuvnor_url() {
return guvnor_url;
}
public void setGuvnor_url(String guvnor_url) {
this.guvnor_url = guvnor_url;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactID() {
return artifactID;
}
public void setArtifactID(String artifactID) {
this.artifactID = artifactID;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("GuvnorRessourceFile{");
sb.append("guvnor_url='").append(guvnor_url).append('\'');
sb.append('}');
return sb.toString();
}
}

View file

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="Definition"
targetNamespace="http://www.jboss.org/drools"
typeLanguage="http://www.java.com/javaTypes"
expressionLanguage="http://www.mvel.org/2.0"
xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"
xmlns:g="http://www.jboss.org/drools/flow/gpd"
xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
xmlns:dc="http://www.omg.org/spec/DD/20100524/DC"
xmlns:di="http://www.omg.org/spec/DD/20100524/DI"
xmlns:tns="http://www.jboss.org/drools">
<process processType="Private" isExecutable="true" id="P1" artifactId="Hello World" tns:groupId="org.chtijbug.drools.runtime.test" >
<!-- nodes -->
<startEvent id="_1" artifactId="StartProcess" />
<endEvent id="_3" artifactId="EndProcess" />
<businessRuleTask id="_4" artifactId="Group1" g:ruleFlowGroup="Group1" >
</businessRuleTask>
<businessRuleTask id="_5" artifactId="Group2" g:ruleFlowGroup="Group2" >
</businessRuleTask>
<!-- connections -->
<sequenceFlow id="_5-_3" sourceRef="_5" targetRef="_3" />
<sequenceFlow id="_1-_4" sourceRef="_1" targetRef="_4" />
<sequenceFlow id="_4-_5" sourceRef="_4" targetRef="_5" />
</process>
<bpmndi:BPMNDiagram>
<bpmndi:BPMNPlane bpmnElement="P1" >
<bpmndi:BPMNShape bpmnElement="_1" >
<dc:Bounds x="16" y="16" width="48" height="48" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="_3" >
<dc:Bounds x="462" y="28" width="48" height="48" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="_4" >
<dc:Bounds x="161" y="64" width="80" height="48" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="_5" >
<dc:Bounds x="304" y="50" width="80" height="48" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="_5-_3" >
<di:waypoint x="344" y="74" />
<di:waypoint x="486" y="52" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="_1-_4" >
<di:waypoint x="40" y="40" />
<di:waypoint x="201" y="88" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="_4-_5" >
<di:waypoint x="201" y="88" />
<di:waypoint x="344" y="74" />
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>

View file

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:change-set="http://drools.org/drools-5.0/change-set"
elementFormDefault="qualified"
targetNamespace="http://drools.org/drools-5.0/change-set">
<xsd:import namespace="http://www.w3.org/2001/XMLSchema-instance"/>
<xsd:element artifactId="change-set">
<xsd:complexType>
<xsd:choice>
<xsd:element ref="change-set:add"/>
<xsd:element ref="change-set:remove"/>
</xsd:choice>
</xsd:complexType>
</xsd:element>
<xsd:element artifactId="add">
<xsd:complexType mixed="true">
<xsd:sequence>
<xsd:element minOccurs="0" maxOccurs="unbounded" ref="change-set:resource"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element artifactId="remove">
<xsd:complexType mixed="true">
<xsd:sequence>
<xsd:element minOccurs="0" maxOccurs="unbounded" ref="change-set:resource"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element artifactId="resource">
<xsd:complexType>
<xsd:sequence>
<xsd:any minOccurs="0"/>
<xsd:element minOccurs="0" ref="change-set:decisiontable-conf"/>
</xsd:sequence>
<!-- URL to the resource, can be file based -->
<xsd:attribute artifactId="source" use="required" type="xsd:anyURI"/>
<!-- for example, DRL, or PKG -->
<xsd:attribute artifactId="type" use="required" type="xsd:string"/>
<xsd:attribute artifactId="basicAuthentication" type="xsd:string"/>
<xsd:attribute artifactId="username" type="xsd:string"/>
<xsd:attribute artifactId="password" type="xsd:string"/>
</xsd:complexType>
</xsd:element>
<xsd:element artifactId="decisiontable-conf">
<xsd:complexType>
<xsd:attribute artifactId="input-type" use="required" type="xsd:NCName"/>
<xsd:attribute artifactId="worksheet-artifactId" use="required" type="xsd:NCName"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>

View file

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<change-set xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://drools.org/drools-5.0/change-set"
xsi:schemaLocation="http://drools.org/drools-5.0/change-set changeset-1.0.0.xsd">
<add>
<resource
type="PKG"
source="%s"
basicAuthentication="enabled"
username="%s"
password="%s">
</resource>
</add>
</change-set>

View file

@ -0,0 +1,49 @@
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chtijbug.drools.runtime
import org.chtijbug.drools.runtime.Fibonacci;
dialect "mvel"
rule Recurse
salience 10
when
not ( Fibonacci ( sequence == 1 ) )
f : Fibonacci ( value == -1 )
then
insert( new Fibonacci( f.sequence - 1 ) );
System.out.println( "recurse for " + f.sequence );
end
rule Bootstrap
when
f : Fibonacci( sequence == 1 || == 2, value == -1 ) // this is a multi-restriction || on a single field
then
modify ( f ){ value = 1 };
System.out.println( f.sequence + " == " + f.value );
end
rule Calculate
when
f1 : Fibonacci( s1 : sequence, value != -1 ) // here we bind sequence
f2 : Fibonacci( sequence == (s1 + 1 ), value != -1 ) // here we don't, just to demonstrate the different way bindings can be used
f3 : Fibonacci( s3 : sequence == (f2.sequence + 1 ), value == -1 )
then
modify ( f3 ) { value = f1.value + f2.value };
System.out.println( s3 + " == " + f3.value ); // see how you can access pattern and field bindings
end

View file

@ -0,0 +1,26 @@
package org.chtijbug.drools.runtime.test
import org.chtijbug.drools.runtime.Fibonacci;
rule "Account group1"
no-loop
ruleflow-group "Group1"
when
f : Fibonacci(sequence==0 )
then
update(f);
insert( new Fibonacci( 1 ) );
end
rule "Account group2"
ruleflow-group "Group2"
when
f : Fibonacci(sequence==1 )
then
retract(f);
insert( new Fibonacci( 2 ) );
end