private RuleSetBean getRuleSet(String ruleOid, String target, String oidRef) {
   RuleSetBean ruleSet = new RuleSetBean();
   ruleSet.setTarget(createExpression(Context.OC_RULES_V1, target));
   ruleSet.setOriginalTarget(createExpression(Context.OC_RULES_V1, target));
   RuleSetRuleBean ruleSetRule = createRuleSetRule(ruleSet, ruleOid, oidRef);
   ruleSet.addRuleSetRule(ruleSetRule);
   return ruleSet;
 }
  private RulesPostImportContainer prepareRulesPostImportRuleSetContainer(String ruleSetId) {
    RulesPostImportContainer rpic = new RulesPostImportContainer();

    RuleSetBean ruleSet =
        getRuleSetService().getRuleSetDao().findById(Integer.valueOf(ruleSetId), currentStudy);
    rpic.addRuleSet(ruleSet);
    for (RuleSetRuleBean ruleSetRule : ruleSet.getRuleSetRules()) {
      rpic.addRuleDef(ruleSetRule.getRuleBean());
    }
    return rpic;
  }
  public RulesPostImportContainer validateRuleSetDefs(RulesPostImportContainer importContainer) {
    for (RuleSetBean ruleSetBean : importContainer.getRuleSets()) {
      AuditableBeanWrapper<RuleSetBean> ruleSetBeanWrapper =
          new AuditableBeanWrapper<RuleSetBean>(ruleSetBean);
      ruleSetBeanWrapper.getAuditableBean().setStudy(currentStudy);
      if (isRuleSetExpressionValid(ruleSetBeanWrapper)) {
        RuleSetBean persistentRuleSetBean = getRuleSetDao().findByExpression(ruleSetBean);

        if (persistentRuleSetBean != null) {
          List<RuleSetRuleBean> importedRuleSetRules =
              ruleSetBeanWrapper.getAuditableBean().getRuleSetRules();
          ruleSetBeanWrapper.setAuditableBean(persistentRuleSetBean);
          ruleSetBeanWrapper.getAuditableBean().addRuleSetRules(importedRuleSetRules);
          // ruleSetBeanWrapper.getAuditableBean().setId(persistentRuleSetBean.getId());
        } else {
          if (importContainer
              .getValidRuleSetExpressionValues()
              .contains(ruleSetBeanWrapper.getAuditableBean().getTarget().getValue())) {
            ruleSetBeanWrapper.error(
                "You have two rule assignments with exact same Target, Combine and try again");
          }
          ruleSetBeanWrapper
              .getAuditableBean()
              .setStudyEventDefinition(
                  getExpressionService()
                      .getStudyEventDefinitionFromExpression(ruleSetBean.getTarget().getValue()));
          ruleSetBeanWrapper
              .getAuditableBean()
              .setCrf(
                  getExpressionService().getCRFFromExpression(ruleSetBean.getTarget().getValue()));
          ruleSetBeanWrapper
              .getAuditableBean()
              .setCrfVersion(
                  getExpressionService()
                      .getCRFVersionFromExpression(ruleSetBean.getTarget().getValue()));
        }
        isRuleSetRuleValid(importContainer, ruleSetBeanWrapper);
      }
      putRuleSetInCorrectContainer(ruleSetBeanWrapper, importContainer);
    }
    logger.info("# of Valid RuleSetDefs : " + importContainer.getValidRuleSetDefs().size());
    logger.info("# of InValid RuleSetDefs : " + importContainer.getInValidRuleSetDefs().size());
    logger.info(
        "# of Overwritable RuleSetDefs : " + importContainer.getDuplicateRuleSetDefs().size());
    return importContainer;
  }
  private RulesPostImportContainer prepareRulesPostImportRuleSetRuleContainer(
      String ruleSetRuleIds) {
    HashMap<Integer, RuleSetBean> ruleSets = new HashMap<Integer, RuleSetBean>();
    HashSet<RuleBean> rules = new HashSet<RuleBean>();
    RulesPostImportContainer rpic = new RulesPostImportContainer();

    String[] splitExpression = ruleSetRuleIds.split(",");
    for (String string : splitExpression) {
      RuleSetRuleBean rsr =
          getRuleSetService().getRuleSetRuleDao().findById(Integer.valueOf(string));
      Collections.sort(rsr.getActions(), new RuleActionComparator());
      Integer key = rsr.getRuleSetBean().getId();
      if (ruleSets.containsKey(key)) {
        RuleSetBean rs = ruleSets.get(key);
        rs.setTarget(rsr.getRuleSetBean().getTarget());
        rs.addRuleSetRule(rsr);
      } else {
        RuleSetBean rs = new RuleSetBean();
        rs.setTarget(rsr.getRuleSetBean().getTarget());
        rs.addRuleSetRule(rsr);
        ruleSets.put(key, rs);
      }
      rules.add(rsr.getRuleBean());
    }

    for (Map.Entry<Integer, RuleSetBean> entry : ruleSets.entrySet()) {
      rpic.addRuleSet(entry.getValue());
    }
    for (RuleBean theRule : rules) {
      rpic.addRuleDef(theRule);
    }
    return rpic;
  }
  @Override
  public void onApplicationEvent(final OnStudyEventUpdated event) {

    LOGGER.debug("listening");
    if (event.getContainer().getChangeDetails().getStartDateChanged()
        || event.getContainer().getChangeDetails().getStatusChanged()) {

      StudyEvent studyEvent = event.getContainer().getEvent();

      Integer studyEventDefId = studyEvent.getStudyEventDefinition().getStudyEventDefinitionId();
      Integer studyEventOrdinal = studyEvent.getSampleOrdinal();
      //	Integer studySubjectId =
      // event.getContainer().getEvent().getStudySubject().getStudySubjectId();
      Integer userId = studyEvent.getUpdateId();

      if (userId == null && studyEvent.getUserAccount() != null)
        userId = studyEvent.getUserAccount().getUserId();

      StudyEventBean studyEventBean = new StudyEventBean();
      studyEventBean.setId(studyEvent.getStudyEventId());

      ArrayList<RuleSetBean> ruleSets = (ArrayList<RuleSetBean>) createRuleSet(studyEventDefId);
      for (RuleSetBean ruleSet : ruleSets) {
        ArrayList<RuleSetBean> ruleSetBeans = new ArrayList();
        ExpressionBean eBean = new ExpressionBean();
        eBean.setValue(ruleSet.getTarget().getValue() + ".A.B");
        ruleSet.setTarget(eBean);
        ruleSet.addExpression(
            getRuleSetService().replaceSEDOrdinal(ruleSet.getTarget(), studyEventBean));
        ruleSetBeans.add(ruleSet);

        getRuleSetService()
            .runIndividualRulesInBeanProperty(
                ruleSetBeans, userId, event.getContainer().getChangeDetails(), studyEventOrdinal);
      }

      //  	  }
    }
  }
  @Override
  public void update(Listener lstnr) {

    //	System.out.println("Triggering the rules based on event updates");
    StudyEventBeanContainer studyEventBeanContainer = (StudyEventBeanContainer) lstnr;

    //	if (studyEventBeanContainer.getChangeDetails().getStartDateChanged() ||
    // studyEventBeanContainer.getChangeDetails().getStatusChanged()){

    Integer studyEventDefId = studyEventBeanContainer.getEvent().getStudyEventDefinitionId();
    //		Integer studySubjectId = studyEventBeanContainer.getEvent().getStudySubjectId();
    Integer userId = studyEventBeanContainer.getEvent().getUpdaterId();
    Integer studyEventOrdinal = studyEventBeanContainer.getEvent().getSampleOrdinal();
    if (userId == 0) userId = studyEventBeanContainer.getEvent().getOwnerId();
    StudyEventBean studyEvent = studyEventBeanContainer.getEvent();

    ArrayList<RuleSetBean> ruleSets = (ArrayList<RuleSetBean>) createRuleSet(studyEventDefId);
    for (RuleSetBean ruleSet : ruleSets) {
      ArrayList<RuleSetBean> ruleSetBeans = new ArrayList();
      ExpressionBean eBean = new ExpressionBean();
      eBean.setValue(ruleSet.getTarget().getValue() + ".A.B");
      ruleSet.setTarget(eBean);
      ruleSet.addExpression(getRuleSetService().replaceSEDOrdinal(ruleSet.getTarget(), studyEvent));
      ruleSetBeans.add(ruleSet);

      // for (RuleSetBean ruleSet : ruleSetBeans){
      String targetProperty =
          ruleSet.getTarget().getValue().substring(ruleSet.getTarget().getValue().indexOf("."));

      if ((targetProperty.contains(ExpressionService.STARTDATE + ".A.B")
              && studyEventBeanContainer.getChangeDetails().getStartDateChanged())
          || (targetProperty.contains(ExpressionService.STATUS + ".A.B")
              && studyEventBeanContainer.getChangeDetails().getStatusChanged())) {

        getRuleSetService()
            .runIndividualRulesInBeanProperty(
                ruleSetBeans,
                userId,
                studyEventBeanContainer.getChangeDetails(),
                studyEventOrdinal);
      }
    }
    //	}

  }
Пример #7
0
  private RulesPostImportContainer mapRulesToRulesPostImportContainer(
      org.openclinica.ns.rules.v31.Rules rules) {
    RulesPostImportContainer rpic = new RulesPostImportContainer();

    for (RuleAssignmentType rat : rules.getRuleAssignment()) {
      TargetType targetType = rat.getTarget();
      ExpressionBean targetBean = new ExpressionBean(Context.OC_RULES_V1, targetType.getValue());
      RunOnScheduleType scheduleType = rules.getRuleAssignment().get(0).getRunOnSchedule();
      RuleSetBean ruleSetBean = new RuleSetBean();
      ruleSetBean.setOriginalTarget(targetBean);
      if (scheduleType != null) {
        if (!scheduleType.getTime().equals("")) {
          ruleSetBean.setRunTime(scheduleType.getTime());
        }
      }

      for (RuleRefType rrt : rat.getRuleRef()) {
        RuleSetRuleBean ruleSetRuleBean = new RuleSetRuleBean();
        ruleSetRuleBean.setOid(rrt.getOID());

        for (DiscrepancyNoteActionType discrepancyNoteActionType : rrt.getDiscrepancyNoteAction()) {
          DiscrepancyNoteActionBean action = new DiscrepancyNoteActionBean();
          action.setMessage(discrepancyNoteActionType.getMessage());
          action.setExpressionEvaluatesTo(
              Boolean.valueOf(discrepancyNoteActionType.getIfExpressionEvaluates()));
          action
              .getRuleActionRun()
              .setInitialDataEntry(discrepancyNoteActionType.getRun().isInitialDataEntry());
          action
              .getRuleActionRun()
              .setDoubleDataEntry(discrepancyNoteActionType.getRun().isDoubleDataEntry());
          action
              .getRuleActionRun()
              .setAdministrativeDataEntry(
                  discrepancyNoteActionType.getRun().isAdministrativeDataEntry());
          action
              .getRuleActionRun()
              .setImportDataEntry(discrepancyNoteActionType.getRun().isImportDataEntry());
          action.getRuleActionRun().setBatch(discrepancyNoteActionType.getRun().isBatch());
          ruleSetRuleBean.addAction(action);
        }
        for (EmailActionType emailActionType : rrt.getEmailAction()) {
          EmailActionBean action = new EmailActionBean();
          action.setMessage(emailActionType.getMessage());
          action.setTo(emailActionType.getTo());
          action.setExpressionEvaluatesTo(
              Boolean.valueOf(emailActionType.getIfExpressionEvaluates()));
          action
              .getRuleActionRun()
              .setInitialDataEntry(emailActionType.getRun().isInitialDataEntry());
          action
              .getRuleActionRun()
              .setDoubleDataEntry(emailActionType.getRun().isDoubleDataEntry());
          action
              .getRuleActionRun()
              .setAdministrativeDataEntry(emailActionType.getRun().isAdministrativeDataEntry());
          action
              .getRuleActionRun()
              .setImportDataEntry(emailActionType.getRun().isImportDataEntry());
          action.getRuleActionRun().setBatch(emailActionType.getRun().isBatch());
          ruleSetRuleBean.addAction(action);
        }
        for (ShowActionType showActionType : rrt.getShowAction()) {
          ShowActionBean action = new ShowActionBean();
          action.setMessage(showActionType.getMessage());
          action.setExpressionEvaluatesTo(
              Boolean.valueOf(showActionType.getIfExpressionEvaluates()));
          action
              .getRuleActionRun()
              .setInitialDataEntry(showActionType.getRun().isInitialDataEntry());
          action.getRuleActionRun().setDoubleDataEntry(showActionType.getRun().isDoubleDataEntry());
          action
              .getRuleActionRun()
              .setAdministrativeDataEntry(showActionType.getRun().isAdministrativeDataEntry());
          action.getRuleActionRun().setImportDataEntry(showActionType.getRun().isImportDataEntry());
          action.getRuleActionRun().setBatch(showActionType.getRun().isBatch());
          for (PropertyType propertyType : showActionType.getDestinationProperty()) {
            PropertyBean property = new PropertyBean();
            property.setOid(propertyType.getOID());
            action.addProperty(property);
          }
          ruleSetRuleBean.addAction(action);
        }
        for (HideActionType hideActionType : rrt.getHideAction()) {
          HideActionBean action = new HideActionBean();
          action.setMessage(hideActionType.getMessage());
          action.setExpressionEvaluatesTo(
              Boolean.valueOf(hideActionType.getIfExpressionEvaluates()));
          action
              .getRuleActionRun()
              .setInitialDataEntry(hideActionType.getRun().isInitialDataEntry());
          action.getRuleActionRun().setDoubleDataEntry(hideActionType.getRun().isDoubleDataEntry());
          action
              .getRuleActionRun()
              .setAdministrativeDataEntry(hideActionType.getRun().isAdministrativeDataEntry());
          action.getRuleActionRun().setImportDataEntry(hideActionType.getRun().isImportDataEntry());
          action.getRuleActionRun().setBatch(hideActionType.getRun().isBatch());
          for (PropertyType propertyType : hideActionType.getDestinationProperty()) {
            PropertyBean property = new PropertyBean();
            property.setOid(propertyType.getOID());
            action.addProperty(property);
          }
          ruleSetRuleBean.addAction(action);
        }
        for (InsertActionType insertActionType : rrt.getInsertAction()) {
          InsertActionBean action = new InsertActionBean();
          action.setExpressionEvaluatesTo(
              Boolean.valueOf(insertActionType.getIfExpressionEvaluates()));
          action
              .getRuleActionRun()
              .setInitialDataEntry(insertActionType.getRun().isInitialDataEntry());
          action
              .getRuleActionRun()
              .setDoubleDataEntry(insertActionType.getRun().isDoubleDataEntry());
          action
              .getRuleActionRun()
              .setAdministrativeDataEntry(insertActionType.getRun().isAdministrativeDataEntry());
          action
              .getRuleActionRun()
              .setImportDataEntry(insertActionType.getRun().isImportDataEntry());
          action.getRuleActionRun().setBatch(insertActionType.getRun().isBatch());
          ruleSetRuleBean.addAction(action);
          for (PropertyType propertyType : insertActionType.getDestinationProperty()) {
            PropertyBean property = new PropertyBean();
            property.setOid(propertyType.getOID());
            property.setValue(propertyType.getValue());
            ExpressionBean expressionBean =
                new ExpressionBean(
                    Context.OC_RULES_V1, propertyType.getValueExpression().getValue());
            property.setValueExpression(expressionBean);
            action.addProperty(property);
          }
          ruleSetRuleBean.addAction(action);
        }

        for (EventActionType eventActionType : rrt.getEventAction()) {
          EventActionBean action = new EventActionBean();
          action.setExpressionEvaluatesTo(
              Boolean.valueOf(eventActionType.getIfExpressionEvaluates()));
          action.setOc_oid_reference(eventActionType.getOID());
          action
              .getRuleActionRun()
              .setNot_started(eventActionType.getRunOnStatus().isNotScheduled());
          action.getRuleActionRun().setScheduled(eventActionType.getRunOnStatus().isScheduled());
          action
              .getRuleActionRun()
              .setData_entry_started(eventActionType.getRunOnStatus().isDataEntryStarted());
          action.getRuleActionRun().setComplete(eventActionType.getRunOnStatus().isCompleted());
          action.getRuleActionRun().setSkipped(eventActionType.getRunOnStatus().isSkipped());
          action.getRuleActionRun().setStopped(eventActionType.getRunOnStatus().isStopped());
          for (EventDestinationType eventDestinationType : eventActionType.getEventDestination()) {
            EventPropertyBean property = new EventPropertyBean();
            property.setProperty(eventDestinationType.getProperty());
            ExpressionBean expressionBean =
                new ExpressionBean(
                    Context.OC_RULES_V1, eventDestinationType.getValueExpression().getValue());
            property.setValueExpression(expressionBean);
            action.addProperty(property);
          }
          ruleSetRuleBean.addAction(action);
        }

        for (NotificationActionType notificationActionType : rrt.getNotificationAction()) {
          NotificationActionBean action = new NotificationActionBean();
          action.setExpressionEvaluatesTo(
              Boolean.valueOf(notificationActionType.getIfExpressionEvaluates()));
          action.setTo(notificationActionType.getTo());
          action.setSubject(notificationActionType.getSubject());
          action.setMessage(notificationActionType.getMessage());
          ruleSetRuleBean.addAction(action);
        }

        ruleSetBean.addRuleSetRule(ruleSetRuleBean);
      }
      rpic.addRuleSet(ruleSetBean);
    }

    for (RuleDefType rdt : rules.getRuleDef()) {
      RuleBean ruleBean = new RuleBean();
      ExpressionBean ruleExpressionBean =
          new ExpressionBean(Context.OC_RULES_V1, rdt.getExpression().getValue());
      ruleBean.setExpression(ruleExpressionBean);
      ruleBean.setDescription(rdt.getDescription());
      ruleBean.setName(rdt.getName());
      ruleBean.setOid(rdt.getOID());
      rpic.addRuleDef(ruleBean);
    }

    return rpic;
  }
  public MessageContainer runRules(
      List<RuleSetBean> ruleSets,
      ExecutionMode executionMode,
      StudyBean currentStudy,
      HashMap<String, String> variableAndValue,
      UserAccountBean ub,
      Phase phase) {

    if (variableAndValue == null || variableAndValue.isEmpty()) {
      logger.warn("You must be executing Rules in Batch");
      variableAndValue = new HashMap<String, String>();
    }

    MessageContainer messageContainer = new MessageContainer();
    HashMap<String, ArrayList<RuleActionContainer>> toBeExecuted =
        new HashMap<String, ArrayList<RuleActionContainer>>();
    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);
          try {
            OpenClinicaExpressionParser oep = new OpenClinicaExpressionParser(eow);
            result = oep.parseAndEvaluateExpression(rule.getExpression().getValue());
            itemData = getExpressionService().getItemDataBeanFromDb(ruleSet.getTarget().getValue());

            // Actions
            List<RuleActionBean> actionListBasedOnRuleExecutionResult =
                ruleSetRule.getActions(result, phase);

            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();
                }
              }
            }

            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 in {} mode. ",
                new Object[] {
                  ruleSet.getTarget().getValue(),
                  rule.getName(),
                  result,
                  actionListBasedOnRuleExecutionResult.size(),
                  executionMode.name()
                });
          } catch (OpenClinicaSystemException osa) {
            // TODO: report something useful
          }
        }
      }
    }

    for (Map.Entry<String, ArrayList<RuleActionContainer>> entry : toBeExecuted.entrySet()) {
      // Sort the list of actions
      Collections.sort(entry.getValue(), new RuleActionContainerComparator());

      for (RuleActionContainer ruleActionContainer : entry.getValue()) {
        logger.info(
            "START Expression is : {} , RuleAction : {} , ExecutionMode : {} ",
            new Object[] {
              ruleActionContainer.getExpressionBean().getValue(),
              ruleActionContainer.getRuleAction().toString(),
              executionMode
            });

        ruleActionContainer.getRuleSetBean().setTarget(ruleActionContainer.getExpressionBean());
        ruleActionContainer
            .getRuleAction()
            .setCuratedMessage(
                curateMessage(
                    ruleActionContainer.getRuleAction(),
                    (ruleActionContainer.getRuleAction().getRuleSetRule())));
        ActionProcessor ap =
            ActionProcessorFacade.getActionProcessor(
                ruleActionContainer.getRuleAction().getActionType(),
                ds,
                getMailSender(),
                dynamicsMetadataService,
                ruleActionContainer.getRuleSetBean(),
                getRuleActionRunLogDao(),
                ruleActionContainer.getRuleAction().getRuleSetRule());
        RuleActionBean rab =
            ap.execute(
                RuleRunnerMode.DATA_ENTRY,
                executionMode,
                ruleActionContainer.getRuleAction(),
                ruleActionContainer.getItemDataBean(),
                DiscrepancyNoteBean.ITEM_DATA,
                currentStudy,
                ub,
                prepareEmailContents(
                    ruleActionContainer.getRuleSetBean(),
                    ruleActionContainer.getRuleAction().getRuleSetRule(),
                    currentStudy,
                    ruleActionContainer.getRuleAction()));
        if (rab != null) {
          messageContainer.add(
              getExpressionService()
                  .getGroupOrdninalConcatWithItemOid(
                      ruleActionContainer.getRuleSetBean().getTarget().getValue()),
              ruleActionContainer.getRuleAction());
        }
        logger.info(
            "END Expression is : {} , RuleAction : {} , ExecutionMode : {} ",
            new Object[] {
              ruleActionContainer.getExpressionBean().getValue(),
              ruleActionContainer.getRuleAction().toString(),
              executionMode
            });
      }
    }
    return messageContainer;
  }
  /**
   * Organize objects in a certain way so that we can show to Users on UI. step1 : Get StudyEvent ,
   * eventCrf , crfVersion from studyEventId.
   *
   * @param crfViewSpecificOrderedObjects
   * @param ruleSet
   * @param rule
   * @return
   */
  private HashMap<RuleBulkExecuteContainer, HashMap<RuleBulkExecuteContainerTwo, Set<String>>>
      populateForCrfBasedRulesView(
          HashMap<RuleBulkExecuteContainer, HashMap<RuleBulkExecuteContainerTwo, Set<String>>>
              crfViewSpecificOrderedObjects,
          RuleSetBean ruleSet,
          RuleBean rule,
          String result,
          StudyBean currentStudy,
          List<RuleActionBean> actions) {

    // step1
    StudyEventBean studyEvent =
        (StudyEventBean)
            getStudyEventDao()
                .findByPK(
                    Integer.valueOf(
                        getExpressionService()
                            .getStudyEventDefenitionOrdninalCurated(
                                ruleSet.getTarget().getValue())));
    EventCRFBean eventCrf =
        (EventCRFBean)
            getEventCrfDao()
                .findAllByStudyEventAndCrfOrCrfVersionOid(
                    studyEvent, getExpressionService().getCrfOid(ruleSet.getTarget().getValue()))
                .get(0);
    CRFVersionBean crfVersion =
        (CRFVersionBean) getCrfVersionDao().findByPK(eventCrf.getCRFVersionId());

    RuleBulkExecuteContainer key =
        new RuleBulkExecuteContainer(crfVersion.getName(), rule, result, actions);
    String key2String =
        getExpressionService()
            .getCustomExpressionUsedToCreateView(
                ruleSet.getTarget().getValue(), studyEvent.getSampleOrdinal());
    String studyEventDefinitionName =
        getExpressionService()
            .getStudyEventDefinitionFromExpression(ruleSet.getTarget().getValue(), currentStudy)
            .getName();
    studyEventDefinitionName += " [" + studyEvent.getSampleOrdinal() + "]";
    // String itemGroupName =
    // getExpressionService().getItemGroupNameAndOrdinal(ruleSet.getTarget().getValue());
    // String itemName =
    // getExpressionService().getItemGroupExpression(ruleSet.getTarget().getValue()).getName();

    String itemGroupName =
        getExpressionService().getItemGroupNameAndOrdinal(ruleSet.getTarget().getValue());
    ItemGroupBean itemGroupBean =
        getExpressionService().getItemGroupExpression(ruleSet.getTarget().getValue());
    ItemBean itemBean =
        getExpressionService().getItemExpression(ruleSet.getTarget().getValue(), itemGroupBean);
    String itemName = itemBean.getName();

    RuleBulkExecuteContainerTwo key2 =
        new RuleBulkExecuteContainerTwo(
            key2String, studyEvent, studyEventDefinitionName, itemGroupName, itemName);
    StudySubjectBean studySubject =
        (StudySubjectBean) getStudySubjectDao().findByPK(studyEvent.getStudySubjectId());

    if (crfViewSpecificOrderedObjects.containsKey(key)) {
      HashMap<RuleBulkExecuteContainerTwo, Set<String>> k = crfViewSpecificOrderedObjects.get(key);
      if (k.containsKey(key2)) {
        k.get(key2).add(String.valueOf(studySubject.getLabel()));
      } else {
        HashSet<String> values = new HashSet<String>();
        values.add(String.valueOf(studySubject.getLabel()));
        k.put(key2, values);
      }
    } else {
      HashMap<RuleBulkExecuteContainerTwo, Set<String>> k =
          new HashMap<RuleBulkExecuteContainerTwo, Set<String>>();
      HashSet<String> values = new HashSet<String>();
      values.add(String.valueOf(studySubject.getLabel()));
      k.put(key2, values);
      crfViewSpecificOrderedObjects.put(key, k);
    }
    return crfViewSpecificOrderedObjects;
  }
  public HashMap<RuleBulkExecuteContainer, HashMap<RuleBulkExecuteContainerTwo, Set<String>>>
      runRulesBulk(
          List<RuleSetBean> ruleSets,
          Boolean dryRun,
          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 = oep.parseAndEvaluateExpression(rule.getExpression().getValue());

            // Actions
            List<RuleActionBean> actionListBasedOnRuleExecutionResult =
                ruleSetRule.getActions(result);

            if (dryRun && actionListBasedOnRuleExecutionResult.size() > 0) {
              crfViewSpecificOrderedObjects =
                  populateForCrfBasedRulesView(
                      crfViewSpecificOrderedObjects,
                      ruleSet,
                      rule,
                      result,
                      currentStudy,
                      actionListBasedOnRuleExecutionResult);
            }

            // If not a dryRun meaning run Actions
            if (!dryRun) {
              for (RuleActionBean ruleAction : actionListBasedOnRuleExecutionResult) {
                int itemDataBeanId =
                    getExpressionService()
                        .getItemDataBeanFromDb(ruleSet.getTarget().getValue())
                        .getId();
                ruleAction.setCuratedMessage(curateMessage(ruleAction, ruleSetRule));
                // getDiscrepancyNoteService().saveFieldNotes(ruleAction.getSummary(),
                // itemDataBeanId, "ItemData", currentStudy, ub);
                ActionProcessor ap =
                    ActionProcessorFacade.getActionProcessor(ruleAction.getActionType(), ds);
                ap.execute(
                    ruleAction,
                    itemDataBeanId,
                    "ItemData",
                    currentStudy,
                    ub,
                    prepareEmailContents(ruleSet, ruleSetRule, currentStudy, ruleAction));
              }
            }
          } catch (OpenClinicaSystemException osa) {
            // TODO: Auditing might happen here failed rule
            logger.warn(
                "RuleSet with target  : {} , Ran Rule : {} , It resulted in an error due to : {}",
                new Object[] {ruleSet.getTarget().getValue(), rule.getName(), osa.getMessage()});
          }
        }
      }
    }
    logCrfViewSpecificOrderedObjects(crfViewSpecificOrderedObjects);
    return crfViewSpecificOrderedObjects;
  }