use of org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO 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;
}
}
}
use of org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO in project OpenClinica by OpenClinica.
the class StudyModuleController method handleMainPage.
@RequestMapping(method = RequestMethod.GET)
public ModelMap handleMainPage(HttpServletRequest request, HttpServletResponse response) {
ModelMap map = new ModelMap();
// Todo need something to reset panel from all the Spring Controllers
StudyInfoPanel panel = new StudyInfoPanel();
UserAccountBean userBean = (UserAccountBean) request.getSession().getAttribute("userBean");
if (!mayProceed(request)) {
try {
response.sendRedirect(request.getContextPath() + "/MainMenu?message=authentication_failed");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
panel.reset();
request.getSession().setAttribute("panel", panel);
// setUpSidebar(request);
ResourceBundleProvider.updateLocale(LocaleResolver.getLocale(request));
StudyBean currentStudy = (StudyBean) request.getSession().getAttribute("study");
eventDefinitionCRFDao = new EventDefinitionCRFDAO(dataSource);
studyEventDefinitionDao = new StudyEventDefinitionDAO(dataSource);
crfDao = new CRFDAO(dataSource);
studyGroupClassDao = new StudyGroupClassDAO(dataSource);
studyDao = new StudyDAO(dataSource);
userDao = new UserAccountDAO(dataSource);
ruleDao = new RuleDAO(dataSource);
StudyModuleStatus sms = studyModuleStatusDao.findByStudyId(currentStudy.getId());
if (sms == null) {
sms = new StudyModuleStatus();
sms.setStudyId(currentStudy.getId());
}
int crfCount = crfDao.findAllByStudy(currentStudy.getId()).size();
int crfWithEventDefinition = crfDao.findAllActiveByDefinitions(currentStudy.getId()).size();
int totalCrf = crfCount + crfWithEventDefinition;
// int eventDefinitionCount = eventDefinitionCRFDao.findAllActiveByStudy(currentStudy).size();
int eventDefinitionCount = studyEventDefinitionDao.findAllActiveByStudy(currentStudy).size();
int subjectGroupCount = studyGroupClassDao.findAllActiveByStudy(currentStudy).size();
// List<RuleSetBean> ruleSets = ruleSetService.getRuleSetsByStudy(currentStudy);
// ruleSets = ruleSetService.filterByStatusEqualsAvailableOnlyRuleSetRules(ruleSets);
int ruleCount = ruleSetService.getCountByStudy(currentStudy);
int siteCount = studyDao.findOlnySiteIdsByStudy(currentStudy).size();
int userCount = userDao.findAllUsersByStudy(currentStudy.getId()).size();
Collection childStudies = studyDao.findAllByParent(currentStudy.getId());
Map childStudyUserCount = new HashMap();
for (Object sb : childStudies) {
StudyBean childStudy = (StudyBean) sb;
childStudyUserCount.put(childStudy.getName(), userDao.findAllUsersByStudy(childStudy.getId()).size());
}
if (sms.getCrf() == 0) {
sms.setCrf(StudyModuleStatus.NOT_STARTED);
}
if (sms.getCrf() != 3 && totalCrf > 0) {
sms.setCrf(StudyModuleStatus.IN_PROGRESS);
}
if (sms.getEventDefinition() == 0) {
sms.setEventDefinition(StudyModuleStatus.NOT_STARTED);
}
if (sms.getEventDefinition() != 3 && eventDefinitionCount > 0) {
sms.setEventDefinition(StudyModuleStatus.IN_PROGRESS);
}
if (sms.getSubjectGroup() == 0) {
sms.setSubjectGroup(StudyModuleStatus.NOT_STARTED);
}
if (sms.getSubjectGroup() != 3 && subjectGroupCount > 0) {
sms.setSubjectGroup(StudyModuleStatus.IN_PROGRESS);
}
if (sms.getRule() == 0) {
sms.setRule(StudyModuleStatus.NOT_STARTED);
}
if (sms.getRule() != 3 && ruleCount > 0) {
sms.setRule(StudyModuleStatus.IN_PROGRESS);
}
if (sms.getSite() == 0) {
sms.setSite(StudyModuleStatus.NOT_STARTED);
}
if (sms.getSite() != 3 && siteCount > 0) {
sms.setSite(StudyModuleStatus.IN_PROGRESS);
}
if (sms.getUsers() == 0) {
sms.setUsers(StudyModuleStatus.NOT_STARTED);
}
if (sms.getUsers() != 3 && userCount > 0) {
sms.setUsers(StudyModuleStatus.IN_PROGRESS);
}
map.addAttribute(sms);
map.addAttribute("crfCount", totalCrf);
map.addAttribute("eventDefinitionCount", eventDefinitionCount);
map.addAttribute("subjectGroupCount", subjectGroupCount);
map.addAttribute("ruleCount", ruleCount);
map.addAttribute("siteCount", siteCount);
map.addAttribute("userCount", userCount);
map.addAttribute("childStudyUserCount", childStudyUserCount);
map.addAttribute("studyId", currentStudy.getId());
map.addAttribute("currentStudy", currentStudy);
// Load Participate registration information
String portalURL = CoreResources.getField("portalURL");
map.addAttribute("portalURL", portalURL);
if (portalURL != null && !portalURL.equals("")) {
String participateOCStatus = currentStudy.getStudyParameterConfig().getParticipantPortal();
ParticipantPortalRegistrar registrar = new ParticipantPortalRegistrar();
Authorization pManageAuthorization = registrar.getAuthorization(currentStudy.getOid());
String participateStatus = "";
String url = "";
try {
URL pManageUrl = new URL(portalURL);
if (pManageAuthorization != null && pManageAuthorization.getAuthorizationStatus() != null && pManageAuthorization.getAuthorizationStatus().getStatus() != null)
participateStatus = pManageAuthorization.getAuthorizationStatus().getStatus();
map.addAttribute("participateURL", pManageUrl);
map.addAttribute("participateOCStatus", participateOCStatus);
map.addAttribute("participateStatus", participateStatus);
if (pManageAuthorization != null && pManageAuthorization.getStudy() != null && pManageAuthorization.getStudy().getHost() != null && !pManageAuthorization.getStudy().getHost().equals("")) {
url = pManageUrl.getProtocol() + "://" + pManageAuthorization.getStudy().getHost() + "." + pManageUrl.getHost() + ((pManageUrl.getPort() > 0) ? ":" + String.valueOf(pManageUrl.getPort()) : "");
}
} catch (MalformedURLException e) {
logger.error(e.getMessage());
logger.error(ExceptionUtils.getStackTrace(e));
}
map.addAttribute("participateURLDisplay", url);
map.addAttribute("participateURLFull", url + "/#/login");
}
// Load Randomization information
String moduleManager = CoreResources.getField("moduleManager");
map.addAttribute("moduleManager", moduleManager);
if (moduleManager != null && !moduleManager.equals("")) {
String randomizationOCStatus = currentStudy.getStudyParameterConfig().getRandomization();
RandomizationRegistrar randomizationRegistrar = new RandomizationRegistrar();
SeRandomizationDTO randomization = null;
try {
randomization = randomizationRegistrar.getCachedRandomizationDTOObject(currentStudy.getOid(), true);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String randomizationStatus = "";
URL randomizeUrl = null;
if (randomization != null && randomization.getStatus() != null) {
randomizationStatus = randomization.getStatus();
if (randomization.getUrl() != null) {
try {
randomizeUrl = new URL(randomization.getUrl());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
map.addAttribute("randomizeURL", randomizeUrl);
map.addAttribute("randomizationOCStatus", randomizationOCStatus);
map.addAttribute("randomizationStatus", randomizationStatus);
}
// @pgawade 13-April-2011- #8877: Added the rule designer URL
if (null != coreResources) {
map.addAttribute("ruleDesignerURL", coreResources.getField("designer.url"));
map.addAttribute("contextPath", getContextPath(request));
logMe("before checking getHostPath url = " + request.getRequestURL());
// JN: for the eclinicalhosting the https is not showing up in the request path, going for a fix of taking
// the hostpath from sysurl
// map.addAttribute("hostPath", getHostPath(request));
map.addAttribute("hostPath", getHostPathFromSysUrl(coreResources.getField("sysURL.base"), request.getContextPath()));
map.addAttribute("path", "pages/studymodule");
}
// UserAccountBean userBean = (UserAccountBean) request.getSession().getAttribute("userBean");
request.setAttribute("userBean", userBean);
ArrayList statusMap = Status.toStudyUpdateMembersList();
// statusMap.add(Status.PENDING);
request.setAttribute("statusMap", statusMap);
if (currentStudy.getParentStudyId() > 0) {
StudyBean parentStudy = (StudyBean) studyDao.findByPK(currentStudy.getParentStudyId());
request.setAttribute("parentStudy", parentStudy);
}
ArrayList pageMessages = new ArrayList();
if (request.getSession().getAttribute("pageMessages") != null) {
pageMessages.addAll((ArrayList) request.getSession().getAttribute("pageMessages"));
request.setAttribute("pageMessages", pageMessages);
request.getSession().removeAttribute("pageMessages");
}
ArrayList regMessages = new ArrayList();
if (request.getSession().getAttribute(REG_MESSAGE) != null) {
regMessages.addAll((ArrayList) request.getSession().getAttribute(REG_MESSAGE));
request.setAttribute(REG_MESSAGE, regMessages);
request.getSession().removeAttribute(REG_MESSAGE);
}
return map;
}
use of org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO in project OpenClinica by OpenClinica.
the class ImportCRFDataService method fetchEventCRFStatuses.
/*
* purpose: Build a map of EventCRFs and the statuses they should have post-import. Assumes EventCRFs have been
* created for "Not Started" forms.
*/
public HashMap<Integer, String> fetchEventCRFStatuses(ODMContainer odmContainer) {
HashMap<Integer, String> eventCRFStatuses = new HashMap<Integer, String>();
EventCRFDAO eventCrfDAO = new EventCRFDAO(ds);
StudySubjectDAO studySubjectDAO = new StudySubjectDAO(ds);
StudyEventDefinitionDAO studyEventDefinitionDAO = new StudyEventDefinitionDAO(ds);
StudyDAO studyDAO = new StudyDAO(ds);
StudyEventDAO studyEventDAO = new StudyEventDAO(ds);
String studyOID = odmContainer.getCrfDataPostImportContainer().getStudyOID();
StudyBean studyBean = studyDAO.findByOid(studyOID);
ArrayList<SubjectDataBean> subjectDataBeans = odmContainer.getCrfDataPostImportContainer().getSubjectData();
for (SubjectDataBean subjectDataBean : subjectDataBeans) {
ArrayList<StudyEventDataBean> studyEventDataBeans = subjectDataBean.getStudyEventData();
StudySubjectBean studySubjectBean = studySubjectDAO.findByOidAndStudy(subjectDataBean.getSubjectOID(), studyBean.getId());
for (StudyEventDataBean studyEventDataBean : studyEventDataBeans) {
ArrayList<FormDataBean> formDataBeans = studyEventDataBean.getFormData();
String sampleOrdinal = studyEventDataBean.getStudyEventRepeatKey() == null ? "1" : studyEventDataBean.getStudyEventRepeatKey();
StudyEventDefinitionBean studyEventDefinitionBean = studyEventDefinitionDAO.findByOidAndStudy(studyEventDataBean.getStudyEventOID(), studyBean.getId(), studyBean.getParentStudyId());
logger.info("find all by def and subject " + studyEventDefinitionBean.getName() + " study subject " + studySubjectBean.getName());
StudyEventBean studyEventBean = (StudyEventBean) studyEventDAO.findByStudySubjectIdAndDefinitionIdAndOrdinal(studySubjectBean.getId(), studyEventDefinitionBean.getId(), Integer.parseInt(sampleOrdinal));
for (FormDataBean formDataBean : formDataBeans) {
FormLayoutDAO formLayoutDAO = new FormLayoutDAO(ds);
ArrayList<FormLayoutBean> formLayoutBeans = formLayoutDAO.findAllByOid(formDataBean.getFormOID());
for (FormLayoutBean formLayoutBean : formLayoutBeans) {
ArrayList<EventCRFBean> eventCrfBeans = eventCrfDAO.findByEventSubjectFormLayout(studyEventBean, studySubjectBean, formLayoutBean);
for (EventCRFBean ecb : eventCrfBeans) {
Integer ecbId = new Integer(ecb.getId());
if (!eventCRFStatuses.keySet().contains(ecbId) && formDataBean.getEventCRFStatus() != null) {
eventCRFStatuses.put(ecb.getId(), formDataBean.getEventCRFStatus());
}
}
}
}
}
}
return eventCRFStatuses;
}
use of org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO 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;
}
use of org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO in project OpenClinica by OpenClinica.
the class SelectItemsServlet method processRequest.
@Override
public void processRequest() throws Exception {
FormProcessor fp = new FormProcessor(request);
int crfId = fp.getInt("crfId");
int defId = fp.getInt("defId");
int eventAttr = fp.getInt("eventAttr");
int subAttr = fp.getInt("subAttr");
int CRFAttr = fp.getInt("CRFAttr");
int groupAttr = fp.getInt("groupAttr");
int discAttr = fp.getInt("discAttr");
CRFDAO crfdao = new CRFDAO(sm.getDataSource());
ItemDAO idao = new ItemDAO(sm.getDataSource());
ItemFormMetadataDAO imfdao = new ItemFormMetadataDAO(sm.getDataSource());
StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
HashMap events = (HashMap) session.getAttribute(CreateDatasetServlet.EVENTS_FOR_CREATE_DATASET);
if (events == null) {
events = new HashMap();
}
request.setAttribute("eventlist", events);
logger.info("found dob setting: " + currentStudy.getStudyParameterConfig().getCollectDob());
if (crfId == 0) {
// no crf selected
if (eventAttr == 0 && subAttr == 0 && CRFAttr == 0 && groupAttr == 0 && discAttr == 0) {
forwardPage(Page.CREATE_DATASET_2);
} else if (eventAttr > 0) {
request.setAttribute("subjectAgeAtEvent", "1");
if (currentStudy.getStudyParameterConfig().getCollectDob().equals("3")) {
request.setAttribute("subjectAgeAtEvent", "0");
logger.info("dob not collected, setting age at event to 0");
}
forwardPage(Page.CREATE_DATASET_EVENT_ATTR);
} else if (subAttr > 0) {
if (currentStudy.getStudyParameterConfig().getCollectDob().equals("3")) {
logger.info("dob not collected, setting age at event to 0");
}
forwardPage(Page.CREATE_DATASET_SUB_ATTR);
} else if (CRFAttr > 0) {
forwardPage(Page.CREATE_DATASET_CRF_ATTR);
} else if (groupAttr > 0) {
// TODO set up subject group classes here?
setUpStudyGroupPage();
forwardPage(Page.CREATE_DATASET_GROUP_ATTR);
} else // else if (discAttr > 0) {
// forwardPage(Page.CREATE_DATASET_DISC_ATTR);
// }
{
forwardPage(Page.CREATE_DATASET_2);
}
return;
}
CRFBean crf = (CRFBean) crfdao.findByPK(crfId);
StudyEventDefinitionBean sed = (StudyEventDefinitionBean) seddao.findByPK(defId);
session.setAttribute("crf", crf);
session.setAttribute("definition", sed);
DatasetBean db = (DatasetBean) session.getAttribute("newDataset");
if (db == null) {
db = new DatasetBean();
}
session.setAttribute("newDataset", db);
// save current def id in the seesion to avoid duplicated def id in
// dataset
// bean
// session.setAttribute(CURRENT_DEF_ID, new Integer(defId));
ArrayList items = idao.findAllActiveByCRF(crf);
for (int i = 0; i < items.size(); i++) {
ItemBean item = (ItemBean) items.get(i);
/*
* logger.info("testing on item id "+ item.getId()+ " crf version id "+
* item.getItemMeta().getCrfVersionId());
*/
ItemFormMetadataBean meta = imfdao.findByItemIdAndCRFVersionId(item.getId(), item.getItemMeta().getCrfVersionId());
// TODO change the above data access function, tbh
// ArrayList metas = imfdao.findAllByItemId(item.getId());
meta.setCrfVersionName(item.getItemMeta().getCrfVersionName());
// logger.info("crf versionname" + meta.getCrfVersionName());
item.getItemMetas().add(meta);
// item.setItemMetas(metas);
}
HashMap itemMap = new HashMap();
for (int i = 0; i < items.size(); i++) {
ItemBean item = (ItemBean) items.get(i);
if (!itemMap.containsKey(defId + "_" + item.getId())) {
if (db.getItemMap().containsKey(defId + "_" + item.getId())) {
item.setSelected(true);
item.setDatasetItemMapKey(defId + "_" + item.getId());
// logger.info("Item got selected already11");
}
// itemMap.put(new Integer(item.getId()), item);
itemMap.put(defId + "_" + item.getId(), item);
} else {
// same item,combine the metadata
ItemBean uniqueItem = (ItemBean) itemMap.get(defId + "_" + item.getId());
uniqueItem.getItemMetas().add(item.getItemMetas().get(0));
if (db.getItemMap().containsKey(defId + "_" + uniqueItem.getId())) {
uniqueItem.setSelected(true);
// logger.info("Item got selected already22");
}
}
}
ArrayList itemArray = new ArrayList(itemMap.values());
// now sort them by ordinal/name
Collections.sort(itemArray);
session.setAttribute("allItems", itemArray);
forwardPage(Page.CREATE_DATASET_2);
}
Aggregations