Search in sources :

Example 51 with RuleSetBean

use of org.akaza.openclinica.domain.rule.RuleSetBean in project OpenClinica by OpenClinica.

the class RuleController method validateAndSave.

@RequestMapping(value = "/studies/{study}/validateAndSaveRule", method = RequestMethod.POST)
@ResponseBody
public Response validateAndSave(@RequestBody org.openclinica.ns.rules.v31.Rules rules, Model model, HttpSession session, @PathVariable("study") String studyOid, @RequestParam("ignoreDuplicates") Boolean ignoreDuplicates) 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);
            }
        }
    } else if ((rpic.getDuplicateRuleDefs().size() > 0) && !ignoreDuplicates) {
        response.setValid(Boolean.FALSE);
        for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getDuplicateRuleDefs()) {
            org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
            messageType.setMessage(DUPLICATE_MESSAGE);
            response.getMessages().add(messageType);
        }
    } else {
        getRuleSetService().saveImportFromDesigner(rpic);
    }
    logger.debug("RPIC READY");
    return response;
}
Also used : Locale(java.util.Locale) AuditableBeanWrapper(org.akaza.openclinica.domain.rule.AuditableBeanWrapper) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) MessagesType(org.openclinica.ns.response.v31.MessagesType) RulesTestMessagesType(org.openclinica.ns.rules_test.v31.RulesTestMessagesType) MessagesType(org.openclinica.ns.response.v31.MessagesType) Response(org.openclinica.ns.response.v31.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) RulesPostImportContainer(org.akaza.openclinica.domain.rule.RulesPostImportContainer) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) RuleSetBean(org.akaza.openclinica.domain.rule.RuleSetBean) RuleSetRuleBean(org.akaza.openclinica.domain.rule.RuleSetRuleBean) RuleBean(org.akaza.openclinica.domain.rule.RuleBean) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 52 with RuleSetBean

use of org.akaza.openclinica.domain.rule.RuleSetBean in project OpenClinica by OpenClinica.

the class RuleController method create.

@RequestMapping(value = "/studies/{study}/validateAndTestRule", method = RequestMethod.POST)
@ResponseBody
public 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;
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) DateTime(org.joda.time.DateTime) ExpressionProcessor(org.akaza.openclinica.domain.rule.expression.ExpressionProcessor) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) RulesTestMessagesType(org.openclinica.ns.rules_test.v31.RulesTestMessagesType) ParameterType(org.openclinica.ns.rules_test.v31.ParameterType) PeriodFormatter(org.joda.time.format.PeriodFormatter) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) MessagesType(org.openclinica.ns.response.v31.MessagesType) RulesTestMessagesType(org.openclinica.ns.rules_test.v31.RulesTestMessagesType) Duration(org.joda.time.Duration) MessagesType(org.openclinica.ns.response.v31.MessagesType) Response(org.openclinica.ns.response.v31.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) RulesPostImportContainer(org.akaza.openclinica.domain.rule.RulesPostImportContainer) PeriodFormatterBuilder(org.joda.time.format.PeriodFormatterBuilder) ExpressionObjectWrapper(org.akaza.openclinica.domain.rule.expression.ExpressionObjectWrapper) Map(java.util.Map) HashMap(java.util.HashMap) RuleSetBean(org.akaza.openclinica.domain.rule.RuleSetBean) RuleSetRuleBean(org.akaza.openclinica.domain.rule.RuleSetRuleBean) RuleBean(org.akaza.openclinica.domain.rule.RuleBean) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 53 with RuleSetBean

use of org.akaza.openclinica.domain.rule.RuleSetBean 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;
}
Also used : RuleActionBean(org.akaza.openclinica.domain.rule.action.RuleActionBean) DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) ItemBean(org.akaza.openclinica.bean.submit.ItemBean) HashMap(java.util.HashMap) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) DateTime(org.joda.time.DateTime) ExpressionProcessor(org.akaza.openclinica.domain.rule.expression.ExpressionProcessor) MessageFormat(java.text.MessageFormat) PeriodFormatter(org.joda.time.format.PeriodFormatter) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) Duration(org.joda.time.Duration) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) InsufficientPermissionException(org.akaza.openclinica.web.InsufficientPermissionException) ParseException(java.text.ParseException) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) ExpressionBean(org.akaza.openclinica.domain.rule.expression.ExpressionBean) PeriodFormatterBuilder(org.joda.time.format.PeriodFormatterBuilder) ExpressionObjectWrapper(org.akaza.openclinica.domain.rule.expression.ExpressionObjectWrapper) HashMap(java.util.HashMap) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat) ItemFormMetadataBean(org.akaza.openclinica.bean.submit.ItemFormMetadataBean) RuleSetBean(org.akaza.openclinica.domain.rule.RuleSetBean)

Example 54 with RuleSetBean

use of org.akaza.openclinica.domain.rule.RuleSetBean in project OpenClinica by OpenClinica.

the class TestRuleServlet method getExpressionService.

private ExpressionService getExpressionService() {
    expressionService = this.expressionService != null ? expressionService : new ExpressionService(new ExpressionObjectWrapper(sm.getDataSource(), currentStudy, (ExpressionBean) null, (RuleSetBean) null));
    expressionService.setExpressionWrapper(new ExpressionObjectWrapper(sm.getDataSource(), currentStudy, (ExpressionBean) null, (RuleSetBean) null));
    return expressionService;
}
Also used : ExpressionService(org.akaza.openclinica.service.rule.expression.ExpressionService) ExpressionObjectWrapper(org.akaza.openclinica.domain.rule.expression.ExpressionObjectWrapper) ExpressionBean(org.akaza.openclinica.domain.rule.expression.ExpressionBean) RuleSetBean(org.akaza.openclinica.domain.rule.RuleSetBean)

Example 55 with RuleSetBean

use of org.akaza.openclinica.domain.rule.RuleSetBean in project OpenClinica by OpenClinica.

the class ViewRuleAssignmentRow method compareColumn.

/*
     * (non-Javadoc)
     *
     * @see org.akaza.openclinica.core.EntityBeanRow#compareColumn(java.lang.Object,
     *      int)
     */
@Override
protected int compareColumn(Object row, int sortingColumn) {
    if (!row.getClass().equals(ViewRuleAssignmentRow.class)) {
        return 0;
    }
    RuleSetBean thisRuleSet = (RuleSetBean) bean;
    RuleSetBean argRuleSet = (RuleSetBean) ((ViewRuleAssignmentRow) row).bean;
    int answer = 0;
    switch(sortingColumn) {
        case COL_CRF:
            answer = thisRuleSet.getCrfWithVersionName().toLowerCase().compareTo(argRuleSet.getCrfWithVersionName().toLowerCase());
            break;
        case COL_GROUP:
            answer = thisRuleSet.getGroupLabel().toLowerCase().compareTo(argRuleSet.getGroupLabel().toLowerCase());
            break;
        case COL_ITEM:
            answer = thisRuleSet.getItemName().toLowerCase().compareTo(argRuleSet.getItemName().toLowerCase());
            break;
    }
    return answer;
}
Also used : RuleSetBean(org.akaza.openclinica.domain.rule.RuleSetBean)

Aggregations

RuleSetBean (org.akaza.openclinica.domain.rule.RuleSetBean)67 ArrayList (java.util.ArrayList)28 RuleSetRuleBean (org.akaza.openclinica.domain.rule.RuleSetRuleBean)26 ExpressionBean (org.akaza.openclinica.domain.rule.expression.ExpressionBean)19 RuleBean (org.akaza.openclinica.domain.rule.RuleBean)15 HashMap (java.util.HashMap)13 ExpressionObjectWrapper (org.akaza.openclinica.domain.rule.expression.ExpressionObjectWrapper)11 ItemDataBean (org.akaza.openclinica.bean.submit.ItemDataBean)9 RuleActionBean (org.akaza.openclinica.domain.rule.action.RuleActionBean)9 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)8 OpenClinicaSystemException (org.akaza.openclinica.exception.OpenClinicaSystemException)7 Map (java.util.Map)6 UserAccountBean (org.akaza.openclinica.bean.login.UserAccountBean)6 StudyDAO (org.akaza.openclinica.dao.managestudy.StudyDAO)6 OpenClinicaExpressionParser (org.akaza.openclinica.logic.expressionTree.OpenClinicaExpressionParser)6 StudyEventBean (org.akaza.openclinica.bean.managestudy.StudyEventBean)5 CRFVersionBean (org.akaza.openclinica.bean.submit.CRFVersionBean)5 RulesPostImportContainer (org.akaza.openclinica.domain.rule.RulesPostImportContainer)5 RuleActionRunLogBean (org.akaza.openclinica.domain.rule.action.RuleActionRunLogBean)5 Locale (java.util.Locale)4