Search in sources :

Example 16 with OpenClinicaException

use of org.akaza.openclinica.exception.OpenClinicaException in project OpenClinica by OpenClinica.

the class CreateNewStudyEventServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    checkStudyLocked(Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_locked"));
    panel.setStudyInfoShown(false);
    fp = new FormProcessor(request);
    FormDiscrepancyNotes discNotes = null;
    int studySubjectId = fp.getInt(INPUT_STUDY_SUBJECT_ID_FROM_VIEWSUBJECT);
    // input from manage subject matrix, user has specified definition id
    int studyEventDefinitionId = fp.getInt(INPUT_STUDY_EVENT_DEFINITION);
    // TODO: make this sensitive to permissions
    StudySubjectDAO sdao = new StudySubjectDAO(sm.getDataSource());
    StudySubjectBean ssb;
    if (studySubjectId <= 0) {
        ssb = (StudySubjectBean) request.getAttribute(INPUT_STUDY_SUBJECT);
    } else {
        // YW 11-08-2007, << a new study event could not be added if its
        // study subject has been removed
        ssb = (StudySubjectBean) sdao.findByPK(studySubjectId);
        Status s = ssb.getStatus();
        if ("removed".equalsIgnoreCase(s.getName()) || "auto-removed".equalsIgnoreCase(s.getName())) {
            addPageMessage(resword.getString("study_event") + resterm.getString("could_not_be") + resterm.getString("added") + "." + respage.getString("study_subject_has_been_deleted"));
            request.setAttribute("id", new Integer(studySubjectId).toString());
            forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
        }
        // YW >>
        request.setAttribute(INPUT_REQUEST_STUDY_SUBJECT, "no");
    }
    // running this crashes the server, or so we think...instead, let's grab a count
    // or remove it altogether tbh 10/2009
    // ArrayList subjects = sdao.findAllActiveByStudyOrderByLabel(currentStudy);
    // TODO: make this sensitive to permissions
    StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
    StudyBean studyWithEventDefinitions = currentStudy;
    if (currentStudy.getParentStudyId() > 0) {
        studyWithEventDefinitions = new StudyBean();
        studyWithEventDefinitions.setId(currentStudy.getParentStudyId());
    }
    // find all active definitions with CRFs
    ArrayList eventDefinitions = seddao.findAllActiveByStudy(studyWithEventDefinitions);
    // EventDefinitionCRFDAO edcdao = new
    // EventDefinitionCRFDAO(sm.getDataSource());
    // ArrayList definitionsWithCRF = new ArrayList();
    // for (int i=0; i<eventDefinitions.size(); i++) {
    // StudyEventDefinitionBean sed =
    // (StudyEventDefinitionBean)eventDefinitions.get(i);
    // logger.info("StudyEventDefinition name[" + sed.getName() + "]");
    // ArrayList edcs = edcdao.findAllByEventDefinitionId(sed.getId());
    // if (!edcs.isEmpty()) {
    // definitionsWithCRF.add(sed);
    // }
    // }
    // Collections.sort(definitionsWithCRF);
    Collections.sort(eventDefinitions);
    /*
         * ArrayList eventDefinitionsScheduled = new ArrayList(); for (int i =
         * 0; i < eventDefinitions.size(); i++) { StudyEventDefinitionBean sed =
         * (StudyEventDefinitionBean) eventDefinitions.get(i); if
         * (sed.getType().equalsIgnoreCase("scheduled")) {
         * eventDefinitionsScheduled.add(sed); } }
         */
    // all definitions will appear in scheduled event creation box-11/26/05
    ArrayList eventDefinitionsScheduled = eventDefinitions;
    if (!fp.isSubmitted()) {
        // StudyEventDAO sed = new StudyEventDAO(sm.getDataSource());
        // sed.updateSampleOrdinals_v092();
        HashMap presetValues = new HashMap();
        // YW 08-16-2007 << set default as blank for time
        presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(-1));
        presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(-1));
        presetValues.put(INPUT_STARTDATE_PREFIX + "Half", new String(""));
        presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(-1));
        presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(-1));
        presetValues.put(INPUT_ENDDATE_PREFIX + "Half", new String(""));
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Hour", new Integer(-1));
            presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Minute", new Integer(-1));
            presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Half", new String(""));
            presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Hour", new Integer(-1));
            presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Minute", new Integer(-1));
            presetValues.put(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Half", new String(""));
        }
        // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        // example of taking the above line and transferring to i18n on the
        // below line, tbh
        String dateValue = local_df.format(new Date(System.currentTimeMillis()));
        presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue);
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            presetValues.put(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date", dateValue);
            // location
            presetValues.put(INPUT_SCHEDULED_LOCATION[i], currentStudy.getFacilityCity());
            presetValues.put(this.DISPLAY_SCHEDULED[i], "none");
        }
        // defualt
        presetValues.put(INPUT_LOCATION, currentStudy.getFacilityCity());
        if (ssb != null && ssb.isActive()) {
            presetValues.put(INPUT_STUDY_SUBJECT, ssb);
            String requestStudySubject = (String) request.getAttribute(INPUT_REQUEST_STUDY_SUBJECT);
            if (requestStudySubject != null) {
                presetValues.put(INPUT_REQUEST_STUDY_SUBJECT, requestStudySubject);
                dateValue = local_df.format(new Date());
                presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue);
            }
        }
        if (studyEventDefinitionId > 0) {
            StudyEventDefinitionBean sed = (StudyEventDefinitionBean) seddao.findByPK(studyEventDefinitionId);
            presetValues.put(INPUT_STUDY_EVENT_DEFINITION, sed);
        }
        // tbh
        logger.debug("set preset values: " + presetValues.toString());
        logger.debug("found def.w.CRF list, size " + eventDefinitions.size());
        // tbh
        setPresetValues(presetValues);
        ArrayList subjects = new ArrayList();
        setupBeans(subjects, eventDefinitions);
        discNotes = new FormDiscrepancyNotes();
        session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);
        request.setAttribute("eventDefinitionsScheduled", eventDefinitionsScheduled);
        setInputMessages(new HashMap());
        forwardPage(Page.CREATE_NEW_STUDY_EVENT);
    } else {
        // tbh
        // String dateCheck = (String)request.getAttribute("startDate");
        // String endCheck = (String)request.getAttribute("endDate");
        // logger.debug(dateCheck+"; "+endCheck);
        String dateCheck2 = request.getParameter("startDate");
        String endCheck2 = request.getParameter("endDate");
        logger.debug(dateCheck2 + "; " + endCheck2);
        // YW, 3-12-2008, 2220 fix <<
        String strEnd = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX);
        String[] strEndScheduled = new String[ADDITIONAL_SCHEDULED_NUM];
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            strEndScheduled[i] = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
        }
        Date start = getInputStartDate();
        Date end = null;
        Date[] startScheduled = new Date[ADDITIONAL_SCHEDULED_NUM];
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            startScheduled[i] = getInputStartDateScheduled(i);
        }
        Date[] endScheduled = new Date[ADDITIONAL_SCHEDULED_NUM];
        // YW >>
        // for (java.util.Enumeration enu = request.getAttributeNames();
        // enu.hasMoreElements() ;) {
        // logger.debug(">>> found "+enu.nextElement().toString());
        // }
        // tbh
        discNotes = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
        if (discNotes == null) {
            discNotes = new FormDiscrepancyNotes();
            session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes);
        }
        DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes);
        v.addValidation(INPUT_STARTDATE_PREFIX, Validator.IS_DATE_TIME);
        v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX);
        if (!strEnd.equals("")) {
            v.addValidation(INPUT_ENDDATE_PREFIX, Validator.IS_DATE_TIME);
            v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX);
        }
        v.addValidation(INPUT_STUDY_EVENT_DEFINITION, Validator.ENTITY_EXISTS_IN_STUDY, seddao, studyWithEventDefinitions);
        // v.addValidation(INPUT_STUDY_SUBJECT, Validator.ENTITY_EXISTS_IN_STUDY, sdao, currentStudy);
        // removed tbh 11/2009
        //Made optional field-issue-4904.
        //v.addValidation(INPUT_LOCATION, Validator.NO_BLANKS);
        v.addValidation(INPUT_STUDY_SUBJECT_LABEL, Validator.NO_BLANKS);
        v.addValidation(INPUT_LOCATION, Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 2000);
        if (currentStudy.getStudyParameterConfig().getEventLocationRequired().equalsIgnoreCase("required")) {
            v.addValidation(INPUT_LOCATION, Validator.NO_BLANKS);
        }
        v.alwaysExecuteLastValidation(INPUT_LOCATION);
        boolean hasScheduledEvent = false;
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            if (!StringUtil.isBlank(fp.getString(this.INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i]))) {
                // logger.debug("has scheduled definition******");
                v.addValidation(this.INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i], Validator.ENTITY_EXISTS_IN_STUDY, seddao, studyWithEventDefinitions);
                if (currentStudy.getStudyParameterConfig().getEventLocationRequired().equalsIgnoreCase("required")) {
                    v.addValidation(INPUT_SCHEDULED_LOCATION[i], Validator.NO_BLANKS);
                    v.addValidation(INPUT_SCHEDULED_LOCATION[i], Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 2000);
                    v.alwaysExecuteLastValidation(INPUT_SCHEDULED_LOCATION[i]);
                }
                v.addValidation(INPUT_STARTDATE_PREFIX_SCHEDULED[i], Validator.IS_DATE_TIME);
                v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX_SCHEDULED[i]);
                if (!strEndScheduled[i].equals("")) {
                    v.addValidation(INPUT_ENDDATE_PREFIX_SCHEDULED[i], Validator.IS_DATE_TIME);
                    v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
                }
                hasScheduledEvent = true;
                fp.addPresetValue(DISPLAY_SCHEDULED[i], "all");
            } else {
                fp.addPresetValue(DISPLAY_SCHEDULED[i], "none");
            }
        }
        HashMap errors = v.validate();
        // logger.debug("v is not null *****");
        String location = resword.getString("location");
        // is a required field
        if (!StringUtil.isBlank(fp.getString(INPUT_LOCATION)) && fp.getString(INPUT_LOCATION).equalsIgnoreCase(location)) {
            Validator.addError(errors, INPUT_LOCATION, restext.getString("not_a_valid_location"));
        }
        StudyEventDefinitionBean definition = (StudyEventDefinitionBean) seddao.findByPK(fp.getInt(INPUT_STUDY_EVENT_DEFINITION));
        // StudySubjectBean studySubject = (StudySubjectBean) sdao.findByPK(fp.getInt(INPUT_STUDY_SUBJECT));
        // sdao.findByLabelAndStudy(label, study)
        StudySubjectBean studySubject = sdao.findByLabelAndStudy(fp.getString(INPUT_STUDY_SUBJECT_LABEL), currentStudy);
        // what if we are sent here from AddNewSubjectServlet.java??? we need to get that study subject bean
        if (request.getAttribute(INPUT_STUDY_SUBJECT) != null) {
            studySubject = (StudySubjectBean) request.getAttribute(INPUT_STUDY_SUBJECT);
        }
        // << tbh
        if (studySubject.getLabel() == "") {
            // add an error here, tbh
            Validator.addError(errors, INPUT_STUDY_SUBJECT, respage.getString("must_enter_subject_ID_for_identifying"));
        }
        if (!subjectMayReceiveStudyEvent(sm.getDataSource(), definition, studySubject)) {
            Validator.addError(errors, INPUT_STUDY_EVENT_DEFINITION, restext.getString("not_added_since_event_not_repeating"));
        }
        ArrayList<StudyEventDefinitionBean> definitionScheduleds = new ArrayList<StudyEventDefinitionBean>();
        int[] scheduledDefinitionIds = new int[ADDITIONAL_SCHEDULED_NUM];
        if (hasScheduledEvent) {
            for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                int pk = fp.getInt(INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i]);
                if (pk > 0) {
                    StudyEventDefinitionBean sedb = (StudyEventDefinitionBean) seddao.findByPK(pk);
                    logger.debug("scheduled def:" + pk + " " + INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i] + " " + sedb.getName());
                    definitionScheduleds.add(sedb);
                    scheduledDefinitionIds[i] = pk;
                    if (!subjectMayReceiveStudyEvent(sm.getDataSource(), sedb, studySubject)) {
                        Validator.addError(errors, INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i], restext.getString("not_added_since_event_not_repeating"));
                    }
                } else {
                    definitionScheduleds.add(new StudyEventDefinitionBean());
                }
            }
        }
        // YW, 3-12-2008, 2220 fix >>
        if (!"".equals(strEnd) && !errors.containsKey(INPUT_STARTDATE_PREFIX) && !errors.containsKey(INPUT_ENDDATE_PREFIX)) {
            end = getInputEndDate();
            if (!fp.getString(INPUT_STARTDATE_PREFIX + "Date").equals(fp.getString(INPUT_ENDDATE_PREFIX + "Date"))) {
                if (end.before(start)) {
                    Validator.addError(errors, INPUT_ENDDATE_PREFIX, resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                }
            } else {
                // if in same date, only check when both had time entered
                if (fp.timeEntered(INPUT_STARTDATE_PREFIX) && fp.timeEntered(INPUT_ENDDATE_PREFIX)) {
                    if (end.before(start) || end.equals(start)) {
                        Validator.addError(errors, INPUT_ENDDATE_PREFIX, resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                    }
                }
            }
        }
        String prevStartPrefix = INPUT_STARTDATE_PREFIX;
        Set<Integer> pickedSeds = new TreeSet<Integer>();
        pickedSeds.add(studyEventDefinitionId);
        HashMap<Integer, Integer> scheduledSeds = new HashMap<Integer, Integer>();
        scheduledSeds.put(studyEventDefinitionId, -1);
        for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
            if (scheduledDefinitionIds[i] > 0 && !errors.containsKey(INPUT_STARTDATE_PREFIX_SCHEDULED[i]) && !errors.containsKey(INPUT_ENDDATE_PREFIX_SCHEDULED[i])) {
                if (scheduledSeds.containsKey(scheduledDefinitionIds[i])) {
                    int prevStart = scheduledSeds.get(scheduledDefinitionIds[i]);
                    prevStartPrefix = prevStart == -1 ? INPUT_STARTDATE_PREFIX : INPUT_STARTDATE_PREFIX_SCHEDULED[prevStart];
                    Date prevStartDate = prevStart == -1 ? this.getInputStartDate() : this.getInputStartDateScheduled(Integer.parseInt(prevStartPrefix.charAt(prevStartPrefix.length() - 1) + ""));
                    if (fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date").equals(fp.getString(prevStartPrefix + "Date"))) {
                        // if in same day, only check when both have time
                        // inputs.
                        boolean schStartTime = fp.timeEntered(INPUT_STARTDATE_PREFIX_SCHEDULED[i]);
                        boolean startTime = fp.timeEntered(prevStartPrefix);
                        if (schStartTime && startTime) {
                            if (startScheduled[i].before(prevStartDate)) {
                                Validator.addError(errors, INPUT_STARTDATE_PREFIX_SCHEDULED[i], resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                            }
                        }
                    } else {
                        if (startScheduled[i].before(prevStartDate)) {
                            Validator.addError(errors, INPUT_STARTDATE_PREFIX_SCHEDULED[i], resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                        }
                    }
                }
                scheduledSeds.put(scheduledDefinitionIds[i], i);
                if (!strEndScheduled[i].equals("")) {
                    endScheduled[i] = fp.getDateTime(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
                    String prevEndPrefix = i > 0 ? INPUT_ENDDATE_PREFIX_SCHEDULED[i - 1] : INPUT_ENDDATE_PREFIX;
                    if (!fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Date").equals(fp.getString(prevEndPrefix + "Date"))) {
                        if (endScheduled[i].before(startScheduled[i])) {
                            Validator.addError(errors, INPUT_ENDDATE_PREFIX_SCHEDULED[i], resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                        }
                    } else {
                        // entered
                        if (fp.timeEntered(INPUT_STARTDATE_PREFIX_SCHEDULED[i]) && fp.timeEntered(INPUT_ENDDATE_PREFIX_SCHEDULED[i])) {
                            if (endScheduled[i].before(startScheduled[i]) || endScheduled[i].equals(startScheduled[i])) {
                                Validator.addError(errors, INPUT_ENDDATE_PREFIX_SCHEDULED[i], resexception.getString("input_provided_not_occure_after_previous_start_date_time"));
                            }
                        }
                    }
                }
            }
        }
        // YW >>
        logger.error("we have errors; number of this; " + errors.size());
        if (!errors.isEmpty()) {
            logger.debug("we have errors; number of this; " + errors.size());
            logger.error("found request study subject: " + fp.getString(INPUT_REQUEST_STUDY_SUBJECT));
            addPageMessage(respage.getString("errors_in_submission_see_below"));
            setInputMessages(errors);
            fp.addPresetValue(INPUT_STUDY_EVENT_DEFINITION, definition);
            fp.addPresetValue(INPUT_STUDY_SUBJECT, studySubject);
            fp.addPresetValue(INPUT_STUDY_SUBJECT_LABEL, fp.getString(INPUT_STUDY_SUBJECT_LABEL));
            fp.addPresetValue(INPUT_REQUEST_STUDY_SUBJECT, fp.getString(INPUT_REQUEST_STUDY_SUBJECT));
            fp.addPresetValue(INPUT_LOCATION, fp.getString(INPUT_LOCATION));
            for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                fp.addPresetValue(INPUT_SCHEDULED_LOCATION[i], fp.getString(INPUT_SCHEDULED_LOCATION[i]));
            }
            String[] prefixes = new String[2 + 2 * ADDITIONAL_SCHEDULED_NUM];
            prefixes[0] = INPUT_STARTDATE_PREFIX;
            prefixes[1] = INPUT_ENDDATE_PREFIX;
            int b = ADDITIONAL_SCHEDULED_NUM + 2;
            for (int i = 2; i < b; ++i) {
                prefixes[i] = INPUT_STARTDATE_PREFIX_SCHEDULED[i - 2];
            }
            for (int i = b; i < ADDITIONAL_SCHEDULED_NUM + b; ++i) {
                prefixes[i] = INPUT_ENDDATE_PREFIX_SCHEDULED[i - b];
            }
            fp.setCurrentDateTimeValuesAsPreset(prefixes);
            if (hasScheduledEvent) {
                for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                    fp.addPresetValue(INPUT_STUDY_EVENT_DEFINITION_SCHEDULED[i], definitionScheduleds.get(i));
                }
            }
            setPresetValues(fp.getPresetValues());
            ArrayList subjects = new ArrayList();
            setupBeans(subjects, eventDefinitions);
            request.setAttribute("eventDefinitionsScheduled", eventDefinitionsScheduled);
            forwardPage(Page.CREATE_NEW_STUDY_EVENT);
        } else {
            logger.debug("error is empty");
            StudyEventDAO sed = new StudyEventDAO(sm.getDataSource());
            StudyEventBean studyEvent = new StudyEventBean();
            studyEvent.setStudyEventDefinitionId(definition.getId());
            studyEvent.setStudySubjectId(studySubject.getId());
            // YW 08-17-2007 <<
            if ("-1".equals(getInputStartHour()) && "-1".equals(getInputStartMinute()) && "".equals(getInputStartHalf())) {
                studyEvent.setStartTimeFlag(false);
            } else {
                studyEvent.setStartTimeFlag(true);
            }
            // YW >>
            studyEvent.setDateStarted(start);
            // comment to find bug 1389, tbh
            logger.debug("found start date: " + local_df.format(start));
            Date[] startScheduled2 = new Date[ADDITIONAL_SCHEDULED_NUM];
            for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                startScheduled2[i] = getInputStartDateScheduled(i);
            }
            // YW, 3-12-2008, 2220 fix <<
            if (!"".equals(strEnd)) {
                // YW >>
                if ("-1".equals(getInputEndHour()) && "-1".equals(getInputEndMinute()) && "".equals(getInputEndHalf())) {
                    studyEvent.setEndTimeFlag(false);
                } else {
                    studyEvent.setEndTimeFlag(true);
                }
                studyEvent.setDateEnded(end);
            }
            studyEvent.setOwner(ub);
            studyEvent.setStatus(Status.AVAILABLE);
            studyEvent.setLocation(fp.getString(INPUT_LOCATION));
            studyEvent.setSubjectEventStatus(SubjectEventStatus.SCHEDULED);
            // ArrayList subjectsExistingEvents =
            // sed.findAllByStudyAndStudySubjectId(currentStudy,
            // studySubject.getId());
            studyEvent.setSampleOrdinal(sed.getMaxSampleOrdinal(definition, studySubject) + 1);
            studyEvent = (StudyEventBean) sed.create(studyEvent);
            if (!studyEvent.isActive()) {
                throw new OpenClinicaException(restext.getString("event_not_created_in_database"), "2");
            }
            addPageMessage(restext.getString("X_event_wiht_definition") + definition.getName() + restext.getString("X_and_subject") + studySubject.getName() + respage.getString("X_was_created_succesfully"));
            // save discrepancy notes into DB
            FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session.getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
            DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
            String[] eventFields = { INPUT_LOCATION, INPUT_STARTDATE_PREFIX, INPUT_ENDDATE_PREFIX };
            for (String element : eventFields) {
                AddNewSubjectServlet.saveFieldNotes(element, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy);
            }
            // logger.debug("here ok 3333333333333333");
            if (hasScheduledEvent) {
                for (int i = 0; i < ADDITIONAL_SCHEDULED_NUM; ++i) {
                    // which is scheduledDefinitionIds[i] > 0
                    if (scheduledDefinitionIds[i] > 0) {
                        if (subjectMayReceiveStudyEvent(sm.getDataSource(), definitionScheduleds.get(i), studySubject)) {
                            StudyEventBean studyEventScheduled = new StudyEventBean();
                            studyEventScheduled.setStudyEventDefinitionId(scheduledDefinitionIds[i]);
                            studyEventScheduled.setStudySubjectId(studySubject.getId());
                            // YW 11-14-2007
                            if ("-1".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Hour")) && "-1".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Minute")) && "".equals(fp.getString(INPUT_STARTDATE_PREFIX_SCHEDULED[i] + "Half"))) {
                                studyEventScheduled.setStartTimeFlag(false);
                            } else {
                                studyEventScheduled.setStartTimeFlag(true);
                            }
                            // YW >>
                            studyEventScheduled.setDateStarted(startScheduled[i]);
                            // YW, 3-12-2008, 2220 fix<<
                            if (!"".equals(strEndScheduled[i])) {
                                endScheduled[i] = fp.getDateTime(INPUT_ENDDATE_PREFIX_SCHEDULED[i]);
                                if ("-1".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Hour")) && "-1".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Minute")) && "".equals(fp.getString(INPUT_ENDDATE_PREFIX_SCHEDULED[i] + "Half"))) {
                                    studyEventScheduled.setEndTimeFlag(false);
                                } else {
                                    studyEventScheduled.setEndTimeFlag(true);
                                }
                            }
                            studyEventScheduled.setDateEnded(endScheduled[i]);
                            // YW >>
                            studyEventScheduled.setOwner(ub);
                            studyEventScheduled.setStatus(Status.AVAILABLE);
                            studyEventScheduled.setLocation(fp.getString(INPUT_SCHEDULED_LOCATION[i]));
                            studyEvent.setSubjectEventStatus(SubjectEventStatus.SCHEDULED);
                            // subjectsExistingEvents =
                            // sed.findAllByStudyAndStudySubjectId(
                            // currentStudy,
                            // studySubject.getId());
                            studyEventScheduled.setSampleOrdinal(sed.getMaxSampleOrdinal(definitionScheduleds.get(i), studySubject) + 1);
                            //System.out.println("create scheduled events");
                            studyEventScheduled = (StudyEventBean) sed.create(studyEventScheduled);
                            if (!studyEventScheduled.isActive()) {
                                throw new OpenClinicaException(restext.getString("scheduled_event_not_created_in_database"), "2");
                            }
                            AddNewSubjectServlet.saveFieldNotes(INPUT_SCHEDULED_LOCATION[i], fdn, dndao, studyEventScheduled.getId(), "studyEvent", currentStudy);
                            // YW 3-12-2008, 2220 fix <<
                            AddNewSubjectServlet.saveFieldNotes(INPUT_STARTDATE_PREFIX_SCHEDULED[i], fdn, dndao, studyEventScheduled.getId(), "studyEvent", currentStudy);
                            AddNewSubjectServlet.saveFieldNotes(INPUT_ENDDATE_PREFIX_SCHEDULED[i], fdn, dndao, studyEventScheduled.getId(), "studyEvent", currentStudy);
                        // YW >>
                        } else {
                            addPageMessage(restext.getString("scheduled_event_definition") + definitionScheduleds.get(i).getName() + restext.getString("X_and_subject") + studySubject.getName() + restext.getString("not_created_since_event_not_repeating") + restext.getString("event_type_already_exists"));
                        }
                    }
                }
            }
            // if
            session.removeAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
            request.setAttribute(EnterDataForStudyEventServlet.INPUT_EVENT_ID, String.valueOf(studyEvent.getId()));
            ArrayList<String> pMessage = (ArrayList<String>) request.getAttribute(SecureController.PAGE_MESSAGE);
            String url = response.encodeRedirectURL("EnterDataForStudyEvent?eventId=" + studyEvent.getId() + "&alertmessage=" + URLEncoder.encode(pMessage.get(0), "UTF-8"));
            response.sendRedirect(url);
            // + studyEvent.getId()));
            return;
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) TreeSet(java.util.TreeSet) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) Status(org.akaza.openclinica.bean.core.Status) SubjectEventStatus(org.akaza.openclinica.bean.core.SubjectEventStatus) DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) 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) Date(java.util.Date) DiscrepancyValidator(org.akaza.openclinica.control.form.DiscrepancyValidator) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO)

Example 17 with OpenClinicaException

use of org.akaza.openclinica.exception.OpenClinicaException in project OpenClinica by OpenClinica.

the class DataImportService method validateData.

/**
     * Import Data, the logic which imports the data for our data service. Note that we will return three strings string
     * 0: status, either 'success', 'fail', or 'warn'. string 1: the message string which will be returned in our soap
     * response string 2: the audit message, currently not used but will be saved in the event of a success.
     * 
     * import consist from 3 steps 1) parse xml and extract data 2) validation 3) data submission
     * 
     * @author thickerson
     * @param dataSource
     * @param resources
     * @param studyBean
     * @param userBean
     * @param xml
     * @return
     * @throws Exception
     * 
     *             /* VALIDATE data on all levels
     * 
     *             msg - contains status messages
     * @return list of errors
     */
public List<String> validateData(ODMContainer odmContainer, DataSource dataSource, CoreResources resources, StudyBean studyBean, UserAccountBean userBean, List<DisplayItemBeanWrapper> displayItemBeanWrappers, HashMap<Integer, String> importedCRFStatuses) {
    ResourceBundle respage = ResourceBundleProvider.getPageMessagesBundle();
    setRespage(respage);
    TriggerService triggerService = new TriggerService();
    StringBuffer auditMsg = new StringBuffer();
    List<String> errors = new ArrayList<String>();
    // htaycher: return back later?
    auditMsg.append(respage.getString("passed_study_check") + " ");
    auditMsg.append(respage.getString("passed_oid_metadata_check") + " ");
    // validation errors, the same as in the ImportCRFDataServlet. DRY?
    Boolean eventCRFStatusesValid = getImportCRFDataService(dataSource).eventCRFStatusesValid(odmContainer, userBean);
    List<EventCRFBean> eventCRFBeans = getImportCRFDataService(dataSource).fetchEventCRFBeans(odmContainer, userBean);
    // The following line updates a map that is used for setting the EventCRF status post import
    getImportCRFDataService(dataSource).fetchEventCRFStatuses(odmContainer, importedCRFStatuses);
    ArrayList<Integer> permittedEventCRFIds = new ArrayList<Integer>();
    // -- does the event already exist? if not, fail
    if (eventCRFBeans == null) {
        errors.add(respage.getString("the_event_crf_not_correct_status"));
        return errors;
    } else if (eventCRFBeans.isEmpty() && !eventCRFStatusesValid) {
        errors.add(respage.getString("the_event_crf_not_correct_status"));
        return errors;
    } else if (eventCRFBeans.isEmpty()) {
        errors.add(respage.getString("no_event_crfs_matching_the_xml_metadata"));
        return errors;
    }
    logger.debug("found a list of eventCRFBeans: " + eventCRFBeans.toString());
    for (EventCRFBean eventCRFBean : eventCRFBeans) {
        DataEntryStage dataEntryStage = eventCRFBean.getStage();
        Status eventCRFStatus = eventCRFBean.getStatus();
        logger.debug("Event CRF Bean: id " + eventCRFBean.getId() + ", data entry stage " + dataEntryStage.getName() + ", status " + eventCRFStatus.getName());
        if (eventCRFStatus.equals(Status.AVAILABLE) || dataEntryStage.equals(DataEntryStage.INITIAL_DATA_ENTRY) || dataEntryStage.equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE) || dataEntryStage.equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE) || dataEntryStage.equals(DataEntryStage.DOUBLE_DATA_ENTRY)) {
            permittedEventCRFIds.add(new Integer(eventCRFBean.getId()));
        } else {
            errors.add(respage.getString("your_listed_crf_in_the_file") + " " + eventCRFBean.getEventName());
            continue;
        }
    }
    if (eventCRFBeans.size() >= permittedEventCRFIds.size()) {
        auditMsg.append(respage.getString("passed_event_crf_status_check") + " ");
    } else {
        auditMsg.append(respage.getString("the_event_crf_not_correct_status") + " ");
    }
    // List<DisplayItemBeanWrapper> displayItemBeanWrappers = new ArrayList<DisplayItemBeanWrapper>();
    HashMap<String, String> totalValidationErrors = new HashMap<String, String>();
    HashMap<String, String> hardValidationErrors = new HashMap<String, String>();
    try {
        List<DisplayItemBeanWrapper> tempDisplayItemBeanWrappers = new ArrayList<DisplayItemBeanWrapper>();
        // htaycher: this should be rewritten with validator not to use request to store data
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addPreferredLocale(getLocale());
        tempDisplayItemBeanWrappers = getImportCRFDataService(dataSource).lookupValidationErrors(request, odmContainer, userBean, totalValidationErrors, hardValidationErrors, permittedEventCRFIds);
        displayItemBeanWrappers.addAll(tempDisplayItemBeanWrappers);
        logger.debug("size of total validation errors: " + (totalValidationErrors.size() + hardValidationErrors.size()));
        ArrayList<SubjectDataBean> subjectData = odmContainer.getCrfDataPostImportContainer().getSubjectData();
        if (!hardValidationErrors.isEmpty()) {
            // check here where to get group repeat key
            errors.add(triggerService.generateHardValidationErrorMessage(subjectData, hardValidationErrors, "1"));
        }
        if (!totalValidationErrors.isEmpty()) {
            errors.add(triggerService.generateHardValidationErrorMessage(subjectData, totalValidationErrors, "1"));
        }
    } catch (NullPointerException npe1) {
        // what if you have 2 event crfs but the third is a fake?
        npe1.printStackTrace();
        errors.add(respage.getString("an_error_was_thrown_while_validation_errors"));
        logger.debug("=== threw the null pointer, import === " + npe1.getMessage());
    } catch (OpenClinicaException oce1) {
        errors.add(oce1.getOpenClinicaMessage());
        logger.debug("=== threw the openclinica message, import === " + oce1.getOpenClinicaMessage());
    }
    auditMsg.append(respage.getString("passing_crf_edit_checks") + " ");
    return errors;
}
Also used : Status(org.akaza.openclinica.bean.core.Status) ResolutionStatus(org.akaza.openclinica.bean.core.ResolutionStatus) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ArrayList(java.util.ArrayList) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) DataEntryStage(org.akaza.openclinica.bean.core.DataEntryStage) TriggerService(org.akaza.openclinica.web.job.TriggerService) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) SubjectDataBean(org.akaza.openclinica.bean.submit.crfdata.SubjectDataBean) ResourceBundle(java.util.ResourceBundle) DisplayItemBeanWrapper(org.akaza.openclinica.bean.submit.DisplayItemBeanWrapper)

Example 18 with OpenClinicaException

use of org.akaza.openclinica.exception.OpenClinicaException in project OpenClinica by OpenClinica.

the class ImportCRFDataService method attachValidator.

private void attachValidator(DisplayItemBean displayItemBean, ImportHelper importHelper, DiscrepancyValidator discValidator, HashMap<String, String> hardv, javax.servlet.http.HttpServletRequest request, String eventCRFRepeatKey, String studySubjectOID) throws OpenClinicaException {
    org.akaza.openclinica.bean.core.ResponseType rt = displayItemBean.getMetadata().getResponseSet().getResponseType();
    String itemOid = displayItemBean.getItem().getOid() + "_" + eventCRFRepeatKey + "_" + displayItemBean.getData().getOrdinal() + "_" + studySubjectOID;
    if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.TEXT) || rt.equals(org.akaza.openclinica.bean.core.ResponseType.TEXTAREA)) {
        ItemFormMetadataBean ifm = displayItemBean.getMetadata();
        String widthDecimal = ifm.getWidthDecimal();
        // mm/dd/yyyy
        if (displayItemBean.getItem().getDataType().equals(ItemDataType.DATE)) {
            // pass it if it is blank, tbh
            if (!"".equals(displayItemBean.getData().getValue())) {
                String dateValue = displayItemBean.getData().getValue();
                SimpleDateFormat sdf_sqldate = new SimpleDateFormat("yyyy-MM-dd");
                sdf_sqldate.setLenient(false);
                try {
                    // htaycher: database exspects format YYYY-MM-DD
                    Date originalDate = sdf_sqldate.parse(dateValue);
                    // String replacementValue = new SimpleDateFormat("MM/dd/yyyy").format(originalDate);
                    String replacementValue = new SimpleDateFormat("yyyy-MM-dd").format(originalDate);
                    displayItemBean.getData().setValue(replacementValue);
                } catch (ParseException pe1) {
                    // next version; fail if it does not pass iso 8601
                    MessageFormat mf = new MessageFormat("");
                    mf.applyPattern(respage.getString("you_have_a_date_value_which_is_not"));
                    Object[] arguments = { displayItemBean.getItem().getOid() };
                    hardv.put(itemOid, mf.format(arguments));
                }
            }
        } else if (displayItemBean.getItem().getDataType().equals(ItemDataType.ST)) {
            int width = Validator.parseWidth(widthDecimal);
            if (width > 0 && displayItemBean.getData().getValue().length() > width) {
                hardv.put(itemOid, "This value exceeds required width=" + width);
            }
        } else // what if it's a number? should be only numbers
        if (displayItemBean.getItem().getDataType().equals(ItemDataType.INTEGER)) {
            try {
                Integer testInt = new Integer(displayItemBean.getData().getValue());
                int width = Validator.parseWidth(widthDecimal);
                if (width > 0 && displayItemBean.getData().getValue().length() > width) {
                    hardv.put(itemOid, "This value exceeds required width=" + width);
                }
            // now, didn't check decimal for testInt.
            } catch (Exception e) {
                // pass if blank, tbh 07/2010
                if (!"".equals(displayItemBean.getData().getValue())) {
                    hardv.put(itemOid, "This value is not an integer.");
                }
            }
        } else // what if it's a float? should be only numbers
        if (displayItemBean.getItem().getDataType().equals(ItemDataType.REAL)) {
            try {
                Float testFloat = new Float(displayItemBean.getData().getValue());
                int width = Validator.parseWidth(widthDecimal);
                if (width > 0 && displayItemBean.getData().getValue().length() > width) {
                    hardv.put(itemOid, "This value exceeds required width=" + width);
                }
                int decimal = Validator.parseDecimal(widthDecimal);
                if (decimal > 0 && BigDecimal.valueOf(new Double(displayItemBean.getData().getValue()).doubleValue()).scale() > decimal) {
                    hardv.put(itemOid, "This value exceeds required decimal=" + decimal);
                }
            } catch (Exception ee) {
                // pass if blank, tbh
                if (!"".equals(displayItemBean.getData().getValue())) {
                    hardv.put(itemOid, "This value is not a real number.");
                }
            }
        }
        // what if it's a phone number? how often does that happen?
        request.setAttribute(itemOid, displayItemBean.getData().getValue());
        displayItemBean = importHelper.validateDisplayItemBeanText(discValidator, displayItemBean, itemOid);
    // errors = v.validate();
    } else if (rt.equals(ResponseType.CALCULATION) || rt.equals(ResponseType.GROUP_CALCULATION)) {
        if (displayItemBean.getItem().getDataType().equals(ItemDataType.REAL)) {
            ItemFormMetadataBean ifm = displayItemBean.getMetadata();
            String widthDecimal = ifm.getWidthDecimal();
            int decimal = Validator.parseDecimal(widthDecimal);
            if (decimal > 0) {
                try {
                    Double d = new Double(displayItemBean.getData().getValue());
                    if (BigDecimal.valueOf(d).scale() > decimal) {
                        hardv.put(itemOid, "This value exceeds required decimal=" + decimal);
                    }
                } catch (Exception e) {
                    if (!"".equals(displayItemBean.getData().getValue())) {
                        hardv.put(itemOid, "This value is not a real number.");
                    }
                }
            }
        }
    } else if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.RADIO) || rt.equals(org.akaza.openclinica.bean.core.ResponseType.SELECT)) {
        // logger.info(itemOid + "is a RADIO or
        // a SELECT ");
        // adding a new hard edit check here; response_option mismatch
        String theValue = matchValueWithOptions(displayItemBean, displayItemBean.getData().getValue(), displayItemBean.getMetadata().getResponseSet().getOptions());
        request.setAttribute(itemOid, theValue);
        logger.debug("        found the value for radio/single: " + theValue);
        if (theValue == null && displayItemBean.getData().getValue() != null && !displayItemBean.getData().getValue().isEmpty()) {
            // fail it here
            logger.debug("-- theValue was NULL, the real value was " + displayItemBean.getData().getValue());
            hardv.put(itemOid, "This is not in the correct response set.");
        // throw new OpenClinicaException("One of your items did not
        // have the correct response set. Please review Item OID "
        // + displayItemBean.getItem().getOid() + " repeat key " +
        // displayItemBean.getData().getOrdinal(), "");
        }
        displayItemBean = importHelper.validateDisplayItemBeanSingleCV(discValidator, displayItemBean, itemOid);
    // errors = v.validate();
    } else if (rt.equals(org.akaza.openclinica.bean.core.ResponseType.CHECKBOX) || rt.equals(org.akaza.openclinica.bean.core.ResponseType.SELECTMULTI)) {
        // logger.info(itemOid + "is a CHECKBOX
        // or a SELECTMULTI ");
        String theValue = matchValueWithManyOptions(displayItemBean, displayItemBean.getData().getValue(), displayItemBean.getMetadata().getResponseSet().getOptions());
        request.setAttribute(itemOid, theValue);
        // logger.debug("        found the value for checkbx/multi: " + theValue);
        if (theValue == null && displayItemBean.getData().getValue() != null && !displayItemBean.getData().getValue().isEmpty()) {
            // fail it here? found an 0,1 in the place of a NULL
            // logger.debug("--  theValue was NULL, the real value was " + displayItemBean.getData().getValue());
            hardv.put(itemOid, "This is not in the correct response set.");
        }
        displayItemBean = importHelper.validateDisplayItemBeanMultipleCV(discValidator, displayItemBean, itemOid);
    // errors = v.validate();
    }
}
Also used : MessageFormat(java.text.MessageFormat) Date(java.util.Date) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) ParseException(java.text.ParseException) ResponseType(org.akaza.openclinica.bean.core.ResponseType) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) ItemFormMetadataBean(org.akaza.openclinica.bean.submit.ItemFormMetadataBean)

Example 19 with OpenClinicaException

use of org.akaza.openclinica.exception.OpenClinicaException in project OpenClinica by OpenClinica.

the class ImportCRFDataService method lookupValidationErrors.

public List<DisplayItemBeanWrapper> lookupValidationErrors(HttpServletRequest request, ODMContainer odmContainer, UserAccountBean ub, HashMap<String, String> totalValidationErrors, HashMap<String, String> hardValidationErrors, ArrayList<Integer> permittedEventCRFIds) throws OpenClinicaException {
    DisplayItemBeanWrapper displayItemBeanWrapper = null;
    HashMap validationErrors = new HashMap();
    List<DisplayItemBeanWrapper> wrappers = new ArrayList<DisplayItemBeanWrapper>();
    ImportHelper importHelper = new ImportHelper();
    FormDiscrepancyNotes discNotes = new FormDiscrepancyNotes();
    DiscrepancyValidator discValidator = new DiscrepancyValidator(request, discNotes);
    // create a second Validator, this one for hard edit checks
    HashMap<String, String> hardValidator = new HashMap<String, String>();
    StudyEventDAO studyEventDAO = new StudyEventDAO(ds);
    StudyDAO studyDAO = new StudyDAO(ds);
    StudyBean studyBean = studyDAO.findByOid(odmContainer.getCrfDataPostImportContainer().getStudyOID());
    StudySubjectDAO studySubjectDAO = new StudySubjectDAO(ds);
    StudyEventDefinitionDAO sedDao = new StudyEventDefinitionDAO(ds);
    HashMap<String, ItemDataBean> blankCheck = new HashMap<String, ItemDataBean>();
    String hardValidatorErrorMsgs = "";
    ArrayList<SubjectDataBean> subjectDataBeans = odmContainer.getCrfDataPostImportContainer().getSubjectData();
    int totalEventCRFCount = 0;
    int totalItemDataBeanCount = 0;
    for (SubjectDataBean subjectDataBean : subjectDataBeans) {
        ArrayList<DisplayItemBean> displayItemBeans = new ArrayList<DisplayItemBean>();
        logger.debug("iterating through subject data beans: found " + subjectDataBean.getSubjectOID());
        ArrayList<StudyEventDataBean> studyEventDataBeans = subjectDataBean.getStudyEventData();
        totalEventCRFCount += studyEventDataBeans.size();
        StudySubjectBean studySubjectBean = studySubjectDAO.findByOidAndStudy(subjectDataBean.getSubjectOID(), studyBean.getId());
        for (StudyEventDataBean studyEventDataBean : studyEventDataBeans) {
            int parentStudyId = studyBean.getParentStudyId();
            StudyEventDefinitionBean sedBean = sedDao.findByOidAndStudy(studyEventDataBean.getStudyEventOID(), studyBean.getId(), parentStudyId);
            ArrayList<FormDataBean> formDataBeans = studyEventDataBean.getFormData();
            logger.debug("iterating through study event data beans: found " + studyEventDataBean.getStudyEventOID());
            int ordinal = 1;
            try {
                ordinal = new Integer(studyEventDataBean.getStudyEventRepeatKey()).intValue();
            } catch (Exception e) {
            // trying to catch NPEs, because tags can be without the
            // repeat key
            }
            StudyEventBean studyEvent = (StudyEventBean) studyEventDAO.findByStudySubjectIdAndDefinitionIdAndOrdinal(studySubjectBean.getId(), sedBean.getId(), ordinal);
            displayItemBeans = new ArrayList<DisplayItemBean>();
            for (FormDataBean formDataBean : formDataBeans) {
                Map<String, Integer> groupMaxOrdinals = new HashMap<String, Integer>();
                displayItemBeanWrapper = null;
                CRFVersionDAO crfVersionDAO = new CRFVersionDAO(ds);
                EventCRFDAO eventCRFDAO = new EventCRFDAO(ds);
                ArrayList<CRFVersionBean> crfVersionBeans = crfVersionDAO.findAllByOid(formDataBean.getFormOID());
                ArrayList<ImportItemGroupDataBean> itemGroupDataBeans = formDataBean.getItemGroupData();
                if ((crfVersionBeans == null) || (crfVersionBeans.size() == 0)) {
                    MessageFormat mf = new MessageFormat("");
                    mf.applyPattern(respage.getString("your_crf_version_oid_did_not_generate"));
                    Object[] arguments = { formDataBean.getFormOID() };
                    throw new OpenClinicaException(mf.format(arguments), "");
                }
                CRFVersionBean crfVersion = crfVersionBeans.get(0);
                // if you have a mispelled form oid you get an error here
                // need to error out gracefully and post an error
                logger.debug("iterating through form beans: found " + crfVersion.getOid());
                // may be the point where we cut off item groups etc and
                // instead work on sections
                EventCRFBean eventCRFBean = eventCRFDAO.findByEventCrfVersion(studyEvent, crfVersion);
                EventDefinitionCRFDAO eventDefinitionCRFDAO = new EventDefinitionCRFDAO(ds);
                EventDefinitionCRFBean eventDefinitionCRF = eventDefinitionCRFDAO.findByStudyEventIdAndCRFVersionId(studyBean, studyEvent.getId(), crfVersion.getId());
                if (eventCRFBean != null) {
                    if (permittedEventCRFIds.contains(new Integer(eventCRFBean.getId()))) {
                        for (ImportItemGroupDataBean itemGroupDataBean : itemGroupDataBeans) {
                            groupMaxOrdinals.put(itemGroupDataBean.getItemGroupOID(), 1);
                        }
                        // correctness, tbh
                        for (ImportItemGroupDataBean itemGroupDataBean : itemGroupDataBeans) {
                            ArrayList<ItemBean> blankCheckItems = new ArrayList<ItemBean>();
                            ArrayList<ImportItemDataBean> itemDataBeans = itemGroupDataBean.getItemData();
                            logger.debug("iterating through group beans: " + itemGroupDataBean.getItemGroupOID());
                            // put a checker in here
                            ItemGroupDAO itemGroupDAO = new ItemGroupDAO(ds);
                            ItemGroupBean testBean = itemGroupDAO.findByOid(itemGroupDataBean.getItemGroupOID());
                            if (testBean == null) {
                                // TODO i18n of message
                                MessageFormat mf = new MessageFormat("");
                                mf.applyPattern(respage.getString("your_item_group_oid_for_form_oid"));
                                Object[] arguments = { itemGroupDataBean.getItemGroupOID(), formDataBean.getFormOID() };
                                throw new OpenClinicaException(mf.format(arguments), "");
                            }
                            totalItemDataBeanCount += itemDataBeans.size();
                            for (ImportItemDataBean importItemDataBean : itemDataBeans) {
                                logger.debug("   iterating through item data beans: " + importItemDataBean.getItemOID());
                                ItemDAO itemDAO = new ItemDAO(ds);
                                ItemFormMetadataDAO itemFormMetadataDAO = new ItemFormMetadataDAO(ds);
                                List<ItemBean> itemBeans = itemDAO.findByOid(importItemDataBean.getItemOID());
                                if (!itemBeans.isEmpty()) {
                                    ItemBean itemBean = itemBeans.get(0);
                                    logger.debug("   found " + itemBean.getName());
                                    // throw a null pointer? hopefully not if its been checked...
                                    DisplayItemBean displayItemBean = new DisplayItemBean();
                                    displayItemBean.setItem(itemBean);
                                    ArrayList<ItemFormMetadataBean> metadataBeans = itemFormMetadataDAO.findAllByItemId(itemBean.getId());
                                    logger.debug("      found metadata item beans: " + metadataBeans.size());
                                    int groupOrdinal = 1;
                                    if (itemGroupDataBean.getItemGroupRepeatKey() != null) {
                                        try {
                                            groupOrdinal = new Integer(itemGroupDataBean.getItemGroupRepeatKey()).intValue();
                                            if (groupOrdinal > groupMaxOrdinals.get(itemGroupDataBean.getItemGroupOID())) {
                                                groupMaxOrdinals.put(itemGroupDataBean.getItemGroupOID(), groupOrdinal);
                                            }
                                        } catch (Exception e) {
                                            // do nothing here currently, we are
                                            // looking for a number format
                                            // exception
                                            // from the above.
                                            logger.debug("found npe for group ordinals, line 344!");
                                        }
                                    }
                                    ItemDataBean itemDataBean = createItemDataBean(itemBean, eventCRFBean, importItemDataBean.getValue(), ub, groupOrdinal);
                                    blankCheckItems.add(itemBean);
                                    String newKey = groupOrdinal + "_" + itemGroupDataBean.getItemGroupOID() + "_" + itemBean.getOid() + "_" + subjectDataBean.getSubjectOID();
                                    blankCheck.put(newKey, itemDataBean);
                                    logger.info("adding " + newKey + " to blank checks");
                                    if (!metadataBeans.isEmpty()) {
                                        ItemFormMetadataBean metadataBean = metadataBeans.get(0);
                                        // also possible nullpointer
                                        displayItemBean.setData(itemDataBean);
                                        displayItemBean.setMetadata(metadataBean);
                                        displayItemBean.setEventDefinitionCRF(eventDefinitionCRF);
                                        String eventCRFRepeatKey = studyEventDataBean.getStudyEventRepeatKey();
                                        // if you do indeed leave off this in the XML it will pass but return 'null'
                                        // tbh
                                        attachValidator(displayItemBean, importHelper, discValidator, hardValidator, request, eventCRFRepeatKey, studySubjectBean.getOid());
                                        displayItemBeans.add(displayItemBean);
                                    } else {
                                        MessageFormat mf = new MessageFormat("");
                                        mf.applyPattern(respage.getString("no_metadata_could_be_found"));
                                        Object[] arguments = { importItemDataBean.getItemOID() };
                                        throw new OpenClinicaException(mf.format(arguments), "");
                                    }
                                } else {
                                    // report the error there
                                    MessageFormat mf = new MessageFormat("");
                                    mf.applyPattern(respage.getString("no_item_could_be_found"));
                                    Object[] arguments = { importItemDataBean.getItemOID() };
                                    throw new OpenClinicaException(mf.format(arguments), "");
                                }
                            }
                            // end item data beans
                            logger.debug(".. found blank check: " + blankCheck.toString());
                            for (int i = 1; i <= groupMaxOrdinals.get(itemGroupDataBean.getItemGroupOID()); i++) {
                                for (ItemBean itemBean : blankCheckItems) {
                                    String newKey = i + "_" + itemGroupDataBean.getItemGroupOID() + "_" + itemBean.getOid() + "_" + subjectDataBean.getSubjectOID();
                                    if (blankCheck.get(newKey) == null) {
                                        // if it already exists, Do Not Add It.
                                        ItemDataBean itemDataCheck = getItemDataDao().findByItemIdAndEventCRFIdAndOrdinal(itemBean.getId(), eventCRFBean.getId(), i);
                                        logger.debug("found item data bean id: " + itemDataCheck.getId() + " for ordinal " + i);
                                        if (itemDataCheck.getId() == 0) {
                                            ItemDataBean blank = createItemDataBean(itemBean, eventCRFBean, "", ub, i);
                                            DisplayItemBean displayItemBean = new DisplayItemBean();
                                            displayItemBean.setItem(itemBean);
                                            displayItemBean.setData(blank);
                                            // displayItemBean.setMetadata(metadataBean);
                                            // set event def crf?
                                            displayItemBean.setEventDefinitionCRF(eventDefinitionCRF);
                                            String eventCRFRepeatKey = studyEventDataBean.getStudyEventRepeatKey();
                                            // if you do indeed leave off this in the XML it will pass but return
                                            // 'null'
                                            // tbh
                                            displayItemBeans.add(displayItemBean);
                                            logger.debug("... adding display item bean");
                                        }
                                    }
                                    logger.debug("found a blank at " + i + ", adding " + blankCheckItems.size() + " blank items");
                                }
                            }
                            // << tbh #5548
                            blankCheckItems = new ArrayList<ItemBean>();
                        }
                    // end item group data beans
                    }
                    // matches if on permittedCRFIDs
                    CRFDAO crfDAO = new CRFDAO(ds);
                    CRFBean crfBean = crfDAO.findByVersionId(crfVersion.getCrfId());
                    // seems like an extravagance, but is not contained in crf
                    // version or event crf bean
                    validationErrors = discValidator.validate();
                    // totalValidationErrors.addAll(validationErrors);
                    for (Object errorKey : validationErrors.keySet()) {
                        // JN: to avoid duplicate errors
                        if (!totalValidationErrors.containsKey(errorKey.toString()))
                            totalValidationErrors.put(errorKey.toString(), validationErrors.get(errorKey).toString());
                        // assuming that this will be put back in to the core
                        // method's hashmap, updating statically, tbh 06/2008
                        logger.debug("+++ adding " + errorKey.toString());
                    }
                    logger.debug("-- hard validation checks: --");
                    for (Object errorKey : hardValidator.keySet()) {
                        logger.debug(errorKey.toString() + " -- " + hardValidator.get(errorKey));
                        hardValidationErrors.put(errorKey.toString(), hardValidator.get(errorKey));
                        // updating here 'statically' tbh 06/2008
                        hardValidatorErrorMsgs += hardValidator.get(errorKey) + "<br/><br/>";
                    }
                    String studyEventId = studyEvent.getId() + "";
                    String crfVersionId = crfVersion.getId() + "";
                    logger.debug("creation of wrapper: original count of display item beans " + displayItemBeans.size() + ", count of item data beans " + totalItemDataBeanCount + " count of validation errors " + validationErrors.size() + " count of study subjects " + subjectDataBeans.size() + " count of event crfs " + totalEventCRFCount + " count of hard error checks " + hardValidator.size());
                    // check if we need to overwrite
                    DataEntryStage dataEntryStage = eventCRFBean.getStage();
                    Status eventCRFStatus = eventCRFBean.getStatus();
                    boolean overwrite = false;
                    // //JN: Commenting out the following 2 lines, coz the prompt should come in the cases on
                    if (// eventCRFStatus.equals(Status.UNAVAILABLE) ||
                    dataEntryStage.equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE) || dataEntryStage.equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE) || dataEntryStage.equals(DataEntryStage.INITIAL_DATA_ENTRY) || dataEntryStage.equals(DataEntryStage.DOUBLE_DATA_ENTRY)) {
                        overwrite = true;
                    }
                    // << tbh, adding extra statuses to prevent appending, 06/2009
                    // SummaryStatsBean ssBean = new SummaryStatsBean();
                    // ssBean.setDiscNoteCount(totalValidationErrors);
                    // ssBean.setEventCrfCount(totalEventCRFCount);
                    // ssBean.setStudySubjectCount(subjectDataBeans.size());
                    // // add other stats here, tbh
                    // not working here, need to do it in a different method,
                    // tbh
                    // summary stats added tbh 05/2008
                    // JN: Changed from validationErrors to totalValidationErrors to create discrepancy notes for
                    // all
                    // the
                    displayItemBeanWrapper = new DisplayItemBeanWrapper(displayItemBeans, true, overwrite, validationErrors, studyEventId, crfVersionId, studyEventDataBean.getStudyEventOID(), studySubjectBean.getLabel(), eventCRFBean.getCreatedDate(), crfBean.getName(), crfVersion.getName(), studySubjectBean.getOid(), studyEventDataBean.getStudyEventRepeatKey());
                    // JN: Commenting out the following code, since we shouldn't re-initialize at this point, as
                    // validationErrors would get overwritten and the
                    // older errors will be overriden. Moving it after the form.
                    // Removing the comments for now, since it seems to be creating duplicate Discrepancy Notes.
                    validationErrors = new HashMap();
                    discValidator = new DiscrepancyValidator(request, discNotes);
                // reset to allow for new errors...
                }
            }
            // discValidator = new DiscrepancyValidator(request, discNotes);
            if (displayItemBeanWrapper != null && displayItemBeans.size() > 0)
                wrappers.add(displayItemBeanWrapper);
        }
    // after study events
    // remove repeats here? remove them below by only forwarding the
    // first
    // each wrapper represents an Event CRF and a Form, but we don't
    // have all events for all forms
    // need to not add a wrapper for every event + form combination,
    // but instead for every event + form combination which is present
    // look at the hack below and see what happens
    }
    // thrown, tbh 06/2008
    if (!hardValidator.isEmpty()) {
    // throw new OpenClinicaException(hardValidatorErrorMsgs, "");
    }
    return wrappers;
}
Also used : ItemBean(org.akaza.openclinica.bean.submit.ItemBean) DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) HashMap(java.util.HashMap) ItemDAO(org.akaza.openclinica.dao.submit.ItemDAO) ArrayList(java.util.ArrayList) ItemGroupDAO(org.akaza.openclinica.dao.submit.ItemGroupDAO) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) ImportItemDataBean(org.akaza.openclinica.bean.submit.crfdata.ImportItemDataBean) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) DisplayItemBeanWrapper(org.akaza.openclinica.bean.submit.DisplayItemBeanWrapper) Status(org.akaza.openclinica.bean.core.Status) SubjectEventStatus(org.akaza.openclinica.bean.core.SubjectEventStatus) EventDefinitionCRFDAO(org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) CRFDAO(org.akaza.openclinica.dao.admin.CRFDAO) CRFVersionDAO(org.akaza.openclinica.dao.submit.CRFVersionDAO) FormDiscrepancyNotes(org.akaza.openclinica.control.form.FormDiscrepancyNotes) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) EventDefinitionCRFDAO(org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO) EventDefinitionCRFBean(org.akaza.openclinica.bean.managestudy.EventDefinitionCRFBean) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) CRFBean(org.akaza.openclinica.bean.admin.CRFBean) DataEntryStage(org.akaza.openclinica.bean.core.DataEntryStage) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) EventDefinitionCRFBean(org.akaza.openclinica.bean.managestudy.EventDefinitionCRFBean) ItemGroupBean(org.akaza.openclinica.bean.submit.ItemGroupBean) ImportItemGroupDataBean(org.akaza.openclinica.bean.submit.crfdata.ImportItemGroupDataBean) ImportItemDataBean(org.akaza.openclinica.bean.submit.crfdata.ImportItemDataBean) DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) ItemFormMetadataDAO(org.akaza.openclinica.dao.submit.ItemFormMetadataDAO) MessageFormat(java.text.MessageFormat) StudyEventDataBean(org.akaza.openclinica.bean.submit.crfdata.StudyEventDataBean) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) ParseException(java.text.ParseException) DiscrepancyValidator(org.akaza.openclinica.control.form.DiscrepancyValidator) SubjectDataBean(org.akaza.openclinica.bean.submit.crfdata.SubjectDataBean) FormDataBean(org.akaza.openclinica.bean.submit.crfdata.FormDataBean) CRFVersionBean(org.akaza.openclinica.bean.submit.CRFVersionBean) ItemFormMetadataBean(org.akaza.openclinica.bean.submit.ItemFormMetadataBean)

Example 20 with OpenClinicaException

use of org.akaza.openclinica.exception.OpenClinicaException in project OpenClinica by OpenClinica.

the class ImportSpringJob method processData.

/*
     * processData, a method which should take in all XML files, check to see if they were imported previously, ? insert
     * them into the database if not, and return a message which will go to audit and to the end user.
     */
private ArrayList<String> processData(File[] dest, DataSource dataSource, ResourceBundle respage, ResourceBundle resword, UserAccountBean ub, StudyBean studyBean, File destDirectory, TriggerBean triggerBean, RuleSetServiceInterface ruleSetService) throws Exception {
    StringBuffer msg = new StringBuffer();
    StringBuffer auditMsg = new StringBuffer();
    Mapping myMap = new Mapping();
    String propertiesPath = CoreResources.PROPERTIES_DIR;
    new File(propertiesPath + File.separator + "ODM1-3-0.xsd");
    File xsdFile2 = new File(propertiesPath + File.separator + "ODM1-2-1.xsd");
    // @pgawade 18-April-2011 Fix for issue 8394
    String ODM_MAPPING_DIR_path = CoreResources.ODM_MAPPING_DIR;
    myMap.loadMapping(ODM_MAPPING_DIR_path + File.separator + "cd_odm_mapping.xml");
    Unmarshaller um1 = new Unmarshaller(myMap);
    ODMContainer odmContainer = new ODMContainer();
    // File("log.txt")));
    for (File f : dest) {
        // >> tbh
        boolean fail = false;
        // all whitespace, one or more times
        String regex = "\\s+";
        // replace with underscores
        String replacement = "_";
        String pattern = "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator + "HHmmssSSS" + File.separator;
        SimpleDateFormat sdfDir = new SimpleDateFormat(pattern);
        String generalFileDir = sdfDir.format(new java.util.Date());
        File logDestDirectory = new File(destDirectory + File.separator + generalFileDir + f.getName().replaceAll(regex, replacement) + ".log.txt");
        if (!logDestDirectory.isDirectory()) {
            logger.debug("creating new dir: " + logDestDirectory.getAbsolutePath());
            logDestDirectory.mkdirs();
        }
        File newFile = new File(logDestDirectory, "log.txt");
        // FileOutputStream out = new FileOutputStream(new
        // File(logDestDirectory, "log.txt"));
        // BufferedWriter out = null;
        // wrap the below in a try-catch?
        BufferedWriter out = new BufferedWriter(new FileWriter(newFile));
        // << tbh 06/2010
        if (f != null) {
            String firstLine = "<P>" + f.getName() + ": ";
            msg.append(firstLine);
            out.write(firstLine);
            auditMsg.append(firstLine);
        } else {
            msg.append("<P>" + respage.getString("unreadable_file") + ": ");
            out.write("<P>" + respage.getString("unreadable_file") + ": ");
            auditMsg.append("<P>" + respage.getString("unreadable_file") + ": ");
        }
        try {
            // schemaValidator.validateAgainstSchema(f, xsdFile);
            odmContainer = (ODMContainer) um1.unmarshal(new FileReader(f));
            logger.debug("Found crf data container for study oid: " + odmContainer.getCrfDataPostImportContainer().getStudyOID());
            logger.debug("found length of subject list: " + odmContainer.getCrfDataPostImportContainer().getSubjectData().size());
        } catch (Exception me1) {
            // fail against one, try another
            try {
                schemaValidator.validateAgainstSchema(f, xsdFile2);
                // for backwards compatibility, we also try to validate vs
                // 1.2.1 ODM 06/2008
                odmContainer = (ODMContainer) um1.unmarshal(new FileReader(f));
            } catch (Exception me2) {
                // not sure if we want to report me2
                MessageFormat mf = new MessageFormat("");
                mf.applyPattern(respage.getString("your_xml_is_not_well_formed"));
                Object[] arguments = { me1.getMessage() };
                msg.append(mf.format(arguments) + "<br/>");
                auditMsg.append(mf.format(arguments) + "<br/>");
                // break here with an exception
                logger.error("found an error with XML: " + msg.toString());
                // continue looping
                continue;
            }
        }
        // next: check, then import
        List<String> errors = getImportCRFDataService(dataSource).validateStudyMetadata(odmContainer, studyBean.getId());
        // the user could be in any study ...
        if (errors != null) {
            if (errors.size() > 0) {
                out.write("<P>Errors:<br/>");
                for (String error : errors) {
                    out.write(error + "<br/>");
                }
                out.write("</P>");
                // fail = true;
                // forwardPage(Page.IMPORT_CRF_DATA);
                // break here with an exception
                // throw new Exception("Your XML in the file " + f.getName()
                // + " was well formed, but generated metadata errors: " +
                // errors.toString());
                // msg.append("Your XML in the file " + f.getName() +
                // " was well formed, but generated metadata errors: " +
                // errors.toString());
                MessageFormat mf = new MessageFormat("");
                mf.applyPattern(respage.getString("your_xml_in_the_file"));
                Object[] arguments = { f.getName(), errors.size() };
                auditMsg.append(mf.format(arguments) + "<br/>");
                msg.append(mf.format(arguments) + "<br/>");
                auditMsg.append("You can see the log file <a href='" + SQLInitServlet.getField("sysURL.base") + "ViewLogMessage?n=" + generalFileDir + f.getName() + "&tn=" + triggerBean.getName() + "&gn=1'>here</a>.<br/>");
                msg.append("You can see the log file <a href='" + SQLInitServlet.getField("sysURL.base") + "ViewLogMessage?n=" + generalFileDir + f.getName() + "&tn=" + triggerBean.getName() + "&gn=1'>here</a>.<br/>");
                // auditMsg.append("Your XML in the file " + f.getName() +
                // " was well formed, but generated " + errors.size() +
                // " metadata errors." + "<br/>");
                out.close();
                continue;
            } else {
                msg.append(respage.getString("passed_study_check") + "<br/>");
                msg.append(respage.getString("passed_oid_metadata_check") + "<br/>");
                auditMsg.append(respage.getString("passed_study_check") + "<br/>");
                auditMsg.append(respage.getString("passed_oid_metadata_check") + "<br/>");
            }
        }
        ImportCRFInfoContainer importCrfInfo = new ImportCRFInfoContainer(odmContainer, dataSource);
        // validation errors, the same as in the ImportCRFDataServlet. DRY?
        List<EventCRFBean> eventCRFBeans = getImportCRFDataService(dataSource).fetchEventCRFBeans(odmContainer, ub);
        ArrayList<Integer> permittedEventCRFIds = new ArrayList<Integer>();
        Boolean eventCRFStatusesValid = getImportCRFDataService(dataSource).eventCRFStatusesValid(odmContainer, ub);
        List<DisplayItemBeanWrapper> displayItemBeanWrappers = new ArrayList<DisplayItemBeanWrapper>();
        HashMap<String, String> totalValidationErrors = new HashMap<String, String>();
        HashMap<String, String> hardValidationErrors = new HashMap<String, String>();
        // The following map is used for setting the EventCRF status post import.
        HashMap<Integer, String> importedCRFStatuses = getImportCRFDataService(dataSource).fetchEventCRFStatuses(odmContainer);
        // -- does the event already exist? if not, fail
        if (eventCRFBeans == null) {
            fail = true;
            msg.append(respage.getString("no_event_status_matching"));
            out.write(respage.getString("no_event_status_matching"));
            out.close();
            continue;
        } else if (!eventCRFBeans.isEmpty()) {
            logger.debug("found a list of eventCRFBeans: " + eventCRFBeans.toString());
            for (EventCRFBean eventCRFBean : eventCRFBeans) {
                DataEntryStage dataEntryStage = eventCRFBean.getStage();
                Status eventCRFStatus = eventCRFBean.getStatus();
                logger.debug("Event CRF Bean: id " + eventCRFBean.getId() + ", data entry stage " + dataEntryStage.getName() + ", status " + eventCRFStatus.getName());
                if (eventCRFStatus.equals(Status.AVAILABLE) || dataEntryStage.equals(DataEntryStage.INITIAL_DATA_ENTRY) || dataEntryStage.equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE) || dataEntryStage.equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE) || dataEntryStage.equals(DataEntryStage.DOUBLE_DATA_ENTRY)) {
                    permittedEventCRFIds.add(new Integer(eventCRFBean.getId()));
                } else {
                    // break out here with an exception
                    // throw new
                    // Exception("Your listed Event CRF in the file " +
                    // f.getName() +
                    // " does not exist, or has already been locked for import."
                    // );
                    MessageFormat mf = new MessageFormat("");
                    mf.applyPattern(respage.getString("your_listed_crf_in_the_file"));
                    Object[] arguments = { f.getName() };
                    msg.append(mf.format(arguments) + "<br/>");
                    auditMsg.append(mf.format(arguments) + "<br/>");
                    out.write(mf.format(arguments) + "<br/>");
                    out.close();
                    continue;
                }
            }
            if (eventCRFBeans.size() >= permittedEventCRFIds.size()) {
                msg.append(respage.getString("passed_event_crf_status_check") + "<br/>");
                auditMsg.append(respage.getString("passed_event_crf_status_check") + "<br/>");
            } else {
                fail = true;
                msg.append(respage.getString("the_event_crf_not_correct_status") + "<br/>");
                auditMsg.append(respage.getString("the_event_crf_not_correct_status") + "<br/>");
            }
            // create a 'fake' request to generate the validation errors
            // here, tbh 05/2009
            MockHttpServletRequest request = new MockHttpServletRequest();
            // Locale locale = new Locale("en-US");
            request.addPreferredLocale(locale);
            try {
                List<DisplayItemBeanWrapper> tempDisplayItemBeanWrappers = new ArrayList<DisplayItemBeanWrapper>();
                tempDisplayItemBeanWrappers = getImportCRFDataService(dataSource).lookupValidationErrors(request, odmContainer, ub, totalValidationErrors, hardValidationErrors, permittedEventCRFIds);
                logger.debug("size of total validation errors: " + totalValidationErrors.size());
                displayItemBeanWrappers.addAll(tempDisplayItemBeanWrappers);
            } catch (NullPointerException npe1) {
                // what if you have 2 event crfs but the third is a fake?
                npe1.printStackTrace();
                fail = true;
                logger.debug("threw a NPE after calling lookup validation errors");
                msg.append(respage.getString("an_error_was_thrown_while_validation_errors") + "<br/>");
                auditMsg.append(respage.getString("an_error_was_thrown_while_validation_errors") + "<br/>");
                out.write(respage.getString("an_error_was_thrown_while_validation_errors") + "<br/>");
                logger.debug("=== threw the null pointer, import ===");
            } catch (OpenClinicaException oce1) {
                fail = true;
                logger.error("threw an OCE after calling lookup validation errors " + oce1.getOpenClinicaMessage());
                msg.append(oce1.getOpenClinicaMessage() + "<br/>");
                // auditMsg.append(oce1.getOpenClinicaMessage() + "<br/>");
                out.write(oce1.getOpenClinicaMessage() + "<br/>");
            }
        } else if (!eventCRFStatusesValid) {
            fail = true;
            msg.append(respage.getString("the_event_crf_not_correct_status"));
            out.write(respage.getString("the_event_crf_not_correct_status"));
            out.close();
            continue;
        } else {
            // fail = true;
            // break here with an exception
            msg.append(respage.getString("no_event_crfs_matching_the_xml_metadata") + "<br/>");
            // auditMsg.append(respage.getString("no_event_crfs_matching_the_xml_metadata")
            // + "<br/>");
            out.write(respage.getString("no_event_crfs_matching_the_xml_metadata") + "<br/>");
            // throw new Exception(msg.toString());
            out.close();
            continue;
        }
        ArrayList<SubjectDataBean> subjectData = odmContainer.getCrfDataPostImportContainer().getSubjectData();
        if (!hardValidationErrors.isEmpty()) {
            String messageHardVals = triggerService.generateHardValidationErrorMessage(subjectData, hardValidationErrors, false);
            // byte[] messageHardValsBytes = messageHardVals.getBytes();
            out.write(messageHardVals);
            msg.append(respage.getString("file_generated_hard_validation_error"));
            // here we create a file and append the data, tbh 06/2010
            fail = true;
        } else {
            if (!totalValidationErrors.isEmpty()) {
                String totalValErrors = triggerService.generateHardValidationErrorMessage(subjectData, totalValidationErrors, false);
                out.write(totalValErrors);
            // here we also append data to the file, tbh 06/2010
            }
            String validMsgs = triggerService.generateValidMessage(subjectData, totalValidationErrors);
            out.write(validMsgs);
        // third place to append data to the file? tbh 06/2010
        }
        // << tbh 05/2010, bug #5110, leave off the detailed reports
        out.close();
        if (fail) {
            // forwardPage(Page.IMPORT_CRF_DATA);
            // break here with an exception
            // throw new Exception("Problems encountered with file " +
            // f.getName() + ": " + msg.toString());
            MessageFormat mf = new MessageFormat("");
            mf.applyPattern(respage.getString("problems_encountered_with_file"));
            Object[] arguments = { f.getName(), msg.toString() };
            msg = new StringBuffer(mf.format(arguments) + "<br/>");
            out.close();
            auditMsg.append("You can see the log file <a href='" + SQLInitServlet.getField("sysURL.base") + "ViewLogMessage?n=" + generalFileDir + f.getName() + "&tn=" + triggerBean.getName() + "&gn=1'>here</a>.<br/>");
            msg.append("You can see the log file <a href='" + SQLInitServlet.getField("sysURL.base") + "ViewLogMessage?n=" + generalFileDir + f.getName() + "&tn=" + triggerBean.getName() + "&gn=1'>here</a>.<br/>");
            // ": " + msg.toString() + "<br/>");
            continue;
        } else {
            msg.append(respage.getString("passing_crf_edit_checks") + "<br/>");
            auditMsg.append(respage.getString("passing_crf_edit_checks") + "<br/>");
            // session.setAttribute("importedData",
            // displayItemBeanWrappers);
            // session.setAttribute("validationErrors",
            // totalValidationErrors);
            // session.setAttribute("hardValidationErrors",
            // hardValidationErrors);
            // above are to be sent to the user, but what kind of message
            // can we make of them here?
            // if hard validation errors are present, we only generate one
            // table
            // otherwise, we generate the other two: validation errors and
            // valid data
            logger.debug("found total validation errors: " + totalValidationErrors.size());
            SummaryStatsBean ssBean = getImportCRFDataService(dataSource).generateSummaryStatsBean(odmContainer, displayItemBeanWrappers, importCrfInfo);
            // msg.append("===+");
            // the above is a special key that we will use to split the
            // message into two parts
            // a shorter version for the audit and
            // a longer version for the email
            msg.append(triggerService.generateSummaryStatsMessage(ssBean, respage) + "<br/>");
            // session.setAttribute("summaryStats", ssBean);
            // will have to set hard edit checks here as well
            // session.setAttribute("subjectData",
            // ArrayList<SubjectDataBean> subjectData =
            // odmContainer.getCrfDataPostImportContainer().getSubjectData();
            // forwardPage(Page.VERIFY_IMPORT_SERVLET);
            // instead of forwarding, go ahead and save it all, sending a
            // message at the end
            msg.append(triggerService.generateSkippedCRFMessage(importCrfInfo, resword) + "<br/>");
            // setup ruleSets to run if applicable
            List<ImportDataRuleRunnerContainer> containers = this.ruleRunSetup(dataSource, studyBean, ub, ruleSetService, odmContainer);
            CrfBusinessLogicHelper crfBusinessLogicHelper = new CrfBusinessLogicHelper(dataSource);
            for (DisplayItemBeanWrapper wrapper : displayItemBeanWrappers) {
                boolean resetSDV = false;
                int eventCrfBeanId = -1;
                EventCRFBean eventCrfBean = new EventCRFBean();
                logger.debug("right before we check to make sure it is savable: " + wrapper.isSavable());
                if (wrapper.isSavable()) {
                    ArrayList<Integer> eventCrfInts = new ArrayList<Integer>();
                    logger.debug("wrapper problems found : " + wrapper.getValidationErrors().toString());
                    itemDataDao.setFormatDates(false);
                    for (DisplayItemBean displayItemBean : wrapper.getDisplayItemBeans()) {
                        eventCrfBeanId = displayItemBean.getData().getEventCRFId();
                        eventCrfBean = (EventCRFBean) eventCrfDao.findByPK(eventCrfBeanId);
                        logger.debug("found value here: " + displayItemBean.getData().getValue());
                        logger.debug("found status here: " + eventCrfBean.getStatus().getName());
                        ItemDataBean itemDataBean = new ItemDataBean();
                        itemDataBean = itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(displayItemBean.getItem().getId(), eventCrfBean.getId(), displayItemBean.getData().getOrdinal());
                        if (wrapper.isOverwrite() && itemDataBean.getStatus() != null) {
                            logger.debug("just tried to find item data bean on item name " + displayItemBean.getItem().getName());
                            if (!itemDataBean.getValue().equals(displayItemBean.getData().getValue()))
                                resetSDV = true;
                            itemDataBean.setUpdatedDate(new Date());
                            itemDataBean.setUpdater(ub);
                            itemDataBean.setValue(displayItemBean.getData().getValue());
                            // set status?
                            itemDataDao.update(itemDataBean);
                            logger.debug("updated: " + itemDataBean.getItemId());
                            // need to set pk here in order to create dn
                            displayItemBean.getData().setId(itemDataBean.getId());
                        } else {
                            resetSDV = true;
                            itemDataDao.create(displayItemBean.getData());
                            logger.debug("created: " + displayItemBean.getData().getItemId());
                            ItemDataBean itemDataBean2 = itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(displayItemBean.getItem().getId(), eventCrfBean.getId(), displayItemBean.getData().getOrdinal());
                            logger.debug("found: id " + itemDataBean2.getId() + " name " + itemDataBean2.getName());
                            displayItemBean.getData().setId(itemDataBean2.getId());
                        }
                        ItemDAO idao = new ItemDAO(dataSource);
                        ItemBean ibean = (ItemBean) idao.findByPK(displayItemBean.getData().getItemId());
                        logger.debug("*** checking for validation errors: " + ibean.getName());
                        String itemOid = displayItemBean.getItem().getOid() + "_" + wrapper.getStudyEventRepeatKey() + "_" + displayItemBean.getData().getOrdinal() + "_" + wrapper.getStudySubjectOid();
                        if (wrapper.getValidationErrors().containsKey(itemOid)) {
                            ArrayList messageList = (ArrayList) wrapper.getValidationErrors().get(itemOid);
                            for (int iter = 0; iter < messageList.size(); iter++) {
                                String message = (String) messageList.get(iter);
                                DiscrepancyNoteBean parentDn = createDiscrepancyNote(ibean, message, eventCrfBean, displayItemBean, null, ub, dataSource, studyBean);
                                createDiscrepancyNote(ibean, message, eventCrfBean, displayItemBean, parentDn.getId(), ub, dataSource, studyBean);
                                logger.debug("*** created disc note with message: " + message);
                            // displayItemBean);
                            }
                        }
                        // Update CRF status
                        if (!eventCrfInts.contains(new Integer(eventCrfBean.getId()))) {
                            String eventCRFStatus = importedCRFStatuses.get(new Integer(eventCrfBean.getId()));
                            if (eventCRFStatus != null && eventCRFStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()) && eventCrfBean.getStatus().isAvailable()) {
                                crfBusinessLogicHelper.markCRFStarted(eventCrfBean, ub);
                            } else {
                                crfBusinessLogicHelper.markCRFComplete(eventCrfBean, ub);
                            }
                            logger.debug("*** just updated event crf bean: " + eventCrfBean.getId());
                            eventCrfInts.add(new Integer(eventCrfBean.getId()));
                        }
                    }
                    itemDataDao.setFormatDates(true);
                    // Reset the SDV status if item data has been changed or added
                    if (eventCrfBean != null && resetSDV)
                        eventCrfDao.setSDVStatus(false, ub.getId(), eventCrfBean.getId());
                }
            }
            // msg.append("===+");
            msg.append(respage.getString("data_has_been_successfully_import") + "<br/>");
            auditMsg.append(respage.getString("data_has_been_successfully_import") + "<br/>");
            // MessageFormat mf = new MessageFormat("");
            String linkMessage = respage.getString("you_can_review_the_data") + SQLInitServlet.getField("sysURL.base") + respage.getString("you_can_review_the_data_2") + SQLInitServlet.getField("sysURL.base") + respage.getString("you_can_review_the_data_3") + generalFileDir + f.getName() + "&tn=" + triggerBean.getFullName() + "&gn=1" + respage.getString("you_can_review_the_data_4") + "<br/>";
            // mf.applyPattern(respage.getString("you_can_review_the_data"));
            // Object[] arguments = {
            // SQLInitServlet.getField("sysURL.base"),
            // SQLInitServlet.getField("sysURL.base"), f.getName() };
            msg.append(linkMessage);
            auditMsg.append(linkMessage);
            // was here but is now moved up, tbh
            // String finalLine =
            // "<p>You can review the entered data <a href='" +
            // SQLInitServlet.getField("sysURL.base") +
            // "ListStudySubjects'>here</a>.";
            // >> tbh additional message
            // "you can review the validation messages here" <-- where
            // 'here' is a link to view an external file
            // i.e. /ViewExternal?n=file_name.txt
            // << tbh 06/2010
            // msg.append(finalLine);
            // auditMsg.append(finalLine);
            auditMsg.append(this.runRules(studyBean, ub, containers, ruleSetService, ExecutionMode.SAVE));
        }
    }
    // end for loop
    // is the writer still not closed? try to close it
    ArrayList<String> retList = new ArrayList<String>();
    retList.add(msg.toString());
    retList.add(auditMsg.toString());
    // msg.toString();
    return retList;
}
Also used : ItemBean(org.akaza.openclinica.bean.submit.ItemBean) DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) HashMap(java.util.HashMap) ItemDAO(org.akaza.openclinica.dao.submit.ItemDAO) Date(java.util.Date) ArrayList(java.util.ArrayList) Mapping(org.exolab.castor.mapping.Mapping) SummaryStatsBean(org.akaza.openclinica.bean.submit.crfdata.SummaryStatsBean) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) List(java.util.List) ArrayList(java.util.ArrayList) Unmarshaller(org.exolab.castor.xml.Unmarshaller) DisplayItemBeanWrapper(org.akaza.openclinica.bean.submit.DisplayItemBeanWrapper) TransactionStatus(org.springframework.transaction.TransactionStatus) Status(org.akaza.openclinica.bean.core.Status) ResolutionStatus(org.akaza.openclinica.bean.core.ResolutionStatus) DataEntryStage(org.akaza.openclinica.bean.core.DataEntryStage) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) File(java.io.File) FileWriter(java.io.FileWriter) ImportDataRuleRunnerContainer(org.akaza.openclinica.logic.rulerunner.ImportDataRuleRunnerContainer) BufferedWriter(java.io.BufferedWriter) ODMContainer(org.akaza.openclinica.bean.submit.crfdata.ODMContainer) ImportCRFInfoContainer(org.akaza.openclinica.control.submit.ImportCRFInfoContainer) DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) FileReader(java.io.FileReader) MessageFormat(java.text.MessageFormat) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) JobExecutionException(org.quartz.JobExecutionException) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException) Date(java.util.Date) SubjectDataBean(org.akaza.openclinica.bean.submit.crfdata.SubjectDataBean) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

OpenClinicaException (org.akaza.openclinica.exception.OpenClinicaException)23 ArrayList (java.util.ArrayList)18 HashMap (java.util.HashMap)11 ItemBean (org.akaza.openclinica.bean.submit.ItemBean)8 DisplayItemBean (org.akaza.openclinica.bean.submit.DisplayItemBean)7 ItemFormMetadataBean (org.akaza.openclinica.bean.submit.ItemFormMetadataBean)7 ItemDAO (org.akaza.openclinica.dao.submit.ItemDAO)7 Connection (java.sql.Connection)6 PreparedStatement (java.sql.PreparedStatement)6 ResultSet (java.sql.ResultSet)6 SQLException (java.sql.SQLException)6 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)6 ItemFormMetadataDAO (org.akaza.openclinica.dao.submit.ItemFormMetadataDAO)6 MessageFormat (java.text.MessageFormat)5 EventCRFBean (org.akaza.openclinica.bean.submit.EventCRFBean)5 ItemGroupBean (org.akaza.openclinica.bean.submit.ItemGroupBean)5 StudyDAO (org.akaza.openclinica.dao.managestudy.StudyDAO)5 Iterator (java.util.Iterator)4 List (java.util.List)4 Status (org.akaza.openclinica.bean.core.Status)4