Search in sources :

Example 1 with SubjectGroupMapBean

use of org.akaza.openclinica.bean.submit.SubjectGroupMapBean in project OpenClinica by OpenClinica.

the class ListStudySubjectServlet method processRequest.

// >>
// < ResourceBundleresword;
@Override
public void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    locale = LocaleResolver.getLocale(request);
    // < resword =
    // ResourceBundle.getBundle("org.akaza.openclinica.i18n.words",locale);
    // BWP 3098 << close the info side panel and show icons
    request.setAttribute("closeInfoShowIcons", true);
    // >>
    // BWP 3195, 3330 : designed to address pagination issues
    String pageNumber = fp.getString(SUBJECT_PAGE_NUMBER);
    StringBuilder paginatingQuery = new StringBuilder("");
    String filterKeyword = fp.getString(FILTER_KEYWORD);
    String tmpSearch = fp.getString(SEARCH_SUBMITTED);
    boolean searchSubmitted = !(tmpSearch == null || "".equalsIgnoreCase(tmpSearch)) && !"".equalsIgnoreCase(filterKeyword) && !"+".equalsIgnoreCase(filterKeyword);
    if (pageNumber != null && !"".equalsIgnoreCase(pageNumber)) {
        int tempNum = 0;
        try {
            tempNum = Integer.parseInt(pageNumber);
        } catch (NumberFormatException nfe) {
        // tempNum is already initialized to 0
        }
        if (tempNum > 0) {
            paginatingQuery = new StringBuilder(SUBJECT_PAGE_NUMBER).append("=").append(pageNumber);
            paginatingQuery.append("&ebl_paginated=1");
        }
    }
    // URL encode the search keyword, since it will be a parameter in the
    // URL
    String filterKeywordURLEncode = java.net.URLEncoder.encode(filterKeyword, "UTF-8");
    if (searchSubmitted) {
        paginatingQuery.append("&ebl_sortColumnInd=0&submitted=1&ebl_sortAscending=1&ebl_filtered=1");
        paginatingQuery.append("&").append(FILTER_KEYWORD).append("=").append(filterKeywordURLEncode);
    }
    request.setAttribute(PAGINATING_QUERY, paginatingQuery.toString());
    StudyDAO stdao = new StudyDAO(sm.getDataSource());
    StudySubjectDAO sdao = new StudySubjectDAO(sm.getDataSource());
    StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
    StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
    SubjectGroupMapDAO sgmdao = new SubjectGroupMapDAO(sm.getDataSource());
    StudyGroupClassDAO sgcdao = new StudyGroupClassDAO(sm.getDataSource());
    StudyGroupDAO sgdao = new StudyGroupDAO(sm.getDataSource());
    StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
    // YW << update study parameters of current study.
    // "collectDob" and "genderRequired" are set as the same as the parent
    // study
    // tbh, also add the params "subjectPersonIdRequired",
    // "subjectIdGeneration", "subjectIdPrefixSuffix"
    int parentStudyId = currentStudy.getParentStudyId();
    ArrayList studyGroupClasses = new ArrayList();
    ArrayList allDefs = new ArrayList();
    // tbh
    if (parentStudyId > 0) {
        StudyBean parentStudy = (StudyBean) stdao.findByPK(parentStudyId);
        studyGroupClasses = sgcdao.findAllActiveByStudy(parentStudy);
        allDefs = seddao.findAllActiveByStudy(parentStudy);
    } else {
        parentStudyId = currentStudy.getId();
        studyGroupClasses = sgcdao.findAllActiveByStudy(currentStudy);
        allDefs = seddao.findAllActiveByStudy(currentStudy);
    }
    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());
    StudyParameterValueBean parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "collectDob");
    currentStudy.getStudyParameterConfig().setCollectDob(parentSPV.getValue());
    parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "genderRequired");
    currentStudy.getStudyParameterConfig().setGenderRequired(parentSPV.getValue());
    parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "subjectPersonIdRequired");
    currentStudy.getStudyParameterConfig().setSubjectPersonIdRequired(parentSPV.getValue());
    parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "subjectIdGeneration");
    currentStudy.getStudyParameterConfig().setSubjectIdGeneration(parentSPV.getValue());
    parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "subjectIdPrefixSuffix");
    currentStudy.getStudyParameterConfig().setSubjectIdPrefixSuffix(parentSPV.getValue());
    // for all the study groups for each group class
    for (int i = 0; i < studyGroupClasses.size(); i++) {
        StudyGroupClassBean sgc = (StudyGroupClassBean) studyGroupClasses.get(i);
        ArrayList groups = sgdao.findAllByGroupClass(sgc);
        sgc.setStudyGroups(groups);
    }
    request.setAttribute("studyGroupClasses", studyGroupClasses);
    // information for the event tabs
    session.setAttribute("allDefsArray", allDefs);
    session.setAttribute("allDefsNumber", new Integer(allDefs.size()));
    session.setAttribute("groupSize", new Integer(studyGroupClasses.size()));
    // find all the subjects in current study
    ArrayList subjects = sdao.findAllByStudyId(currentStudy.getId());
    ArrayList<DisplayStudySubjectBean> displayStudySubs = new ArrayList<DisplayStudySubjectBean>();
    // BEGIN LOOPING THROUGH SUBJECTS
    for (int i = 0; i < subjects.size(); i++) {
        StudySubjectBean studySub = (StudySubjectBean) subjects.get(i);
        ArrayList groups = (ArrayList) sgmdao.findAllByStudySubject(studySub.getId());
        ArrayList subGClasses = new ArrayList();
        for (int j = 0; j < studyGroupClasses.size(); j++) {
            StudyGroupClassBean sgc = (StudyGroupClassBean) studyGroupClasses.get(j);
            boolean hasClass = false;
            for (int k = 0; k < groups.size(); k++) {
                SubjectGroupMapBean sgmb = (SubjectGroupMapBean) groups.get(k);
                if (sgmb.getGroupClassName().equalsIgnoreCase(sgc.getName())) {
                    subGClasses.add(sgmb);
                    hasClass = true;
                    break;
                }
            }
            if (!hasClass) {
                subGClasses.add(new SubjectGroupMapBean());
            }
        }
        ArrayList subEvents = new ArrayList();
        // find all events order by definition ordinal
        ArrayList events = sedao.findAllByStudySubject(studySub);
        for (int j = 0; j < allDefs.size(); j++) {
            StudyEventDefinitionBean sed = (StudyEventDefinitionBean) allDefs.get(j);
            boolean hasDef = false;
            // logger.info("...set blank to "+blankid);
            for (int k = 0; k < events.size(); k++) {
                StudyEventBean se = (StudyEventBean) events.get(k);
                if (se.getStudyEventDefinitionId() == sed.getId()) {
                    se.setStudyEventDefinition(sed);
                    // logger.info(">>>found assigned id "+sed.getId()+" sed
                    // name: "+sed.getName()+" "+se.getId());
                    subEvents.add(se);
                    hasDef = true;
                }
            }
            if (!hasDef) {
                StudyEventBean blank = new StudyEventBean();
                blank.setSubjectEventStatus(SubjectEventStatus.NOT_SCHEDULED);
                blank.setStudyEventDefinitionId(sed.getId());
                // how can we set the following:
                // logger.info("...resetting blank id: "+blank.getId()+" to
                // "+blankid);
                // blank.setId(blankid);
                blank.setStudyEventDefinition(sed);
                // logger.info(">>>blank id: "+blank.getId());
                // logger.info(">>>found unassigned id "+sed.getId()+" sed
                // name: "+sed.getName()+" ");
                subEvents.add(blank);
            }
        }
        // logger.info("subevents size after all adds: "+subEvents.size());
        // reorganize the events and find the repeating ones
        // subEvents:[aa bbb cc d ee]
        // finalEvents:[a(2) b(3) c(2) d e(2)]
        int prevDefId = 0;
        int currDefId = 0;
        ArrayList finalEvents = new ArrayList();
        int repeatingNum = 1;
        int count = 0;
        StudyEventBean event = new StudyEventBean();
        // begin looping through subject events
        for (int j = 0; j < subEvents.size(); j++) {
            StudyEventBean se = (StudyEventBean) subEvents.get(j);
            currDefId = se.getStudyEventDefinitionId();
            if (currDefId != prevDefId) {
                // find a new event
                if (repeatingNum > 1) {
                    event.setRepeatingNum(repeatingNum);
                    repeatingNum = 1;
                }
                // add current event to final
                finalEvents.add(se);
                event = se;
                count++;
            // logger.info("event id? "+event.getId());
            } else {
                // repeating event
                repeatingNum++;
                event.getRepeatEvents().add(se);
                // event.getRepeatEvents().size());
                if (j == subEvents.size() - 1) {
                    event.setRepeatingNum(repeatingNum);
                    repeatingNum = 1;
                }
            }
            prevDefId = currDefId;
        }
        // end looping through subject events
        DisplayStudySubjectBean dssb = new DisplayStudySubjectBean();
        // logger.info("final events size: "+finalEvents.size());
        dssb.setStudyEvents(finalEvents);
        dssb.setStudySubject(studySub);
        dssb.setStudyGroups(subGClasses);
        displayStudySubs.add(dssb);
    }
    // END LOOPING THROUGH SUBJECTS
    // Set a subject property to determine whether to show a signed-type
    // icon (electronic signature)
    // in the JSP view or not
    // Get all event crfs by studyevent id; then use
    // EventDefinitionCRFDAO.isRequired to
    // determine whether any uncompleted CRFs are required.
    boolean isRequiredUncomplete = false;
    for (DisplayStudySubjectBean subject : displayStudySubs) {
        for (Iterator it = subject.getStudyEvents().iterator(); it.hasNext(); ) {
            StudyEventBean event = (StudyEventBean) it.next();
            if (event.getSubjectEventStatus() != null && event.getSubjectEventStatus().getId() == 3) {
                // disallow the subject from signing any studies
                subject.setStudySignable(false);
                break;
            } else {
                // determine whether the subject has any required,
                // uncompleted event CRFs
                isRequiredUncomplete = eventHasRequiredUncompleteCRFs(event);
                if (isRequiredUncomplete) {
                    subject.setStudySignable(false);
                    break;
                }
            }
        }
    }
    fp = new FormProcessor(request);
    EntityBeanTable table = fp.getEntityBeanTable();
    ArrayList allStudyRows = DisplayStudySubjectRow.generateRowsFromBeans(displayStudySubs);
    ArrayList columnArray = new ArrayList();
    columnArray.add(resword.getString("study_subject_ID"));
    columnArray.add(resword.getString("subject_status"));
    columnArray.add(resword.getString("OID"));
    columnArray.add(resword.getString("gender"));
    // new
    columnArray.add(resword.getString("secondary_ID"));
    for (int i = 0; i < studyGroupClasses.size(); i++) {
        StudyGroupClassBean sgc = (StudyGroupClassBean) studyGroupClasses.get(i);
        columnArray.add(sgc.getName());
    }
    for (int i = 0; i < allDefs.size(); i++) {
        StudyEventDefinitionBean sed = (StudyEventDefinitionBean) allDefs.get(i);
        columnArray.add(sed.getName());
    }
    columnArray.add(resword.getString("actions"));
    String[] columns = new String[columnArray.size()];
    columnArray.toArray(columns);
    // String[] columns = {"ID", "Subject Status", "Gender", "Enrollment
    // Date",
    // "Study Events", "Actions" };
    table.setColumns(new ArrayList(Arrays.asList(columns)));
    table.setQuery(getBaseURL(), new HashMap());
    table.hideColumnLink(columnArray.size() - 1);
    // table.addLink("Enroll a new subject",
    // "javascript:leftnavExpand('addSubjectRowExpress');");
    table.setRows(allStudyRows);
    if (filterKeyword != null && !"".equalsIgnoreCase(filterKeyword)) {
        table.setKeywordFilter(filterKeyword);
    }
    table.computeDisplay();
    request.setAttribute("table", table);
    // request.setAttribute("subjects", subjects);
    String idSetting = currentStudy.getStudyParameterConfig().getSubjectIdGeneration();
    // set up auto study subject id
    if (idSetting.equals("auto editable") || idSetting.equals("auto non-editable")) {
        // Shaoyu Su
        // int nextLabel = ssdao.findTheGreatestLabel() + 1;
        // request.setAttribute("label", new Integer(nextLabel).toString());
        request.setAttribute("label", resword.getString("id_generated_Save_Add"));
    }
    FormDiscrepancyNotes discNotes = new FormDiscrepancyNotes();
    session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);
    forwardPage(getJSP());
}
Also used : SubjectGroupMapBean(org.akaza.openclinica.bean.submit.SubjectGroupMapBean) HashMap(java.util.HashMap) StudyGroupClassDAO(org.akaza.openclinica.dao.managestudy.StudyGroupClassDAO) EntityBeanTable(org.akaza.openclinica.web.bean.EntityBeanTable) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyGroupDAO(org.akaza.openclinica.dao.managestudy.StudyGroupDAO) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) DisplayStudyEventBean(org.akaza.openclinica.bean.managestudy.DisplayStudyEventBean) StudyParameterValueBean(org.akaza.openclinica.bean.service.StudyParameterValueBean) DisplayStudySubjectBean(org.akaza.openclinica.bean.managestudy.DisplayStudySubjectBean) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) StudyGroupClassBean(org.akaza.openclinica.bean.managestudy.StudyGroupClassBean) Iterator(java.util.Iterator) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) SubjectGroupMapDAO(org.akaza.openclinica.dao.submit.SubjectGroupMapDAO) FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO) DisplayStudySubjectBean(org.akaza.openclinica.bean.managestudy.DisplayStudySubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudyParameterValueDAO(org.akaza.openclinica.dao.service.StudyParameterValueDAO)

Example 2 with SubjectGroupMapBean

use of org.akaza.openclinica.bean.submit.SubjectGroupMapBean in project OpenClinica by OpenClinica.

the class AddNewSubjectServlet method processRequest.

// YW >>
/*
     * (non-Javadoc)
     * 
     * @see org.akaza.openclinica.control.core.SecureController#processRequest()
     */
@Override
protected void processRequest() throws Exception {
    checkStudyLocked(Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_locked"));
    checkStudyFrozen(Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_frozen"));
    StudySubjectDAO ssd = new StudySubjectDAO(sm.getDataSource());
    StudyDAO stdao = new StudyDAO(sm.getDataSource());
    StudyGroupClassDAO sgcdao = new StudyGroupClassDAO(sm.getDataSource());
    ArrayList classes = new ArrayList();
    panel.setStudyInfoShown(false);
    FormProcessor fp = new FormProcessor(request);
    FormDiscrepancyNotes discNotes;
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    // TODO l10n for dates? Note that in some places we hard-code the YOB by
    // using "01/01/"+yob,
    // not exactly supporting i18n...tbh
    // YW << update study parameters of current study.
    // "collectDob" and "genderRequired" are set as the same as the parent
    // study
    int parentStudyId = currentStudy.getParentStudyId();
    if (parentStudyId <= 0) {
        parentStudyId = currentStudy.getId();
        classes = sgcdao.findAllActiveByStudy(currentStudy);
    } else {
        StudyBean parentStudy = (StudyBean) stdao.findByPK(parentStudyId);
        classes = sgcdao.findAllActiveByStudy(parentStudy);
    }
    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());
    StudyParameterValueBean parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "collectDob");
    currentStudy.getStudyParameterConfig().setCollectDob(parentSPV.getValue());
    parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "genderRequired");
    currentStudy.getStudyParameterConfig().setGenderRequired(parentSPV.getValue());
    // YW >>
    // tbh
    StudyParameterValueBean checkPersonId = spvdao.findByHandleAndStudy(parentStudyId, "subjectPersonIdRequired");
    currentStudy.getStudyParameterConfig().setSubjectPersonIdRequired(checkPersonId.getValue());
    if (!fp.isSubmitted()) {
        if (fp.getBoolean("instr")) {
            session.removeAttribute(FORM_DISCREPANCY_NOTES_NAME);
            forwardPage(Page.INSTRUCTIONS_ENROLL_SUBJECT);
        } else {
            setUpBeans(classes);
            Date today = new Date(System.currentTimeMillis());
            String todayFormatted = local_df.format(today);
            fp.addPresetValue(INPUT_ENROLLMENT_DATE, todayFormatted);
            // YW 10-07-2007 <<
            String idSetting = "";
            if (currentStudy.getParentStudyId() > 0) {
                parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "subjectIdGeneration");
                currentStudy.getStudyParameterConfig().setSubjectIdGeneration(parentSPV.getValue());
            }
            idSetting = currentStudy.getStudyParameterConfig().getSubjectIdGeneration();
            // YW >>
            logger.info("subject id setting :" + idSetting);
            // available ID (label) for now
            if (idSetting.equals("auto editable") || idSetting.equals("auto non-editable")) {
                // Shaoyu Su
                // int nextLabel = ssd.findTheGreatestLabel() + 1;
                // fp.addPresetValue(INPUT_LABEL, new Integer(nextLabel).toString());
                fp.addPresetValue(INPUT_LABEL, resword.getString("id_generated_Save_Add"));
            }
            setPresetValues(fp.getPresetValues());
            discNotes = new FormDiscrepancyNotes();
            session.setAttribute(FORM_DISCREPANCY_NOTES_NAME, discNotes);
            forwardPage(Page.ADD_NEW_SUBJECT);
        }
    } else {
        // values in database <subject> table for "add existing subject"
        if (!fp.getBoolean(EXISTING_SUB_SHOWN)) {
            DOB = fp.getString(INPUT_DOB);
            YOB = fp.getString(INPUT_YOB);
            GENDER = fp.getString(INPUT_GENDER);
        }
        // YW >>
        discNotes = (FormDiscrepancyNotes) session.getAttribute(FORM_DISCREPANCY_NOTES_NAME);
        if (discNotes == null) {
            discNotes = new FormDiscrepancyNotes();
        }
        DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes);
        v.addValidation(INPUT_LABEL, Validator.NO_BLANKS);
        String subIdSetting = currentStudy.getStudyParameterConfig().getSubjectIdGeneration();
        if (!subIdSetting.equalsIgnoreCase("auto non-editable") && !subIdSetting.equalsIgnoreCase("auto editable")) {
            v.addValidation(INPUT_LABEL, Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 30);
        }
        if (currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("required")) {
            v.addValidation(INPUT_UNIQUE_IDENTIFIER, Validator.NO_BLANKS);
        }
        v.addValidation(INPUT_UNIQUE_IDENTIFIER, Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
        if (!StringUtils.isBlank(fp.getString(INPUT_SECONDARY_LABEL))) {
            v.addValidation(INPUT_SECONDARY_LABEL, Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 30);
        }
        String dobSetting = currentStudy.getStudyParameterConfig().getCollectDob();
        if (dobSetting.equals("1")) {
            // date of birth
            v.addValidation(INPUT_DOB, Validator.IS_A_DATE);
            if (!StringUtils.isBlank(fp.getString("INPUT_DOB"))) {
                v.alwaysExecuteLastValidation(INPUT_DOB);
            }
            v.addValidation(INPUT_DOB, Validator.DATE_IN_PAST);
        } else if (dobSetting.equals("2")) {
            // year of birth
            v.addValidation(INPUT_YOB, Validator.IS_AN_INTEGER);
            v.alwaysExecuteLastValidation(INPUT_YOB);
            v.addValidation(INPUT_YOB, Validator.COMPARES_TO_STATIC_VALUE, NumericComparisonOperator.GREATER_THAN_OR_EQUAL_TO, 1000);
            // get today's year
            Date today = new Date();
            Calendar c = Calendar.getInstance();
            c.setTime(today);
            int currentYear = c.get(Calendar.YEAR);
            v.addValidation(INPUT_YOB, Validator.COMPARES_TO_STATIC_VALUE, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, currentYear);
        } else {
            // DOB not used, added tbh 102007
            logger.info("should read this only if DOB not used");
        }
        ArrayList acceptableGenders = new ArrayList();
        acceptableGenders.add("m");
        acceptableGenders.add("f");
        if (!currentStudy.getStudyParameterConfig().getGenderRequired().equals("false")) {
            v.addValidation(INPUT_GENDER, Validator.IS_IN_SET, acceptableGenders);
        }
        v.addValidation(INPUT_ENROLLMENT_DATE, Validator.IS_A_DATE);
        v.alwaysExecuteLastValidation(INPUT_ENROLLMENT_DATE);
        v.addValidation(INPUT_ENROLLMENT_DATE, Validator.DATE_IN_PAST);
        boolean locationError = false;
        if (fp.getBoolean("addWithEvent")) {
            v.addValidation(INPUT_EVENT_START_DATE, Validator.IS_A_DATE);
            v.alwaysExecuteLastValidation(INPUT_EVENT_START_DATE);
            if (currentStudy.getStudyParameterConfig().getEventLocationRequired().equalsIgnoreCase("required")) {
                v.addValidation("location", Validator.NO_BLANKS);
                locationError = true;
            }
        }
        HashMap errors = v.validate();
        SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
        // global
        String uniqueIdentifier = fp.getString(INPUT_UNIQUE_IDENTIFIER);
        // Id
        SubjectBean subjectWithSameId = new SubjectBean();
        SubjectBean subjectWithSameIdInParent = new SubjectBean();
        boolean showExistingRecord = false;
        if (!uniqueIdentifier.equals("")) {
            boolean subjectWithSameIdInCurrentStudyTree = false;
            // checks whether there is a subject with same id inside current
            // study/site
            subjectWithSameId = sdao.findByUniqueIdentifierAndStudy(uniqueIdentifier, currentStudy.getId());
            // tbh
            if (subjectWithSameId.isActive()) {
                // ||
                // subjectWithSameIdInParent.isActive())
                // {
                Validator.addError(errors, INPUT_UNIQUE_IDENTIFIER, resexception.getString("subject_with_person_ID") + " " + uniqueIdentifier + " " + resexception.getString("is_already_enrolled_in_this_study"));
                subjectWithSameIdInCurrentStudyTree = true;
                logger.info("just added unique id in study tree");
            } else {
                // checks whether there is a subject with same id inside
                // sites of
                // current study
                subjectWithSameId = sdao.findByUniqueIdentifierAndParentStudy(uniqueIdentifier, currentStudy.getId());
                if (subjectWithSameId.isActive()) {
                    StudySubjectBean ssub = ssd.findBySubjectIdAndStudy(subjectWithSameId.getId(), currentStudy);
                    StudyBean site = (StudyBean) stdao.findByPK(ssub.getStudyId());
                    Validator.addError(errors, INPUT_UNIQUE_IDENTIFIER, resexception.getString("this_subject_person_ID") + " " + uniqueIdentifier + resexception.getString("has_already_enrolled_site") + site.getName() + resexception.getString("of_current_study_need_to_move") + resexception.getString("please_have_user_manage_privileges"));
                    subjectWithSameIdInCurrentStudyTree = true;
                } else {
                    // check whether there is a subject with same id in the
                    // parent study
                    subjectWithSameId = sdao.findByUniqueIdentifierAndStudy(uniqueIdentifier, currentStudy.getParentStudyId());
                    if (subjectWithSameId.isActive()) {
                        Validator.addError(errors, INPUT_UNIQUE_IDENTIFIER, resexception.getString("this_subject_with_person_ID") + " " + uniqueIdentifier + resexception.getString("has_already_enrolled_parent_study"));
                        subjectWithSameIdInCurrentStudyTree = true;
                    } else {
                        // YW 11-26-2007 << check whether there is a subject
                        // with the same id in other sites of the same study
                        subjectWithSameId = sdao.findByUniqueIdentifierAndParentStudy(uniqueIdentifier, currentStudy.getParentStudyId());
                        if (subjectWithSameId.isActive()) {
                            Validator.addError(errors, INPUT_UNIQUE_IDENTIFIER, resexception.getString("this_subject_with_person_ID") + " " + uniqueIdentifier + resexception.getString("has_already_enrolled_site_study"));
                            subjectWithSameIdInCurrentStudyTree = true;
                        }
                    // YW >>
                    }
                }
            }
            if (!subjectWithSameIdInCurrentStudyTree) {
                subjectWithSameId = sdao.findByUniqueIdentifier(uniqueIdentifier);
                // found subject with same id in other study
                if (subjectWithSameId.isActive()) {
                    showExistingRecord = true;
                }
            }
        }
        // end of the block if(!uniqueIdentifier.equals(""))
        String label = fp.getString(INPUT_LABEL);
        String personId = fp.getString(INPUT_UNIQUE_IDENTIFIER);
        String secondaryLable = fp.getString(INPUT_SECONDARY_LABEL);
        // then Study Subject ID should be created when db row is inserted.
        if (label.contains("<") || label.contains(">")) {
            Validator.addError(errors, INPUT_LABEL, resexception.getString("study_subject_id_can_not_contain_html_lessthan_or_greaterthan_elements"));
        }
        if (secondaryLable.contains("<") || secondaryLable.contains(">")) {
            Validator.addError(errors, INPUT_SECONDARY_LABEL, resexception.getString("secondary_id_can_not_contain_html_lessthan_or_greaterthan_elements"));
        }
        if (personId.contains("<") || personId.contains(">")) {
            Validator.addError(errors, INPUT_UNIQUE_IDENTIFIER, resexception.getString("person_id_can_not_contain_html_lessthan_or_greaterthan_elements"));
        }
        if (!label.equalsIgnoreCase(resword.getString("id_generated_Save_Add"))) {
            StudySubjectBean subjectWithSameLabel = ssd.findByLabelAndStudy(label, currentStudy);
            StudySubjectBean subjectWithSameLabelInParent = new StudySubjectBean();
            // tbh
            if (currentStudy.getParentStudyId() > 0) {
                // <
                subjectWithSameLabelInParent = ssd.findSameByLabelAndStudy(label, currentStudy.getParentStudyId(), 0);
            // --
            // blank
            // id
            // since
            // the
            // ss
            // hasn't
            // been
            // created
            // yet,
            // tbh
            }
            // tbh
            if (subjectWithSameLabel.isActive() || subjectWithSameLabelInParent.isActive()) {
                Validator.addError(errors, INPUT_LABEL, resexception.getString("another_assigned_this_ID_choose_unique"));
            }
        }
        if (!classes.isEmpty()) {
            for (int i = 0; i < classes.size(); i++) {
                StudyGroupClassBean sgc = (StudyGroupClassBean) classes.get(i);
                int groupId = fp.getInt("studyGroupId" + i);
                String notes = fp.getString("notes" + i);
                if ("Required".equals(sgc.getSubjectAssignment()) && groupId == 0) {
                    Validator.addError(errors, "studyGroupId" + i, resexception.getString("group_class_is_required"));
                }
                if (notes.trim().length() > 255) {
                    Validator.addError(errors, "notes" + i, resexception.getString("notes_cannot_longer_255"));
                }
                sgc.setStudyGroupId(groupId);
                sgc.setGroupNotes(notes);
            }
        }
        if (!errors.isEmpty()) {
            addPageMessage(respage.getString("there_were_some_errors_submission"));
            if (locationError) {
                addPageMessage(respage.getString("location_blank_error"));
            }
            setInputMessages(errors);
            fp.addPresetValue(INPUT_DOB, fp.getString(INPUT_DOB));
            fp.addPresetValue(INPUT_YOB, fp.getString(INPUT_YOB));
            fp.addPresetValue(INPUT_GENDER, fp.getString(INPUT_GENDER));
            fp.addPresetValue(INPUT_UNIQUE_IDENTIFIER, uniqueIdentifier);
            fp.addPresetValue(INPUT_LABEL, label);
            fp.addPresetValue(INPUT_SECONDARY_LABEL, fp.getString(INPUT_SECONDARY_LABEL));
            fp.addPresetValue(INPUT_ENROLLMENT_DATE, fp.getString(INPUT_ENROLLMENT_DATE));
            fp.addPresetValue(INPUT_EVENT_START_DATE, fp.getString(INPUT_EVENT_START_DATE));
            fp.addPresetValue(STUDY_EVENT_DEFINITION, fp.getInt(STUDY_EVENT_DEFINITION));
            fp.addPresetValue(LOCATION, fp.getString(LOCATION));
            fp.addPresetValue(EDIT_DOB, fp.getString(EDIT_DOB));
            setPresetValues(fp.getPresetValues());
            setUpBeans(classes);
            boolean existingSubShown = fp.getBoolean(EXISTING_SUB_SHOWN);
            if (!existingSubShown) {
                Object isSubjectOverlay = fp.getRequest().getParameter("subjectOverlay");
                if (isSubjectOverlay != null) {
                    int eventId = fp.getInt("studyEventDefinition");
                    if (eventId < 1) {
                        Validator.addError(errors, STUDY_EVENT_DEFINITION, resexception.getString("input_not_acceptable_option"));
                    }
                    String location = fp.getString(LOCATION);
                    if (location == null && location.length() == 0) {
                        Validator.addError(errors, LOCATION, resexception.getString("field_not_blank"));
                    }
                    request.setAttribute("showOverlay", true);
                    forwardPage(Page.LIST_STUDY_SUBJECTS_SERVLET);
                } else {
                    forwardPage(Page.ADD_NEW_SUBJECT);
                }
            } else {
                forwardPage(Page.ADD_EXISTING_SUBJECT);
            }
        } else {
            // no errors
            StudySubjectBean studySubject = new StudySubjectBean();
            SubjectBean subject = new SubjectBean();
            boolean existingSubShown = fp.getBoolean(EXISTING_SUB_SHOWN);
            if (showExistingRecord && !existingSubShown) {
                needUpdate = false;
                subject = subjectWithSameId;
                Calendar cal = Calendar.getInstance();
                int year = 0;
                if (subject.getDateOfBirth() != null) {
                    cal.setTime(subject.getDateOfBirth());
                    year = cal.get(Calendar.YEAR);
                    fp.addPresetValue(INPUT_DOB, local_df.format(subject.getDateOfBirth()));
                } else {
                    fp.addPresetValue(INPUT_DOB, "");
                }
                if (currentStudy.getStudyParameterConfig().getCollectDob().equals("1") && !subject.isDobCollected()) {
                    // fp.addPresetValue(EDIT_DOB, "yes");
                    fp.addPresetValue(INPUT_DOB, fp.getString(INPUT_DOB));
                }
                // YW << it has been taken off to solve bug0001125
                /*
                     * else { fp.addPresetValue(INPUT_DOB, ""); }
                     */
                // YW >>
                fp.addPresetValue(INPUT_YOB, String.valueOf(year));
                if (!currentStudy.getStudyParameterConfig().getGenderRequired().equals("false")) {
                    fp.addPresetValue(INPUT_GENDER, subject.getGender() + "");
                } else {
                    fp.addPresetValue(INPUT_GENDER, "");
                }
                // Shaoyu Su: delay setting INPUT_LABEL field
                if (!label.equalsIgnoreCase(resword.getString("id_generated_Save_Add"))) {
                    fp.addPresetValue(INPUT_LABEL, label);
                }
                fp.addPresetValue(INPUT_SECONDARY_LABEL, fp.getString(INPUT_SECONDARY_LABEL));
                fp.addPresetValue(INPUT_ENROLLMENT_DATE, fp.getString(INPUT_ENROLLMENT_DATE));
                fp.addPresetValue(INPUT_EVENT_START_DATE, fp.getString(INPUT_EVENT_START_DATE));
                // YW >>
                fp.addPresetValue(INPUT_UNIQUE_IDENTIFIER, subject.getUniqueIdentifier());
                setPresetValues(fp.getPresetValues());
                setUpBeans(classes);
                // YW <<
                int warningCount = 0;
                if (currentStudy.getStudyParameterConfig().getGenderRequired().equalsIgnoreCase("true")) {
                    if (String.valueOf(subjectWithSameId.getGender()).equals(" ")) {
                        fp.addPresetValue(G_WARNING, "emptytrue");
                        fp.addPresetValue(INPUT_GENDER, GENDER);
                        needUpdate = true;
                        updateSubject = subjectWithSameId;
                        updateSubject.setGender(GENDER.toCharArray()[0]);
                        warningCount++;
                    } else if (!String.valueOf(subjectWithSameId.getGender()).equals(GENDER)) {
                        fp.addPresetValue(G_WARNING, "true");
                        warningCount++;
                    } else {
                        fp.addPresetValue(G_WARNING, "false");
                    }
                } else {
                    fp.addPresetValue(G_WARNING, "false");
                }
                // Current study required DOB
                if (currentStudy.getStudyParameterConfig().getCollectDob().equals("1")) {
                    // date-of-birth in subject table is not completed
                    if (subjectWithSameId.isDobCollected() == false) {
                        needUpdate = true;
                        updateSubject = subjectWithSameId;
                        updateSubject.setDobCollected(true);
                        if (subjectWithSameId.getDateOfBirth() == null) {
                            fp.addPresetValue(INPUT_DOB, DOB);
                            updateSubject.setDateOfBirth(new Date(DOB));
                        } else {
                            String y = String.valueOf(subjectWithSameId.getDateOfBirth()).split("\\-")[0];
                            String[] d = DOB.split("\\/");
                            // if year-of-birth in subject table
                            if (!y.equals("0001")) {
                                // year, use year-of-birth
                                if (!y.equals(d[2])) {
                                    fp.addPresetValue(D_WARNING, "dobYearWrong");
                                    fp.addPresetValue(INPUT_DOB, d[0] + "/" + d[1] + "/" + y);
                                    updateSubject.setDateOfBirth(sdf.parse(d[0] + "/" + d[1] + "/" + y));
                                } else {
                                    fp.addPresetValue(D_WARNING, "dobUsed");
                                    fp.addPresetValue(INPUT_DOB, DOB);
                                    updateSubject.setDateOfBirth(sdf.parse(DOB));
                                }
                            } else // date-of-birth is not required in subject
                            // table
                            {
                                fp.addPresetValue(D_WARNING, "emptyD");
                                fp.addPresetValue(INPUT_DOB, DOB);
                                updateSubject.setDateOfBirth(sdf.parse(DOB));
                            }
                        }
                        warningCount++;
                    } else // date-of-birth in subject table but doesn't match DOB
                    if (!local_df.format(subjectWithSameId.getDateOfBirth()).toString().equals(DOB)) {
                        // System.out.println("comparing " +
                        // local_df.format(
                        // subjectWithSameId.getDateOfBirth()).toString());
                        fp.addPresetValue(D_WARNING, "currentDOBWrong");
                        warningCount++;
                    } else // date-of-birth in subject table matchs DOB
                    {
                        fp.addPresetValue(D_WARNING, "false");
                    }
                } else // current Study require YOB
                if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2")) {
                    String y = String.valueOf(subjectWithSameId.getDateOfBirth()).split("\\-")[0];
                    // year of date-of-birth in subject table is avaible
                    if (!y.equals("0001")) {
                        // year in subject table doesn't match YOB,
                        if (!y.equals(YOB)) {
                            fp.addPresetValue(Y_WARNING, "yobWrong");
                            warningCount++;
                        } else // year in subject table matches YOB
                        {
                            fp.addPresetValue(Y_WARNING, "false");
                        }
                    } else // year of date-of-birth in the subject talbe is not
                    // availbe, YOB is used
                    {
                        needUpdate = true;
                        updateSubject = subjectWithSameId;
                        fp.addPresetValue(Y_WARNING, "yearEmpty");
                        fp.addPresetValue(INPUT_YOB, YOB);
                        updateSubject.setDateOfBirth(sdf.parse("01/01/" + YOB));
                        warningCount++;
                    }
                } else // current study require no DOB, there is no need to check
                // date-of-birth in the subject table
                {
                    fp.addPresetValue(Y_WARNING, "false");
                }
                if (warningCount > 0) {
                    warningCount = 0;
                    forwardPage(Page.ADD_EXISTING_SUBJECT);
                    return;
                }
            // forwardPage(Page.ADD_EXISTING_SUBJECT);
            // return;
            // YW >>
            }
            // to be inserted into both <subject> and <studysubject> tables
            if (!showExistingRecord) {
                // YW >>
                if (!StringUtil.isBlank(fp.getString(INPUT_GENDER))) {
                    subject.setGender(fp.getString(INPUT_GENDER).charAt(0));
                } else {
                    subject.setGender(' ');
                }
                subject.setUniqueIdentifier(uniqueIdentifier);
                if (currentStudy.getStudyParameterConfig().getCollectDob().equals("1")) {
                    if (!StringUtil.isBlank(fp.getString(INPUT_DOB))) {
                        subject.setDateOfBirth(fp.getDate(INPUT_DOB));
                        subject.setDobCollected(true);
                    } else {
                        subject.setDateOfBirth(null);
                        subject.setDobCollected(false);
                    }
                } else if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2")) {
                    // generate a fake birthday in 01/01/YYYY format, only
                    // the year is
                    // valid
                    // added the "2" to make sure that 'not used' is kept to
                    // null, tbh 102007
                    subject.setDobCollected(false);
                    int yob = fp.getInt(INPUT_YOB);
                    Date fakeDate = new Date("01/01/" + yob);
                    // Calendar fakeCal = Calendar.getInstance();
                    // fakeCal.set(Calendar.YEAR, yob);
                    // fakeCal.set(Calendar.MONTH, 1);
                    // fakeCal.set(Calendar.DAY_OF_MONTH, 1);
                    // String dobString = "01/01/" + yob;
                    String dobString = local_df.format(fakeDate);
                    try {
                        Date fakeDOB = local_df.parse(dobString);
                        subject.setDateOfBirth(fakeDOB);
                    } catch (ParseException pe) {
                        subject.setDateOfBirth(new Date());
                        addPageMessage(respage.getString("problem_happened_saving_year"));
                    }
                }
                subject.setStatus(Status.AVAILABLE);
                subject.setOwner(ub);
                subject = sdao.create(subject);
                if (!subject.isActive()) {
                    throw new OpenClinicaException(resexception.getString("could_not_create_subject"), "3");
                }
            // YW << for showExistingRecord && existingSubShown,
            // If input value(s) is(are) different from database,
            // warning will be shown.
            // If value(s) in database is(are) empty, entered value(s)
            // could be used;
            // Otherwise, value(s) in database will be used.
            // For date-of-birth, if database only has year-of-birth,
            // the year in database will be used for year part
            } else if (existingSubShown) {
                if (!needUpdate) {
                    subject = subjectWithSameId;
                } else {
                    updateSubject.setUpdater(ub);
                    updateSubject = (SubjectBean) sdao.update(updateSubject);
                    if (!updateSubject.isActive()) {
                        throw new OpenClinicaException("Could not create subject.", "5");
                    }
                    subject = updateSubject;
                    needUpdate = false;
                }
            }
            // YW >>
            // enroll the subject in the active study
            studySubject.setSubjectId(subject.getId());
            studySubject.setStudyId(currentStudy.getId());
            studySubject.setLabel(fp.getString(INPUT_LABEL));
            studySubject.setSecondaryLabel(fp.getString(INPUT_SECONDARY_LABEL));
            studySubject.setStatus(Status.AVAILABLE);
            studySubject.setEnrollmentDate(fp.getDate(INPUT_ENROLLMENT_DATE));
            if (fp.getBoolean("addWithEvent")) {
                studySubject.setEventStartDate(fp.getDate(INPUT_EVENT_START_DATE));
            }
            studySubject.setOwner(ub);
            // Shaoyu Su: prevent same label ("Study Subject ID")
            if (fp.getString(INPUT_LABEL).equalsIgnoreCase(resword.getString("id_generated_Save_Add"))) {
                synchronized (simpleLockObj) {
                    int nextLabel = ssd.findTheGreatestLabel() + 1;
                    studySubject.setLabel(nextLabel + "");
                    studySubject = ssd.createWithoutGroup(studySubject);
                    if (showExistingRecord && !existingSubShown) {
                        fp.addPresetValue(INPUT_LABEL, label);
                    }
                }
            } else {
                studySubject = ssd.createWithoutGroup(studySubject);
            }
            if (!classes.isEmpty() && studySubject.isActive()) {
                SubjectGroupMapDAO sgmdao = new SubjectGroupMapDAO(sm.getDataSource());
                for (int i = 0; i < classes.size(); i++) {
                    StudyGroupClassBean group = (StudyGroupClassBean) classes.get(i);
                    int studyGroupId = group.getStudyGroupId();
                    String notes = group.getGroupNotes();
                    SubjectGroupMapBean map = new SubjectGroupMapBean();
                    map.setNotes(group.getGroupNotes());
                    map.setStatus(Status.AVAILABLE);
                    map.setStudyGroupId(group.getStudyGroupId());
                    map.setStudySubjectId(studySubject.getId());
                    map.setStudyGroupClassId(group.getId());
                    map.setOwner(ub);
                    if (map.getStudyGroupId() > 0) {
                        sgmdao.create(map);
                    }
                }
            }
            if (!studySubject.isActive()) {
                throw new OpenClinicaException(resexception.getString("could_not_create_study_subject"), "4");
            }
            // save discrepancy notes into DB
            FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session.getAttribute(FORM_DISCREPANCY_NOTES_NAME);
            DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
            String[] subjectFields = { INPUT_DOB, INPUT_YOB, INPUT_GENDER };
            for (String element : subjectFields) {
                saveFieldNotes(element, fdn, dndao, subject.getId(), "subject", currentStudy);
            }
            saveFieldNotes(INPUT_ENROLLMENT_DATE, fdn, dndao, studySubject.getId(), "studySub", currentStudy);
            request.removeAttribute(FormProcessor.FIELD_SUBMITTED);
            request.setAttribute(CreateNewStudyEventServlet.INPUT_STUDY_SUBJECT, studySubject);
            request.setAttribute(CreateNewStudyEventServlet.INPUT_REQUEST_STUDY_SUBJECT, "no");
            request.setAttribute(FormProcessor.FIELD_SUBMITTED, "0");
            addPageMessage(respage.getString("subject_with_unique_identifier") + studySubject.getLabel() + respage.getString("X_was_created_succesfully"));
            if (fp.getBoolean("addWithEvent")) {
                createStudyEvent(fp, studySubject);
                // YW <<
                request.setAttribute("id", studySubject.getId() + "");
                // String url= response.encodeRedirectURL("ViewStudySubject?id=" + studySubject.getId());
                // response.sendRedirect(url);
                forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
                // + studySubject.getId()));
                return;
            }
            String submitEvent = fp.getString(SUBMIT_EVENT_BUTTON);
            String submitEnroll = fp.getString(SUBMIT_ENROLL_BUTTON);
            String submitDone = fp.getString(SUBMIT_DONE_BUTTON);
            session.removeAttribute(FORM_DISCREPANCY_NOTES_NAME);
            if (!StringUtil.isBlank(submitEvent)) {
                forwardPage(Page.CREATE_NEW_STUDY_EVENT_SERVLET);
            } else if (!StringUtil.isBlank(submitEnroll)) {
                // NEW MANTIS ISSUE 4770
                setUpBeans(classes);
                Date today = new Date(System.currentTimeMillis());
                String todayFormatted = local_df.format(today);
                fp.addPresetValue(INPUT_ENROLLMENT_DATE, todayFormatted);
                // YW 10-07-2007 <<
                String idSetting = "";
                if (currentStudy.getParentStudyId() > 0) {
                    parentSPV = spvdao.findByHandleAndStudy(parentStudyId, "subjectIdGeneration");
                    currentStudy.getStudyParameterConfig().setSubjectIdGeneration(parentSPV.getValue());
                }
                idSetting = currentStudy.getStudyParameterConfig().getSubjectIdGeneration();
                // YW >>
                logger.info("subject id setting :" + idSetting);
                // set up auto study subject id
                if (idSetting.equals("auto editable") || idSetting.equals("auto non-editable")) {
                    // Shaoyu Su
                    // int nextLabel = ssd.findTheGreatestLabel() + 1;
                    // fp.addPresetValue(INPUT_LABEL, new Integer(nextLabel).toString());
                    fp.addPresetValue(INPUT_LABEL, resword.getString("id_generated_Save_Add"));
                }
                setPresetValues(fp.getPresetValues());
                discNotes = new FormDiscrepancyNotes();
                session.setAttribute(FORM_DISCREPANCY_NOTES_NAME, discNotes);
                // End of 4770
                forwardPage(Page.ADD_NEW_SUBJECT);
            } else {
                // forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
                // forwardPage(Page.SUBMIT_DATA_SERVLET);
                request.setAttribute("id", studySubject.getId() + "");
                // String url=response.encodeRedirectURL("ViewStudySubject?id=" + studySubject.getId());
                // response.sendRedirect(url);
                forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
                return;
            }
        }
    // end of no error (errors.isEmpty())
    }
// end of fp.isSubmitted()
}
Also used : SubjectGroupMapBean(org.akaza.openclinica.bean.submit.SubjectGroupMapBean) HashMap(java.util.HashMap) StudyGroupClassDAO(org.akaza.openclinica.dao.managestudy.StudyGroupClassDAO) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) SubjectDAO(org.akaza.openclinica.dao.submit.SubjectDAO) ArrayList(java.util.ArrayList) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) StudyParameterValueBean(org.akaza.openclinica.bean.service.StudyParameterValueBean) StudyGroupClassBean(org.akaza.openclinica.bean.managestudy.StudyGroupClassBean) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes) SubjectGroupMapDAO(org.akaza.openclinica.dao.submit.SubjectGroupMapDAO) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) Calendar(java.util.Calendar) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) Date(java.util.Date) SubjectBean(org.akaza.openclinica.bean.submit.SubjectBean) DisplaySubjectBean(org.akaza.openclinica.bean.submit.DisplaySubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) DiscrepancyValidator(org.akaza.openclinica.control.form.DiscrepancyValidator) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) ParseException(java.text.ParseException) StudyParameterValueDAO(org.akaza.openclinica.dao.service.StudyParameterValueDAO) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with SubjectGroupMapBean

use of org.akaza.openclinica.bean.submit.SubjectGroupMapBean in project OpenClinica by OpenClinica.

the class ListStudySubjectTableFactory method setDataAndLimitVariables.

@Override
public void setDataAndLimitVariables(TableFacade tableFacade) {
    Limit limit = tableFacade.getLimit();
    FindSubjectsFilter subjectFilter = getSubjectFilter(limit);
    if (!limit.isComplete()) {
        int totalRows = getStudySubjectDAO().getCountWithFilter(subjectFilter, getStudyBean());
        tableFacade.setTotalRows(totalRows);
    }
    FindSubjectsSort subjectSort = getSubjectSort(limit);
    int rowStart = limit.getRowSelect().getRowStart();
    int rowEnd = limit.getRowSelect().getRowEnd();
    Collection<StudySubjectBean> items = getStudySubjectDAO().getWithFilterAndSort(getStudyBean(), subjectFilter, subjectSort, rowStart, rowEnd);
    Collection<HashMap<Object, Object>> theItems = new ArrayList<HashMap<Object, Object>>();
    for (StudySubjectBean studySubjectBean : items) {
        HashMap<Object, Object> theItem = new HashMap<Object, Object>();
        theItem.put("studySubject", studySubjectBean);
        theItem.put("studySubject.label", studySubjectBean.getLabel());
        theItem.put("studySubject.status", studySubjectBean.getStatus());
        theItem.put("enrolledAt", ((StudyBean) getStudyDAO().findByPK(studySubjectBean.getStudyId())).getIdentifier());
        theItem.put("studySubject.oid", studySubjectBean.getOid());
        theItem.put("studySubject.secondaryLabel", studySubjectBean.getSecondaryLabel());
        SubjectBean subjectBean = (SubjectBean) getSubjectDAO().findByPK(studySubjectBean.getSubjectId());
        theItem.put("subject", subjectBean);
        theItem.put("subject.charGender", subjectBean.getGender());
        // Get All study events for this study subject and then put list in
        // HashMap with study event definition id as
        // key and a list of study events as the value.
        List<StudyEventBean> allStudyEventsForStudySubject = getStudyEventDAO().findAllByStudySubject(studySubjectBean);
        HashMap<Integer, List<StudyEventBean>> allStudyEventsForStudySubjectBySedId = new HashMap<Integer, List<StudyEventBean>>();
        theItem.put("isSignable", isSignable(allStudyEventsForStudySubject, studySubjectBean));
        for (StudyEventBean studyEventBean : allStudyEventsForStudySubject) {
            if (allStudyEventsForStudySubjectBySedId.get(studyEventBean.getStudyEventDefinitionId()) == null) {
                ArrayList<StudyEventBean> a = new ArrayList<StudyEventBean>();
                a.add(studyEventBean);
                allStudyEventsForStudySubjectBySedId.put(studyEventBean.getStudyEventDefinitionId(), a);
            } else {
                allStudyEventsForStudySubjectBySedId.get(studyEventBean.getStudyEventDefinitionId()).add(studyEventBean);
            }
        }
        SubjectGroupMapBean subjectGroupMapBean;
        for (StudyGroupClassBean studyGroupClass : getStudyGroupClasses()) {
            subjectGroupMapBean = getSubjectGroupMapDAO().findAllByStudySubjectAndStudyGroupClass(studySubjectBean.getId(), studyGroupClass.getId());
            if (null != subjectGroupMapBean) {
                theItem.put("sgc_" + studyGroupClass.getId(), subjectGroupMapBean.getStudyGroupId());
                theItem.put("grpName_sgc_" + studyGroupClass.getId(), subjectGroupMapBean.getStudyGroupName());
            }
        }
        subjectGroupMapBean = null;
        for (StudyEventDefinitionBean studyEventDefinition : getStudyEventDefinitions()) {
            List<StudyEventBean> studyEvents = allStudyEventsForStudySubjectBySedId.get(studyEventDefinition.getId());
            SubjectEventStatus subjectEventStatus = null;
            studyEvents = studyEvents == null ? new ArrayList<StudyEventBean>() : studyEvents;
            if (studyEvents.size() < 1) {
                subjectEventStatus = SubjectEventStatus.NOT_SCHEDULED;
            } else {
                for (StudyEventBean studyEventBean : studyEvents) {
                    if (studyEventBean.getSampleOrdinal() == 1) {
                        subjectEventStatus = studyEventBean.getSubjectEventStatus();
                        break;
                    }
                }
            }
            theItem.put("sed_" + studyEventDefinition.getId(), subjectEventStatus.getId());
            theItem.put("sed_" + studyEventDefinition.getId() + "_studyEvents", studyEvents);
            theItem.put("sed_" + studyEventDefinition.getId() + "_object", studyEventDefinition);
        }
        theItems.add(theItem);
    }
    // Do not forget to set the items back on the tableFacade.
    tableFacade.setItems(theItems);
}
Also used : SubjectGroupMapBean(org.akaza.openclinica.bean.submit.SubjectGroupMapBean) FindSubjectsSort(org.akaza.openclinica.dao.managestudy.FindSubjectsSort) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) SubjectEventStatus(org.akaza.openclinica.bean.core.SubjectEventStatus) SubjectBean(org.akaza.openclinica.bean.submit.SubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudyGroupClassBean(org.akaza.openclinica.bean.managestudy.StudyGroupClassBean) List(java.util.List) ArrayList(java.util.ArrayList) Limit(org.jmesa.limit.Limit) FindSubjectsFilter(org.akaza.openclinica.dao.managestudy.FindSubjectsFilter)

Example 4 with SubjectGroupMapBean

use of org.akaza.openclinica.bean.submit.SubjectGroupMapBean in project OpenClinica by OpenClinica.

the class RemoveStudyServlet method processRequest.

@Override
public void processRequest() throws Exception {
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    FormProcessor fp = new FormProcessor(request);
    int studyId = fp.getInt("id");
    StudyBean study = (StudyBean) sdao.findByPK(studyId);
    // find all sites
    ArrayList sites = (ArrayList) sdao.findAllByParent(studyId);
    // find all user and roles in the study, include ones in sites
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    ArrayList userRoles = udao.findAllByStudyId(studyId);
    // find all subjects in the study, include ones in sites
    StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
    ArrayList subjects = ssdao.findAllByStudy(study);
    // find all events in the study, include ones in sites
    StudyEventDefinitionDAO sefdao = new StudyEventDefinitionDAO(sm.getDataSource());
    ArrayList definitions = sefdao.findAllByStudy(study);
    String action = request.getParameter("action");
    if (studyId == 0) {
        addPageMessage(respage.getString("please_choose_a_study_to_remove"));
        forwardPage(Page.STUDY_LIST_SERVLET);
    } else {
        if ("confirm".equalsIgnoreCase(action)) {
            request.setAttribute("studyToRemove", study);
            request.setAttribute("sitesToRemove", sites);
            request.setAttribute("userRolesToRemove", userRoles);
            request.setAttribute("subjectsToRemove", subjects);
            request.setAttribute("definitionsToRemove", definitions);
            forwardPage(Page.REMOVE_STUDY);
        } else {
            logger.info("submit to remove the study");
            // change all statuses to unavailable
            StudyDAO studao = new StudyDAO(sm.getDataSource());
            study.setOldStatus(study.getStatus());
            study.setStatus(Status.DELETED);
            study.setUpdater(ub);
            study.setUpdatedDate(new Date());
            studao.update(study);
            // remove all sites
            for (int i = 0; i < sites.size(); i++) {
                StudyBean site = (StudyBean) sites.get(i);
                if (!site.getStatus().equals(Status.DELETED)) {
                    site.setOldStatus(site.getStatus());
                    site.setStatus(Status.AUTO_DELETED);
                    site.setUpdater(ub);
                    site.setUpdatedDate(new Date());
                    sdao.update(site);
                }
            }
            // remove all users and roles
            for (int i = 0; i < userRoles.size(); i++) {
                StudyUserRoleBean role = (StudyUserRoleBean) userRoles.get(i);
                logger.info("remove user role" + role.getName());
                if (!role.getStatus().equals(Status.DELETED)) {
                    role.setStatus(Status.AUTO_DELETED);
                    role.setUpdater(ub);
                    role.setUpdatedDate(new Date());
                    udao.updateStudyUserRole(role, role.getUserName());
                }
            }
            // YW << bug fix for that current active study has been deleted
            if (study.getId() == currentStudy.getId()) {
                currentStudy.setStatus(Status.DELETED);
                currentRole.setStatus(Status.DELETED);
            } else // (auto-removed)
            if (currentStudy.getParentStudyId() == study.getId()) {
                currentStudy.setStatus(Status.AUTO_DELETED);
                // we may need handle this later?
                currentRole.setStatus(Status.DELETED);
            }
            // remove all subjects
            for (int i = 0; i < subjects.size(); i++) {
                StudySubjectBean subject = (StudySubjectBean) subjects.get(i);
                if (!subject.getStatus().equals(Status.DELETED)) {
                    subject.setStatus(Status.AUTO_DELETED);
                    subject.setUpdater(ub);
                    subject.setUpdatedDate(new Date());
                    ssdao.update(subject);
                }
            }
            // remove all study_group_class
            // changed by jxu on 08-31-06, to fix the problem of no study_id
            // in study_group table
            StudyGroupClassDAO sgcdao = new StudyGroupClassDAO(sm.getDataSource());
            StudyGroupDAO sgdao = new StudyGroupDAO(sm.getDataSource());
            SubjectGroupMapDAO sgmdao = new SubjectGroupMapDAO(sm.getDataSource());
            // YW 09-27-2007, enable status updating for StudyGroupClassBean
            ArrayList groups = sgcdao.findAllByStudy(study);
            for (int i = 0; i < groups.size(); i++) {
                StudyGroupClassBean group = (StudyGroupClassBean) groups.get(i);
                if (!group.getStatus().equals(Status.DELETED)) {
                    group.setStatus(Status.AUTO_DELETED);
                    group.setUpdater(ub);
                    group.setUpdatedDate(new Date());
                    sgcdao.update(group);
                    // all subject_group_map
                    ArrayList subjectGroupMaps = sgmdao.findAllByStudyGroupClassId(group.getId());
                    for (int j = 0; j < subjectGroupMaps.size(); j++) {
                        SubjectGroupMapBean sgMap = (SubjectGroupMapBean) subjectGroupMaps.get(j);
                        if (!sgMap.getStatus().equals(Status.DELETED)) {
                            sgMap.setStatus(Status.AUTO_DELETED);
                            sgMap.setUpdater(ub);
                            sgMap.setUpdatedDate(new Date());
                            sgmdao.update(sgMap);
                        }
                    }
                }
            }
            ArrayList groupClasses = sgcdao.findAllActiveByStudy(study);
            for (int i = 0; i < groupClasses.size(); i++) {
                StudyGroupClassBean gc = (StudyGroupClassBean) groupClasses.get(i);
                if (!gc.getStatus().equals(Status.DELETED)) {
                    gc.setStatus(Status.AUTO_DELETED);
                    gc.setUpdater(ub);
                    gc.setUpdatedDate(new Date());
                    sgcdao.update(gc);
                }
            }
            // remove all event definitions and event
            EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
            StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
            for (int i = 0; i < definitions.size(); i++) {
                StudyEventDefinitionBean definition = (StudyEventDefinitionBean) definitions.get(i);
                if (!definition.getStatus().equals(Status.DELETED)) {
                    definition.setStatus(Status.AUTO_DELETED);
                    definition.setUpdater(ub);
                    definition.setUpdatedDate(new Date());
                    sefdao.update(definition);
                    ArrayList edcs = (ArrayList) edcdao.findAllByDefinition(definition.getId());
                    for (int j = 0; j < edcs.size(); j++) {
                        EventDefinitionCRFBean edc = (EventDefinitionCRFBean) edcs.get(j);
                        if (!edc.getStatus().equals(Status.DELETED)) {
                            edc.setStatus(Status.AUTO_DELETED);
                            edc.setUpdater(ub);
                            edc.setUpdatedDate(new Date());
                            edcdao.update(edc);
                        }
                    }
                    ArrayList events = (ArrayList) sedao.findAllByDefinition(definition.getId());
                    EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());
                    for (int j = 0; j < events.size(); j++) {
                        StudyEventBean event = (StudyEventBean) events.get(j);
                        if (!event.getStatus().equals(Status.DELETED)) {
                            event.setStatus(Status.AUTO_DELETED);
                            event.setUpdater(ub);
                            event.setUpdatedDate(new Date());
                            sedao.update(event);
                            ArrayList eventCRFs = ecdao.findAllByStudyEvent(event);
                            ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
                            for (int k = 0; k < eventCRFs.size(); k++) {
                                EventCRFBean eventCRF = (EventCRFBean) eventCRFs.get(k);
                                if (!eventCRF.getStatus().equals(Status.DELETED)) {
                                    eventCRF.setOldStatus(eventCRF.getStatus());
                                    eventCRF.setStatus(Status.AUTO_DELETED);
                                    eventCRF.setUpdater(ub);
                                    eventCRF.setUpdatedDate(new Date());
                                    ecdao.update(eventCRF);
                                    ArrayList itemDatas = iddao.findAllByEventCRFId(eventCRF.getId());
                                    for (int a = 0; a < itemDatas.size(); a++) {
                                        ItemDataBean item = (ItemDataBean) itemDatas.get(a);
                                        if (!item.getStatus().equals(Status.DELETED)) {
                                            item.setOldStatus(item.getStatus());
                                            item.setStatus(Status.AUTO_DELETED);
                                            item.setUpdater(ub);
                                            item.setUpdatedDate(new Date());
                                            iddao.update(item);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // for definitions
            DatasetDAO datadao = new DatasetDAO(sm.getDataSource());
            ArrayList dataset = datadao.findAllByStudyId(study.getId());
            for (int i = 0; i < dataset.size(); i++) {
                DatasetBean data = (DatasetBean) dataset.get(i);
                if (!data.getStatus().equals(Status.DELETED)) {
                    data.setStatus(Status.AUTO_DELETED);
                    data.setUpdater(ub);
                    data.setUpdatedDate(new Date());
                    datadao.update(data);
                }
            }
            addPageMessage(resexception.getString("this_study_has_been_removed_succesfully"));
            forwardPage(Page.STUDY_LIST_SERVLET);
        }
    }
}
Also used : SubjectGroupMapBean(org.akaza.openclinica.bean.submit.SubjectGroupMapBean) StudyGroupClassDAO(org.akaza.openclinica.dao.managestudy.StudyGroupClassDAO) DatasetBean(org.akaza.openclinica.bean.extract.DatasetBean) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyGroupDAO(org.akaza.openclinica.dao.managestudy.StudyGroupDAO) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) StudyGroupClassBean(org.akaza.openclinica.bean.managestudy.StudyGroupClassBean) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) SubjectGroupMapDAO(org.akaza.openclinica.dao.submit.SubjectGroupMapDAO) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) StudyUserRoleBean(org.akaza.openclinica.bean.login.StudyUserRoleBean) EventDefinitionCRFDAO(org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) DatasetDAO(org.akaza.openclinica.dao.extract.DatasetDAO) Date(java.util.Date) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) EventDefinitionCRFBean(org.akaza.openclinica.bean.managestudy.EventDefinitionCRFBean)

Example 5 with SubjectGroupMapBean

use of org.akaza.openclinica.bean.submit.SubjectGroupMapBean in project OpenClinica by OpenClinica.

the class SubjectGroupMapDAO method findAll.

public Collection findAll() {
    this.setTypesExpected();
    ArrayList alist = this.select(digester.getQuery("findAll"));
    ArrayList al = new ArrayList();
    Iterator it = alist.iterator();
    while (it.hasNext()) {
        SubjectGroupMapBean eb = (SubjectGroupMapBean) this.getEntityFromHashMap((HashMap) it.next());
        al.add(eb);
    }
    return al;
}
Also used : SubjectGroupMapBean(org.akaza.openclinica.bean.submit.SubjectGroupMapBean) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator)

Aggregations

SubjectGroupMapBean (org.akaza.openclinica.bean.submit.SubjectGroupMapBean)22 ArrayList (java.util.ArrayList)19 HashMap (java.util.HashMap)14 SubjectGroupMapDAO (org.akaza.openclinica.dao.submit.SubjectGroupMapDAO)12 StudySubjectBean (org.akaza.openclinica.bean.managestudy.StudySubjectBean)11 StudyGroupClassBean (org.akaza.openclinica.bean.managestudy.StudyGroupClassBean)10 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)9 FormProcessor (org.akaza.openclinica.control.form.FormProcessor)9 StudyDAO (org.akaza.openclinica.dao.managestudy.StudyDAO)9 StudySubjectDAO (org.akaza.openclinica.dao.managestudy.StudySubjectDAO)9 StudyEventBean (org.akaza.openclinica.bean.managestudy.StudyEventBean)8 StudyGroupClassDAO (org.akaza.openclinica.dao.managestudy.StudyGroupClassDAO)8 StudyGroupDAO (org.akaza.openclinica.dao.managestudy.StudyGroupDAO)8 Date (java.util.Date)7 Iterator (java.util.Iterator)7 StudyEventDAO (org.akaza.openclinica.dao.managestudy.StudyEventDAO)6 StudyEventDefinitionDAO (org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO)6 StudyEventDefinitionBean (org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean)5 EventCRFBean (org.akaza.openclinica.bean.submit.EventCRFBean)5 EventDefinitionCRFDAO (org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO)5