@RequestMapping(value = "/studies/{study}/validateRule", method = RequestMethod.POST)
  public @ResponseBody Response create(
      @RequestBody org.openclinica.ns.rules.v31.Rules rules,
      Model model,
      HttpSession session,
      @PathVariable("study") String studyOid)
      throws Exception {
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    RulesPostImportContainer rpic = mapRulesToRulesPostImportContainer(rules);
    StudyDAO studyDao = new StudyDAO(dataSource);
    StudyBean currentStudy = studyDao.findByOid(studyOid);

    UserAccountBean userAccount = getUserAccount();
    mayProceed(userAccount, currentStudy);

    getRulePostImportContainerService(currentStudy, userAccount);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleDefs(rpic);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleSetDefs(rpic);
    Response response = new Response();
    response.setValid(Boolean.TRUE);
    if (rpic.getInValidRuleDefs().size() > 0 || rpic.getInValidRuleSetDefs().size() > 0) {
      response.setValid(Boolean.FALSE);
      for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getInValidRuleDefs()) {
        for (String error : beanWrapper.getImportErrors()) {
          org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
          messageType.setMessage(error);
          response.getMessages().add(messageType);
        }
      }
      for (AuditableBeanWrapper<RuleSetBean> beanWrapper : rpic.getInValidRuleSetDefs()) {
        for (String error : beanWrapper.getImportErrors()) {
          org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
          messageType.setMessage(error);
          response.getMessages().add(messageType);
        }
      }
    }
    logger.debug("RPIC READY");
    return response;
  }
  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;
  }
  @RequestMapping(value = "/studies/{study}/validateAndTestRule", method = RequestMethod.POST)
  public @ResponseBody org.openclinica.ns.rules_test.v31.RulesTest create(
      @RequestBody org.openclinica.ns.rules_test.v31.RulesTest ruleTest,
      Model model,
      HttpSession session,
      @PathVariable("study") String studyOid)
      throws Exception {
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    RulesPostImportContainer rpic = mapRulesToRulesPostImportContainer(ruleTest.getRules());
    StudyDAO studyDao = new StudyDAO(dataSource);
    StudyBean currentStudy = studyDao.findByOid(studyOid);

    UserAccountBean userAccount = getUserAccount();
    mayProceed(userAccount, currentStudy);

    getRulePostImportContainerService(currentStudy, userAccount);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleDefs(rpic);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleSetDefs(rpic);
    Response response = new Response();
    response.setValid(Boolean.TRUE);
    if (rpic.getInValidRuleDefs().size() > 0 || rpic.getInValidRuleSetDefs().size() > 0) {
      response.setValid(Boolean.FALSE);
      for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getInValidRuleDefs()) {
        for (String error : beanWrapper.getImportErrors()) {
          org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
          messageType.setMessage(error);
          response.getMessages().add(messageType);
        }
      }
      for (AuditableBeanWrapper<RuleSetBean> beanWrapper : rpic.getInValidRuleSetDefs()) {
        for (String error : beanWrapper.getImportErrors()) {
          org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
          messageType.setMessage(error);
          response.getMessages().add(messageType);
        }
      }
    }

    HashMap<String, String> p = new HashMap<String, String>();
    for (ParameterType parameterType : ruleTest.getParameters()) {
      p.put(parameterType.getKey(), parameterType.getValue());
    }
    ExpressionObjectWrapper eow =
        new ExpressionObjectWrapper(
            dataSource,
            currentStudy,
            rpic.getRuleDefs().get(0).getExpression(),
            rpic.getRuleSets().get(0));
    ExpressionProcessor ep = ExpressionProcessorFactory.createExpressionProcessor(eow);

    // 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);
    ruleTest.getParameters().clear();
    for (Map.Entry<String, String> entry : result.entrySet()) {
      ParameterType parameterType = new ParameterType();
      parameterType.setKey(entry.getKey());
      parameterType.setValue(entry.getValue());
      ruleTest.getParameters().add(parameterType);
    }
    // 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()));
    RulesTestMessagesType messageType = new RulesTestMessagesType();
    messageType.setKey("duration");
    messageType.setValue(yearsAndMonths.print(dur.toPeriod()));
    ruleTest.getRulesTestMessages().add(messageType);

    return ruleTest;
  }