use of org.akaza.openclinica.domain.rule.expression.ExpressionBean in project OpenClinica by OpenClinica.
the class ImportDataRuleRunner method populateToBeExpected.
@Transactional
private HashMap<String, ArrayList<RuleActionContainer>> populateToBeExpected(ImportDataRuleRunnerContainer container, StudyBean study, UserAccountBean ub) {
//copied code for toBeExpected from DataEntryServlet runRules
HashMap<String, ArrayList<RuleActionContainer>> toBeExecuted = new HashMap<String, ArrayList<RuleActionContainer>>();
HashMap<String, String> variableAndValue = (HashMap<String, String>) container.getVariableAndValue();
if (variableAndValue == null || variableAndValue.isEmpty()) {
logger.warn("No rule target item with value found.");
return toBeExecuted;
}
List<RuleSetBean> ruleSets = container.getImportDataTrueRuleSets();
for (RuleSetBean ruleSet : ruleSets) {
String key = getExpressionService().getItemOid(ruleSet.getOriginalTarget().getValue());
List<RuleActionContainer> allActionContainerListBasedOnRuleExecutionResult = null;
if (toBeExecuted.containsKey(key)) {
allActionContainerListBasedOnRuleExecutionResult = toBeExecuted.get(key);
} else {
toBeExecuted.put(key, new ArrayList<RuleActionContainer>());
allActionContainerListBasedOnRuleExecutionResult = toBeExecuted.get(key);
}
ItemDataBean itemData = null;
for (ExpressionBean expressionBean : ruleSet.getExpressions()) {
ruleSet.setTarget(expressionBean);
for (RuleSetRuleBean ruleSetRule : ruleSet.getRuleSetRules()) {
String result = null;
RuleBean rule = ruleSetRule.getRuleBean();
//ExpressionObjectWrapper eow = new ExpressionObjectWrapper(ds, currentStudy, rule.getExpression(), ruleSet, variableAndValue,ecb);
ExpressionObjectWrapper eow = new ExpressionObjectWrapper(ds, study, rule.getExpression(), ruleSet, variableAndValue);
try {
OpenClinicaExpressionParser oep = new OpenClinicaExpressionParser(eow);
result = (String) oep.parseAndEvaluateExpression(rule.getExpression().getValue());
itemData = getExpressionService().getItemDataBeanFromDb(ruleSet.getTarget().getValue());
// Actions
List<RuleActionBean> actionListBasedOnRuleExecutionResult = ruleSetRule.getActions(result, Phase.IMPORT);
if (itemData != null) {
Iterator<RuleActionBean> itr = actionListBasedOnRuleExecutionResult.iterator();
//String firstDDE = "firstDDEInsert_"+ruleSetRule.getOid()+"_"+itemData.getId();
while (itr.hasNext()) {
RuleActionBean ruleActionBean = itr.next();
/*
if(ruleActionBean.getActionType()==ActionType.INSERT) {
request.setAttribute("insertAction", true);
if(phase==Phase.DOUBLE_DATA_ENTRY && itemData.getStatus().getId()==4
&& request.getAttribute(firstDDE)==null) {
request.setAttribute(firstDDE, true);
}
}
if(request.getAttribute(firstDDE)==Boolean.TRUE) {
} else {
*/
String itemDataValueFromImport = "";
if (variableAndValue.containsKey(key)) {
itemDataValueFromImport = variableAndValue.get(key);
} else {
logger.info("Cannot find value from variableAndValue for item=" + key + ". " + "Used itemData.getValue()");
itemDataValueFromImport = itemData.getValue();
}
RuleActionRunLogBean ruleActionRunLog = new RuleActionRunLogBean(ruleActionBean.getActionType(), itemData, itemDataValueFromImport, ruleSetRule.getRuleBean().getOid());
if (getRuleActionRunLogDao().findCountByRuleActionRunLogBean(ruleActionRunLog) > 0) {
itr.remove();
}
//}
}
}
for (RuleActionBean ruleActionBean : actionListBasedOnRuleExecutionResult) {
RuleActionContainer ruleActionContainer = new RuleActionContainer(ruleActionBean, expressionBean, itemData, ruleSet);
allActionContainerListBasedOnRuleExecutionResult.add(ruleActionContainer);
}
logger.info("RuleSet with target : {} , Ran Rule : {} The Result was : {} , Based on that {} action will be executed. ", new Object[] { ruleSet.getTarget().getValue(), rule.getName(), result, actionListBasedOnRuleExecutionResult.size() });
} catch (OpenClinicaSystemException osa) {
// TODO: report something useful
}
}
}
}
return toBeExecuted;
}
use of org.akaza.openclinica.domain.rule.expression.ExpressionBean in project OpenClinica by OpenClinica.
the class BeanPropertyRuleRunner method runRules.
public void runRules(List<RuleSetBean> ruleSets, DataSource ds, BeanPropertyService beanPropertyService, StudyEventDao studyEventDaoHib, StudyEventDefinitionDao studyEventDefDaoHib, StudyEventChangeDetails changeDetails, Integer userId, JavaMailSenderImpl mailSender) {
for (RuleSetBean ruleSet : ruleSets) {
List<ExpressionBean> expressions = ruleSet.getExpressions();
for (ExpressionBean expressionBean : expressions) {
ruleSet.setTarget(expressionBean);
StudyEvent studyEvent = studyEventDaoHib.findByStudyEventId(Integer.valueOf(getExpressionService().getStudyEventDefenitionOrdninalCurated(ruleSet.getTarget().getValue())));
int eventOrdinal = studyEvent.getSampleOrdinal();
int studySubjectBeanId = studyEvent.getStudySubject().getStudySubjectId();
List<RuleSetRuleBean> ruleSetRules = ruleSet.getRuleSetRules();
for (RuleSetRuleBean ruleSetRule : ruleSetRules) {
Object result = null;
if (ruleSetRule.getStatus() == Status.AVAILABLE) {
RuleBean rule = ruleSetRule.getRuleBean();
// StudyBean currentStudy = rule.getStudy();//TODO:Fix me!
StudyDAO sdao = new StudyDAO(ds);
StudyBean currentStudy = (StudyBean) sdao.findByPK(rule.getStudyId());
ExpressionBeanObjectWrapper eow = new ExpressionBeanObjectWrapper(ds, currentStudy, rule.getExpression(), ruleSet, studySubjectBeanId, studyEventDaoHib, studyEventDefDaoHib);
try {
// StopWatch sw = new StopWatch();
ExpressionObjectWrapper ew = new ExpressionObjectWrapper(ds, currentStudy, rule.getExpression(), ruleSet);
ew.setStudyEventDaoHib(studyEventDaoHib);
ew.setStudySubjectId(studySubjectBeanId);
ew.setExpressionContext(ExpressionObjectWrapper.CONTEXT_EXPRESSION);
OpenClinicaExpressionParser oep = new OpenClinicaExpressionParser(ew);
// eow.setUserAccountBean(ub);
eow.setStudyBean(currentStudy);
result = oep.parseAndEvaluateExpression(rule.getExpression().getValue());
// sw.stop();
logger.debug("Rule Expression Evaluation Result: " + result);
// Actions
List<RuleActionBean> actionListBasedOnRuleExecutionResult = ruleSetRule.getActions(result.toString());
for (RuleActionBean ruleActionBean : actionListBasedOnRuleExecutionResult) {
// ActionProcessor ap =ActionProcessorFacade.getActionProcessor(ruleActionBean.getActionType(), ds, null, null,ruleSet, null, ruleActionBean.getRuleSetRule());
if (ruleActionBean instanceof EventActionBean) {
beanPropertyService.runAction(ruleActionBean, eow, userId, changeDetails.getRunningInTransaction());
} else if (ruleActionBean instanceof NotificationActionBean) {
notificationActionProcessor = new NotificationActionProcessor(ds, mailSender, ruleSetRule);
notificationActionProcessor.runNotificationAction(ruleActionBean, ruleSet, studySubjectBeanId, eventOrdinal);
}
}
} catch (OpenClinicaSystemException osa) {
// osa.printStackTrace();
logger.error("Rule Runner received exception: " + osa.getMessage());
logger.error(ExceptionUtils.getStackTrace(osa));
// TODO: report something useful
}
}
}
// }
}
}
}
use of org.akaza.openclinica.domain.rule.expression.ExpressionBean in project OpenClinica by OpenClinica.
the class Key method runRulesBulkOLD.
@Deprecated
public HashMap<RuleBulkExecuteContainer, HashMap<RuleBulkExecuteContainerTwo, Set<String>>> runRulesBulkOLD(List<RuleSetBean> ruleSets, ExecutionMode executionMode, StudyBean currentStudy, HashMap<String, String> variableAndValue, UserAccountBean ub) {
if (variableAndValue == null || variableAndValue.isEmpty()) {
logger.warn("You must be executing Rules in Batch");
variableAndValue = new HashMap<String, String>();
}
HashMap<RuleBulkExecuteContainer, HashMap<RuleBulkExecuteContainerTwo, Set<String>>> crfViewSpecificOrderedObjects = new HashMap<RuleBulkExecuteContainer, HashMap<RuleBulkExecuteContainerTwo, Set<String>>>();
for (RuleSetBean ruleSet : ruleSets) {
for (ExpressionBean expressionBean : ruleSet.getExpressions()) {
ruleSet.setTarget(expressionBean);
for (RuleSetRuleBean ruleSetRule : ruleSet.getRuleSetRules()) {
String result = null;
RuleBean rule = ruleSetRule.getRuleBean();
ExpressionObjectWrapper eow = new ExpressionObjectWrapper(ds, currentStudy, rule.getExpression(), ruleSet, variableAndValue);
try {
OpenClinicaExpressionParser oep = new OpenClinicaExpressionParser(eow);
result = (String) oep.parseAndEvaluateExpression(rule.getExpression().getValue());
// Actions
List<RuleActionBean> actionListBasedOnRuleExecutionResult = ruleSetRule.getActions(result, Phase.BATCH);
ItemDataBean itemData = getExpressionService().getItemDataBeanFromDb(ruleSet.getTarget().getValue());
if (itemData != null) {
Iterator<RuleActionBean> itr = actionListBasedOnRuleExecutionResult.iterator();
while (itr.hasNext()) {
RuleActionBean ruleActionBean = itr.next();
RuleActionRunLogBean ruleActionRunLog = new RuleActionRunLogBean(ruleActionBean.getActionType(), itemData, itemData.getValue(), ruleSetRule.getRuleBean().getOid());
if (getRuleActionRunLogDao().findCountByRuleActionRunLogBean(ruleActionRunLog) > 0) {
itr.remove();
}
}
}
List<RuleActionBean> actionBeansToShow = new ArrayList<RuleActionBean>();
if (actionListBasedOnRuleExecutionResult.size() > 0) {
//if (!dryRun) {
for (RuleActionBean ruleAction : actionListBasedOnRuleExecutionResult) {
ruleAction.setCuratedMessage(curateMessage(ruleAction, ruleSetRule));
// getDiscrepancyNoteService().saveFieldNotes(ruleAction.getSummary(), itemDataBeanId, "ItemData", currentStudy, ub);
ActionProcessor ap = ActionProcessorFacade.getActionProcessor(ruleAction.getActionType(), ds, getMailSender(), dynamicsMetadataService, ruleSet, getRuleActionRunLogDao(), ruleSetRule);
RuleActionBean rab = ap.execute(RuleRunnerMode.RULSET_BULK, executionMode, ruleAction, itemData, DiscrepancyNoteBean.ITEM_DATA, currentStudy, ub, prepareEmailContents(ruleSet, ruleSetRule, currentStudy, ruleAction));
if (rab != null) {
actionBeansToShow.add(ruleAction);
}
}
if (actionBeansToShow.size() > 0) {
crfViewSpecificOrderedObjects = populateForCrfBasedRulesView(crfViewSpecificOrderedObjects, ruleSet, rule, result, currentStudy, actionBeansToShow);
}
}
} catch (OpenClinicaSystemException osa) {
String errorMessage = "RuleSet with target : " + ruleSet.getTarget().getValue() + " , Ran Rule : " + rule.getName() + " , It resulted in an error due to : " + osa.getMessage();
// log error
logger.warn(errorMessage);
}
}
}
}
logCrfViewSpecificOrderedObjects(crfViewSpecificOrderedObjects);
return crfViewSpecificOrderedObjects;
}
use of org.akaza.openclinica.domain.rule.expression.ExpressionBean in project OpenClinica by OpenClinica.
the class OpenRosaXmlGenerator method getSkipPattern.
/**
* For Skip Pattern
*
* @param itemBean
* @param itemGroupBean
* @return
*/
private ExpressionExpressionEvaluate getSkipPattern(ItemBean itemBean, ItemGroupBean itemGroupBean) {
ExpressionExpressionEvaluate eev = new ExpressionExpressionEvaluate();
boolean expressionEvaluate = true;
String expression = null;
ExpressionBean expressionBean = null;
ArrayList<PropertyBean> propertyBeans = null;
if (itemBean == null) {
propertyBeans = getGroupPropertyBean(itemGroupBean.getOid());
} else {
propertyBeans = getItemGroupPropertyBean(itemBean.getOid(), itemGroupBean.getOid());
}
if (propertyBeans.size() != 0) {
for (PropertyBean propertyBean : propertyBeans) {
logger.info("property bean oid: " + propertyBean.getOid());
RuleActionBean ruleActionBean = propertyBean.getRuleActionBean();
if (ruleActionBean.getActionType().getCode() == 3 && ruleActionBean.getRuleSetRule().getStatus().getCode() == 1) {
expressionBean = ruleActionBean.getRuleSetRule().getRuleBean().getExpression();
expressionEvaluate = ruleActionBean.getExpressionEvaluatesTo();
logger.info(" ExpressionBean: " + expressionBean.getValue());
if (expression != null) {
expression = expression + " and " + expressionBean.getValue();
} else {
expression = expressionBean.getValue();
}
}
}
}
eev.setExpressionEvaluate(expressionEvaluate);
eev.setExpression(expression);
return eev;
}
use of org.akaza.openclinica.domain.rule.expression.ExpressionBean in project OpenClinica by OpenClinica.
the class TestRuleServlet method validate.
private HashMap<String, String> validate(Validator v) throws ParseException {
FormProcessor fp = new FormProcessor(request);
String targetString = fp.getString("target");
String ruleString = fp.getString("rule");
ruleString = ruleString.trim().replaceAll("(\n|\t|\r)", " ");
targetString = targetString.trim().replaceAll("(\n|\t|\r)", "");
HashMap<String, String> p = session.getAttribute("testValues") != null ? (HashMap<String, String>) session.getAttribute("testValues") : new HashMap<String, String>();
if (p != null) {
for (Map.Entry<String, String> entry : p.entrySet()) {
entry.setValue(fp.getString(entry.getKey()));
if (entry.getKey().startsWith(ExpressionService.STUDY_EVENT_OID_START_KEY) && (entry.getKey().endsWith(ExpressionService.STATUS) || entry.getKey().endsWith(ExpressionService.STARTDATE))) {
StudyEventDefinitionBean sed = getExpressionService().getStudyEventDefinitionFromExpressionForEvents(entry.getKey(), currentStudy);
if (entry.getKey().endsWith(ExpressionService.STATUS)) {
//TODO add the logic for status
} else if (entry.getKey().endsWith(ExpressionService.STARTDATE)) {
try {
v.addValidation(entry.getKey(), Validator.IS_A_DATE);
SimpleDateFormat sdf = new SimpleDateFormat(resformat.getString("date_format_string"));
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
if (!entry.getValue().isEmpty()) {
java.util.Date date = sdf2.parse(entry.getValue());
entry.setValue(sdf.format(date));
}
} catch (Exception e) {
logger.error(e.toString());
// TODO: handle exception
}
}
} else {
ItemBean item = getExpressionService().getItemBeanFromExpression(entry.getKey());
List<ItemFormMetadataBean> itemFormMetadataBeans = getItemFormMetadataDAO().findAllByItemId(item.getId());
ItemFormMetadataBean itemFormMetadataBean = itemFormMetadataBeans.size() > 0 ? itemFormMetadataBeans.get(0) : null;
if (!entry.getValue().equals("") && NullValue.getByName(entry.getValue()) == NullValue.INVALID) {
if (itemFormMetadataBean != null) {
if (itemFormMetadataBean.getResponseSet().getResponseType() == ResponseType.SELECTMULTI || itemFormMetadataBean.getResponseSet().getResponseType() == ResponseType.CHECKBOX) {
v.addValidation(entry.getKey(), Validator.IN_RESPONSE_SET_COMMA_SEPERATED, itemFormMetadataBean.getResponseSet());
}
if (itemFormMetadataBean.getResponseSet().getResponseType() == ResponseType.SELECT || itemFormMetadataBean.getResponseSet().getResponseType() == ResponseType.RADIO) {
v.addValidation(entry.getKey(), Validator.IN_RESPONSE_SET_SINGLE_VALUE, itemFormMetadataBean.getResponseSet());
} else {
itemDataTypeToValidatorId(entry.getKey(), item, v);
}
}
}
if (item.getItemDataTypeId() == 9) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(resformat.getString("date_format_string"));
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
if (!entry.getValue().isEmpty()) {
java.util.Date date = sdf.parse(entry.getValue());
entry.setValue(sdf2.format(date));
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}
List<RuleActionBean> actions = session.getAttribute("testRuleActions") != null ? (List<RuleActionBean>) session.getAttribute("testRuleActions") : new ArrayList<RuleActionBean>();
if (actions != null) {
for (int i = 0; i < actions.size(); i++) {
actions.get(i).setExpressionEvaluatesTo(fp.getBoolean("actions" + i));
}
}
// Check Target if not valid report and return
try {
getExpressionService().ruleSetExpressionChecker(targetString);
} catch (OpenClinicaSystemException e) {
HashMap<String, String> result = new HashMap<String, String>();
MessageFormat mf = new MessageFormat("");
mf.applyPattern(respage.getString(e.getErrorCode()));
Object[] arguments = e.getErrorParams();
result.put("ruleValidation", "target_invalid");
result.put("ruleValidationFailMessage", e.getErrorCode() + " : " + mf.format(arguments));
result.put("ruleEvaluatesTo", "");
request.setAttribute("targetFail", "on");
return result;
}
// Auto update itemName & itemDefinition based on target
ItemBean item = getExpressionService().getItemBeanFromExpression(targetString);
StudyEventDefinitionBean sed = null;
if (item != null) {
request.setAttribute("itemName", item.getName());
request.setAttribute("itemDefinition", item.getDescription());
} else {
sed = getExpressionService().getStudyEventDefinitionFromExpressionForEvents(targetString, currentStudy);
if (sed != null) {
request.setAttribute("itemName", sed.getName());
request.setAttribute("itemDefinition", sed.getDescription());
}
}
RuleSetBean ruleSet = new RuleSetBean();
ExpressionBean target = new ExpressionBean();
target.setContext(Context.OC_RULES_V1);
target.setValue(targetString);
ruleSet.setTarget(target);
RuleSetBean persistentRuleSet = getRuleSetDao().findByExpressionAndStudy(ruleSet, currentStudy.getId());
if (persistentRuleSet != null) {
if (item != null)
request.setAttribute("ruleSetId", item.getId());
else
request.setAttribute("ruleSetId", sed.getId());
}
ExpressionBean rule = new ExpressionBean();
rule.setContext(Context.OC_RULES_V1);
rule.setValue(ruleString);
ExpressionObjectWrapper eow = new ExpressionObjectWrapper(sm.getDataSource(), currentStudy, rule, ruleSet);
ExpressionProcessor ep = ExpressionProcessorFactory.createExpressionProcessor(eow);
ep.setRespage(respage);
// Run expression with populated HashMap
DateTime start = new DateTime();
HashMap<String, String> result = ep.testEvaluateExpression(p);
DateTime end = new DateTime();
Duration dur = new Duration(start, end);
PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder().printZeroAlways().appendSecondsWithMillis().appendSuffix(" second", " seconds").toFormatter();
yearsAndMonths.print(dur.toPeriod());
// Run expression with empty HashMap to check rule validity, because
// using illegal test values will cause invalidity
HashMap<String, String> k = new HashMap<String, String>();
HashMap<String, String> theResult = ep.testEvaluateExpression(k);
if (theResult.get("ruleValidation").equals("rule_valid") && result.get("ruleValidation").equals("rule_invalid")) {
result.put("ruleValidation", "rule_valid");
result.put("ruleEvaluatesTo", resword.getString("test_rules_rule_fail") + " " + result.get("ruleValidationFailMessage"));
result.remove("ruleValidationFailMessage");
}
// Put on screen
request.setAttribute("duration", yearsAndMonths.print(dur.toPeriod()));
return result;
}
Aggregations