public ArrayList findAllSubjectByStudy(StudyBean study) {
    this.setTypesExpected();
    ArrayList alist = new ArrayList();
    this.setTypeExpected(11, TypeNames.STRING); // ss.label
    this.setTypeExpected(12, TypeNames.STRING); // column_name
    this.setTypeExpected(13, TypeNames.INT); // subject_id

    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(study.getId()));
    variables.put(new Integer(2), new Integer(study.getId()));
    variables.put(new Integer(3), new Integer(study.getId()));

    alist = this.select(digester.getQuery("findAllSubjectByStudy"), variables);

    ArrayList al = new ArrayList();
    Iterator it = alist.iterator();
    while (it.hasNext()) {
      HashMap hm = (HashMap) it.next();
      DiscrepancyNoteBean eb = (DiscrepancyNoteBean) this.getEntityFromHashMap(hm);
      eb.setSubjectName((String) hm.get("label"));
      eb.setColumn((String) hm.get("column_name"));
      eb.setEntityId(((Integer) hm.get("subject_id")).intValue());
      al.add(eb);
    }
    return al;
  }
  private UserAccountBean createUserAccount(
      UserAccountBean rootUserAccount, StudyBean studyBean, StudySubjectBean studySubjectBean)
      throws Exception {

    UserAccountBean createdUserAccountBean = new UserAccountBean();
    createdUserAccountBean.setName(getInputUsername(studyBean, studySubjectBean));
    createdUserAccountBean.setFirstName(INPUT_FIRST_NAME);
    createdUserAccountBean.setLastName(INPUT_LAST_NAME);
    createdUserAccountBean.setEmail(INPUT_EMAIL);
    createdUserAccountBean.setInstitutionalAffiliation(INPUT_INSTITUTION);
    createdUserAccountBean.setActiveStudyId(studyBean.getId());
    String passwordHash = UserAccountBean.LDAP_PASSWORD;
    createdUserAccountBean.setPasswd(passwordHash);
    createdUserAccountBean.setPasswdTimestamp(null);
    createdUserAccountBean.setLastVisitDate(null);
    createdUserAccountBean.setActiveStudyId(studyBean.getId());
    createdUserAccountBean.setStatus(Status.DELETED);
    createdUserAccountBean.setPasswdChallengeQuestion("");
    createdUserAccountBean.setPasswdChallengeAnswer("");
    createdUserAccountBean.setPhone("");
    createdUserAccountBean.setOwner(rootUserAccount);
    createdUserAccountBean.setRunWebservices(false);
    Role r = Role.RESEARCHASSISTANT2;
    createdUserAccountBean =
        addActiveStudyRole(createdUserAccountBean, studyBean.getId(), r, rootUserAccount);
    UserType type = UserType.get(2);
    createdUserAccountBean.addUserType(type);

    UserAccountDAO udao = new UserAccountDAO(dataSource);
    createdUserAccountBean = (UserAccountBean) udao.create(createdUserAccountBean);
    // authoritiesDao.saveOrUpdate(new AuthoritiesBean(createdUserAccountBean.getName()));
    return createdUserAccountBean;
  }
 private ArrayList<StudyEventDefinitionBean> initDefinitions(StudyBean site) {
   ArrayList<StudyEventDefinitionBean> seds = new ArrayList<StudyEventDefinitionBean>();
   StudyEventDefinitionDAO sedDao = new StudyEventDefinitionDAO(sm.getDataSource());
   EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
   CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
   CRFDAO cdao = new CRFDAO(sm.getDataSource());
   StudyBean parentStudy =
       (StudyBean) new StudyDAO(sm.getDataSource()).findByPK(site.getParentStudyId());
   seds = sedDao.findAllByStudy(parentStudy);
   int start = 0;
   for (StudyEventDefinitionBean sed : seds) {
     int defId = sed.getId();
     ArrayList<EventDefinitionCRFBean> edcs =
         (ArrayList<EventDefinitionCRFBean>)
             edcdao.findAllByDefinitionAndSiteIdAndParentStudyId(
                 defId, site.getId(), parentStudy.getId());
     ArrayList<EventDefinitionCRFBean> defCrfs = new ArrayList<EventDefinitionCRFBean>();
     // sed.setCrfNum(edcs.size());
     for (EventDefinitionCRFBean edcBean : edcs) {
       int edcStatusId = edcBean.getStatus().getId();
       CRFBean crf = (CRFBean) cdao.findByPK(edcBean.getCrfId());
       int crfStatusId = crf.getStatusId();
       if (edcStatusId == 5 || edcStatusId == 7 || crfStatusId == 5 || crfStatusId == 7) {
       } else {
         ArrayList<CRFVersionBean> versions =
             (ArrayList<CRFVersionBean>) cvdao.findAllActiveByCRF(edcBean.getCrfId());
         edcBean.setVersions(versions);
         edcBean.setCrfName(crf.getName());
         CRFVersionBean defaultVersion =
             (CRFVersionBean) cvdao.findByPK(edcBean.getDefaultVersionId());
         edcBean.setDefaultVersionName(defaultVersion.getName());
         String sversionIds = edcBean.getSelectedVersionIds();
         ArrayList<Integer> idList = new ArrayList<Integer>();
         if (sversionIds.length() > 0) {
           String[] ids = sversionIds.split("\\,");
           for (String id : ids) {
             idList.add(Integer.valueOf(id));
           }
         }
         edcBean.setSelectedVersionIdList(idList);
         defCrfs.add(edcBean);
         ++start;
       }
     }
     logger.debug("definitionCrfs size=" + defCrfs.size() + " total size=" + edcs.size());
     sed.setCrfs(defCrfs);
     sed.setCrfNum(defCrfs.size());
   }
   return seds;
 }
  private void createDiscrepancyNoteBean(
      String description,
      String detailedNotes,
      int itemDataId,
      StudyBean studyBean,
      UserAccountBean ub,
      DiscrepancyNoteBean parentDiscrepancyNote) {
    DiscrepancyNoteBean dnb = new DiscrepancyNoteBean();
    dnb.setEntityId(itemDataId); // this is needed for DN Map object
    dnb.setStudyId(studyBean.getId());
    dnb.setEntityType(DiscrepancyNoteBean.ITEM_DATA);
    dnb.setDescription(description);
    dnb.setDetailedNotes(detailedNotes);
    dnb.setDiscrepancyNoteTypeId(
        parentDiscrepancyNote.getDiscrepancyNoteTypeId()); // set to parent DN Type Id
    dnb.setResolutionStatusId(4); // set to closed
    dnb.setColumn("value"); // this is needed for DN Map object
    dnb.setAssignedUserId(ub.getId());
    dnb.setOwner(ub);
    dnb.setParentDnId(parentDiscrepancyNote.getId());
    dnb.setActivated(false);
    dnb = (DiscrepancyNoteBean) getDnDao().create(dnb); // create child DN
    getDnDao().createMapping(dnb); // create DN mapping

    DiscrepancyNoteBean itemParentNote =
        (DiscrepancyNoteBean) getDnDao().findByPK(dnb.getParentDnId());
    itemParentNote.setResolutionStatusId(ResolutionStatus.CLOSED.getId());
    itemParentNote.setAssignedUserId(ub.getId());
    getDnDao().update(itemParentNote); // update parent DN
    getDnDao().updateAssignedUser(itemParentNote); // update parent DN assigned user
  }
  private boolean mayProceedPreview(String studyOid) throws Exception {
    boolean accessPermission = false;
    StudyBean study = getParentStudy(studyOid);
    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(dataSource);

    StudyParameterValueBean pStatus =
        spvdao.findByHandleAndStudy(study.getId(), "participantPortal");
    participantPortalRegistrar = new ParticipantPortalRegistrar();
    String pManageStatus =
        participantPortalRegistrar.getRegistrationStatus(studyOid).toString(); // ACTIVE ,
    // PENDING ,
    // INACTIVE
    String participateStatus = pStatus.getValue().toString(); // enabled , disabled
    String studyStatus =
        study.getStatus().getName().toString(); // available , pending , frozen , locked
    logger.info(
        "pManageStatus: "
            + pManageStatus
            + "  participantStatus: "
            + participateStatus
            + "   studyStatus: "
            + studyStatus);
    if (participateStatus.equalsIgnoreCase("enabled")
        && (studyStatus.equalsIgnoreCase("available")
            || studyStatus.equalsIgnoreCase("pending")
            || studyStatus.equalsIgnoreCase("frozen")
            || studyStatus.equalsIgnoreCase("locked"))
        && (pManageStatus.equalsIgnoreCase("ACTIVE")
            || pManageStatus.equalsIgnoreCase("PENDING")
            || pManageStatus.equalsIgnoreCase("INACTIVE"))) {
      accessPermission = true;
    }
    return accessPermission;
  }
 public ArrayList findAllByStudyAndParent(StudyBean study, int parentId) {
   HashMap variables = new HashMap();
   variables.put(new Integer(1), new Integer(parentId));
   variables.put(new Integer(2), new Integer(study.getId()));
   variables.put(new Integer(3), new Integer(study.getId()));
   return this.executeFindAllQuery("findAllByStudyAndParent", variables);
 }
 private void submitSiteEventDefinitions(StudyBean site) {
   FormProcessor fp = new FormProcessor(request);
   ArrayList<StudyEventDefinitionBean> seds = new ArrayList<StudyEventDefinitionBean>();
   CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
   seds = (ArrayList<StudyEventDefinitionBean>) session.getAttribute("definitions");
   HashMap<String, Boolean> changes = (HashMap<String, Boolean>) session.getAttribute("changed");
   for (StudyEventDefinitionBean sed : seds) {
     EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
     ArrayList<EventDefinitionCRFBean> edcs = sed.getCrfs();
     for (EventDefinitionCRFBean edcBean : edcs) {
       int edcStatusId = edcBean.getStatus().getId();
       if (edcStatusId == 5 || edcStatusId == 7) {
       } else {
         boolean changed = changes.get(sed.getId() + "-" + edcBean.getId());
         if (changed) {
           edcBean.setParentId(edcBean.getId());
           edcBean.setStudyId(site.getId());
           edcBean.setUpdater(ub);
           edcBean.setUpdatedDate(new Date());
           logger.debug("create for the site");
           edcdao.create(edcBean);
         }
       }
     }
   }
   session.removeAttribute("definitions");
   session.removeAttribute("changed");
   session.removeAttribute("sdvOptions");
 }
 private StudyUserRoleBean getRole(UserAccountBean userAccount, StudyBean study) throws Exception {
   StudyUserRoleBean role = new StudyUserRoleBean();
   if (study == null || userAccount == null || study.getId() == 0) {
     throw new Exception();
   }
   if (userAccount.getId() > 0
       && study.getId() > 0
       && !study.getStatus().getName().equals("removed")) {
     role = userAccount.getRoleByStudy(study.getId());
     if (study.getParentStudyId() > 0) {
       StudyUserRoleBean roleInParent = userAccount.getRoleByStudy(study.getParentStudyId());
       role.setRole(Role.max(role.getRole(), roleInParent.getRole()));
     }
   } else {
     throw new Exception();
   }
   return role;
 }
  /** Finds all the studies */
  @Override
  public void processRequest() throws Exception {

    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    ArrayList studies = (ArrayList) sdao.findAll();
    // find all parent studies
    ArrayList parents = (ArrayList) sdao.findAllParents();
    ArrayList displayStudies = new ArrayList();

    for (int i = 0; i < parents.size(); i++) {
      StudyBean parent = (StudyBean) parents.get(i);
      ArrayList children = (ArrayList) sdao.findAllByParent(parent.getId());
      DisplayStudyBean displayStudy = new DisplayStudyBean();
      displayStudy.setParent(parent);
      displayStudy.setChildren(children);
      displayStudies.add(displayStudy);
    }

    FormProcessor fp = new FormProcessor(request);
    EntityBeanTable table = fp.getEntityBeanTable();
    ArrayList allStudyRows = DisplayStudyRow.generateRowsFromBeans(displayStudies);

    String[] columns = {
      resword.getString("name"),
      resword.getString("unique_identifier"),
      resword.getString("OID"),
      resword.getString("principal_investigator"),
      resword.getString("facility_name"),
      resword.getString("date_created"),
      resword.getString("status"),
      resword.getString("actions")
    };
    table.setColumns(new ArrayList(Arrays.asList(columns)));
    table.hideColumnLink(2);
    table.hideColumnLink(6);
    table.setQuery("ListStudy", new HashMap());
    table.addLink(resword.getString("create_a_new_study"), "CreateStudy");
    table.setRows(allStudyRows);
    table.computeDisplay();

    request.setAttribute("table", table);
    // request.setAttribute("studies", studies);
    session.setAttribute("fromListSite", "no");

    resetPanel();
    panel.setStudyInfoShown(false);
    panel.setOrderedData(true);
    setToPanel(resword.getString("in_the_application"), "");
    if (parents.size() > 0) {
      setToPanel(resword.getString("studies"), new Integer(parents.size()).toString());
    }
    if (studies.size() > 0) {
      setToPanel(
          resword.getString("sites"), new Integer(studies.size() - parents.size()).toString());
    }
    forwardPage(Page.STUDY_LIST);
  }
 private StudySubjectBean createStudySubject(
     SubjectBean subject, StudyBean studyBean, Date enrollmentDate, String secondaryId) {
   StudySubjectBean studySubject = new StudySubjectBean();
   studySubject.setSecondaryLabel(secondaryId);
   studySubject.setOwner(getUserAccount());
   studySubject.setEnrollmentDate(enrollmentDate);
   studySubject.setLabel(subject.getLabel());
   subject.setLabel(null);
   studySubject.setSubjectId(subject.getId());
   studySubject.setStudyId(studyBean.getId());
   studySubject.setStatus(Status.AVAILABLE);
   return studySubject;
 }
 public void collectOdmStudy() {
   StudyBean study = studyBase.getStudy();
   String studyOID = study.getOid();
   if (studyOID == null || studyOID.length() <= 0) {
     logger.info(
         "Constructed studyOID using study_id because oc_oid is missing from the table - study.");
     studyOID = "" + study.getId();
   }
   odmStudy.setOid(studyOID);
   collectGlobalVariables();
   collectBasicDefinitions();
   collectMetaDataVersion();
 }
 private void collectGlobalVariables() {
   StudyBean study = studyBase.getStudy();
   String sn = study.getName();
   String sd = study.getSummary().trim();
   String pn = study.getIdentifier();
   if (parentStudy.getId() > 0) {
     sn = parentStudy.getName() + " - " + study.getName();
     sd = parentStudy.getSummary().trim() + " - " + study.getSummary().trim();
     pn = parentStudy.getIdentifier() + " - " + study.getIdentifier();
   }
   GlobalVariablesBean gv = this.odmStudy.getGlobalVariables();
   gv.setStudyName(sn);
   gv.setStudyDescription(sd);
   gv.setProtocolName(pn);
 }
 public StudySubjectBean createStudySubjectBean(
     StudyBean sBean, SubjectBean subjectBean, UserAccountBean uBean) {
   StudySubjectBean ssBean = new StudySubjectBean();
   subjectBean.setGender('\0'); // setting null character
   ssBean.setStudyId(sBean.getId());
   ssBean.setSubjectId(subjectBean.getId());
   ssBean.setStatus(Status.AVAILABLE);
   ssBean.setOwner(uBean);
   ssBean.setEnrollmentDate(new Date());
   int nextLabel = getStudySubjectDao().findTheGreatestLabel() + 1;
   ssBean.setLabel(Integer.toString(nextLabel));
   StudySubjectDAO ssdao = new StudySubjectDAO(dataSource);
   ssBean = (StudySubjectBean) ssdao.create(ssBean, false);
   return ssBean;
 }
  public ArrayList findAllParentsByStudy(StudyBean study) {
    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(study.getId()));
    variables.put(new Integer(2), new Integer(study.getId()));
    ArrayList notes = executeFindAllQuery("findAllParentsByStudy", variables);

    if (fetchMapping) {
      for (int i = 0; i < notes.size(); i++) {
        DiscrepancyNoteBean dnb = (DiscrepancyNoteBean) notes.get(i);
        dnb = findSingleMapping(dnb);
        notes.set(i, dnb);
      }
    }

    return notes;
  }
  public static DiscrepancyNoteBean createDiscrepancyNote(
      ItemBean itemBean,
      String message,
      EventCRFBean eventCrfBean,
      DisplayItemBean displayItemBean,
      Integer parentId,
      UserAccountBean uab,
      DataSource ds,
      StudyBean study) {
    // DisplayItemBean displayItemBean) {
    DiscrepancyNoteBean note = new DiscrepancyNoteBean();
    StudySubjectDAO ssdao = new StudySubjectDAO(ds);
    note.setDescription(message);
    note.setDetailedNotes("Failed Validation Check");
    note.setOwner(uab);
    note.setCreatedDate(new Date());
    note.setResolutionStatusId(ResolutionStatus.OPEN.getId());
    note.setDiscrepancyNoteTypeId(DiscrepancyNoteType.FAILEDVAL.getId());
    if (parentId != null) {
      note.setParentDnId(parentId);
    }

    note.setField(itemBean.getName());
    note.setStudyId(study.getId());
    note.setEntityName(itemBean.getName());
    note.setEntityType("ItemData");
    note.setEntityValue(displayItemBean.getData().getValue());

    note.setEventName(eventCrfBean.getName());
    note.setEventStart(eventCrfBean.getCreatedDate());
    note.setCrfName(displayItemBean.getEventDefinitionCRF().getCrfName());

    StudySubjectBean ss = (StudySubjectBean) ssdao.findByPK(eventCrfBean.getStudySubjectId());
    note.setSubjectName(ss.getName());

    note.setEntityId(displayItemBean.getData().getId());
    note.setColumn("value");

    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(ds);
    note = (DiscrepancyNoteBean) dndao.create(note);
    // so that the below method works, need to set the entity above
    // System.out.println("trying to create mapping with " + note.getId() + " " + note.getEntityId()
    // + " " + note.getColumn() + " " + note.getEntityType());
    dndao.createMapping(note);
    // System.out.println("just created mapping");
    return note;
  }
  private void updateInterviewerForSites(
      StudyBean studyBean,
      List<StudyBean> sites,
      StudyParameterValueDAO studyParameterValueDAO,
      String parameterType) {

    StudyParameterValueBean studyParameterValueBean = new StudyParameterValueBean();

    if ("interviewerNameEditable".equalsIgnoreCase(parameterType)) {
      studyParameterValueBean.setParameter("interviewerNameEditable");
      studyParameterValueBean.setValue(
          studyBean.getStudyParameterConfig().getInterviewerNameEditable());
    } else {
      studyParameterValueBean.setParameter("interviewerDateEditable");
      studyParameterValueBean.setValue(
          studyBean.getStudyParameterConfig().getInterviewDateEditable());
    }
    for (StudyBean siteBean : sites) {
      studyParameterValueBean.setStudyId(siteBean.getId());
      updateParameter(studyParameterValueDAO, studyParameterValueBean);
    }
  }
  public ArrayList findAllItemDataByStudy(StudyBean study) {
    this.setTypesExpected();
    ArrayList alist = new ArrayList();
    this.setTypeExpected(11, TypeNames.STRING); // ss.label
    this.setTypeExpected(12, TypeNames.DATE); // date_start
    this.setTypeExpected(13, TypeNames.STRING); // sed_name
    this.setTypeExpected(14, TypeNames.STRING); // crf_name
    this.setTypeExpected(15, TypeNames.STRING); // item_name
    this.setTypeExpected(16, TypeNames.STRING); // value
    this.setTypeExpected(17, TypeNames.INT); // item_data_id
    this.setTypeExpected(18, TypeNames.INT); // item_id

    HashMap variables = new HashMap();
    variables.put(new Integer(1), new Integer(study.getId()));
    variables.put(new Integer(2), new Integer(study.getId()));
    alist = this.select(digester.getQuery("findAllItemDataByStudy"), variables);

    ArrayList al = new ArrayList();
    Iterator it = alist.iterator();
    while (it.hasNext()) {
      HashMap hm = (HashMap) it.next();
      DiscrepancyNoteBean eb = (DiscrepancyNoteBean) this.getEntityFromHashMap(hm);
      eb.setEventName((String) hm.get("sed_name"));
      eb.setEventStart((Date) hm.get("date_start"));
      eb.setCrfName((String) hm.get("crf_name"));
      eb.setSubjectName((String) hm.get("label"));
      eb.setEntityName((String) hm.get("item_name"));
      eb.setEntityValue((String) hm.get("value"));
      // YW << change EntityId from item_id to item_data_id.
      eb.setEntityId(((Integer) hm.get("item_data_id")).intValue());
      eb.setItemId(((Integer) hm.get("item_id")).intValue());
      // YW >>
      al.add(eb);
    }
    return al;
  }
  /** Inserts the new study into database */
  private void submitStudy() {
    FormProcessor fp = new FormProcessor(request);
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyBean study = (StudyBean) session.getAttribute("newStudy");

    ArrayList parameters = study.getStudyParameters();
    logger.info("study bean to be created:\n");
    logger.info(
        study.getName()
            + "\n"
            + study.getIdentifier()
            + "\n"
            + study.getParentStudyId()
            + "\n"
            + study.getSummary()
            + "\n"
            + study.getPrincipalInvestigator()
            + "\n"
            + study.getDatePlannedStart()
            + "\n"
            + study.getDatePlannedEnd()
            + "\n"
            + study.getFacilityName()
            + "\n"
            + study.getFacilityCity()
            + "\n"
            + study.getFacilityState()
            + "\n"
            + study.getFacilityZip()
            + "\n"
            + study.getFacilityCountry()
            + "\n"
            + study.getFacilityRecruitmentStatus()
            + "\n"
            + study.getFacilityContactName()
            + "\n"
            + study.getFacilityContactEmail()
            + "\n"
            + study.getFacilityContactPhone()
            + "\n"
            + study.getFacilityContactDegree());

    study.setOwner(ub);
    study.setCreatedDate(new Date());
    StudyBean parent = (StudyBean) sdao.findByPK(study.getParentStudyId());
    study.setType(parent.getType());
    // YW 10-10-2007, enable setting site status
    study.setStatus(study.getStatus());
    // YW >>

    study.setGenetic(parent.isGenetic());
    study = (StudyBean) sdao.create(study);

    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());
    for (int i = 0; i < parameters.size(); i++) {
      StudyParamsConfig config = (StudyParamsConfig) parameters.get(i);
      StudyParameterValueBean spv = config.getValue();
      spv.setStudyId(study.getId());
      spv = (StudyParameterValueBean) spvdao.create(config.getValue());
    }

    // YW << here only "collectDob" and "genderRequired" have been corrected
    // for sites.
    StudyParameterValueBean spv = new StudyParameterValueBean();
    StudyParameterValueBean parentSPV = spvdao.findByHandleAndStudy(parent.getId(), "collectDob");
    spv.setStudyId(study.getId());
    spv.setParameter("collectDob");
    spv.setValue(parentSPV.getValue());
    spvdao.create(spv);

    parentSPV = spvdao.findByHandleAndStudy(parent.getId(), "genderRequired");
    spv.setParameter("genderRequired");
    spv.setValue(parentSPV.getValue());
    spvdao.create(spv);
    // YW >>

    // switch user to the newly created site
    session.setAttribute("study", session.getAttribute("newStudy"));
    currentStudy = (StudyBean) session.getAttribute("study");

    session.removeAttribute("newStudy");
    addPageMessage(respage.getString("the_new_site_created_succesfully_current"));
    forwardPage(Page.SITE_LIST_SERVLET);
  }
  public void processRequest() throws Exception {

    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    FormProcessor fp = new FormProcessor(request);
    int studyId = fp.getInt("id");

    StudyBean study = (StudyBean) sdao.findByPK(studyId);
    // find all sites
    ArrayList sites = (ArrayList) sdao.findAllByParent(studyId);

    // find all user and roles in the study, include ones in sites
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    ArrayList userRoles = udao.findAllByStudyId(studyId);

    // find all subjects in the study, include ones in sites
    StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
    ArrayList subjects = ssdao.findAllByStudy(study);

    // find all events in the study, include ones in sites
    StudyEventDefinitionDAO sefdao = new StudyEventDefinitionDAO(sm.getDataSource());
    ArrayList definitions = sefdao.findAllByStudy(study);

    String action = request.getParameter("action");
    if (studyId == 0) {
      addPageMessage("Please choose a study to restore.");
      forwardPage(Page.STUDY_LIST_SERVLET);
    } else {
      if ("confirm".equalsIgnoreCase(action)) {
        request.setAttribute("studyToRestore", study);

        request.setAttribute("sitesToRestore", sites);

        request.setAttribute("userRolesToRestore", userRoles);

        request.setAttribute("subjectsToRestore", subjects);

        request.setAttribute("definitionsToRRestore", definitions);
        forwardPage(Page.RESTORE_STUDY);
      } else {
        logger.info("submit to restore the study");
        // change all statuses to unavailable
        StudyDAO studao = new StudyDAO(sm.getDataSource());
        study.setStatus(Status.AVAILABLE);
        study.setUpdater(ub);
        study.setUpdatedDate(new Date());
        studao.update(study);

        // remove all sites
        for (int i = 0; i < sites.size(); i++) {
          StudyBean site = (StudyBean) sites.get(i);
          site.setStatus(Status.AVAILABLE);
          site.setUpdater(ub);
          site.setUpdatedDate(new Date());
          sdao.update(site);
        }

        // remove all users and roles
        for (int i = 0; i < userRoles.size(); i++) {
          StudyUserRoleBean role = (StudyUserRoleBean) userRoles.get(i);
          role.setStatus(Status.AVAILABLE);
          role.setUpdater(ub);
          role.setUpdatedDate(new Date());
          udao.updateStudyUserRole(role, role.getUserName());
        }

        // remove all subjects
        for (int i = 0; i < subjects.size(); i++) {
          StudySubjectBean subject = (StudySubjectBean) subjects.get(i);
          subject.setStatus(Status.AVAILABLE);
          subject.setUpdater(ub);
          subject.setUpdatedDate(new Date());
          ssdao.update(subject);
        }

        // remove all study_group
        StudyGroupDAO sgdao = new StudyGroupDAO(sm.getDataSource());
        SubjectGroupMapDAO sgmdao = new SubjectGroupMapDAO(sm.getDataSource());
        ArrayList groups = sgdao.findAllByStudy(study);
        for (int i = 0; i < groups.size(); i++) {
          StudyGroupBean group = (StudyGroupBean) groups.get(i);
          group.setStatus(Status.AVAILABLE);
          group.setUpdater(ub);
          group.setUpdatedDate(new Date());
          sgdao.update(group);
          // all subject_group_map
          ArrayList subjectGroupMaps = sgmdao.findAllByStudyGroupId(group.getId());
          for (int j = 0; j < subjectGroupMaps.size(); j++) {
            SubjectGroupMapBean sgMap = (SubjectGroupMapBean) subjectGroupMaps.get(j);
            sgMap.setStatus(Status.AVAILABLE);
            sgMap.setUpdater(ub);
            sgMap.setUpdatedDate(new Date());
            sgmdao.update(sgMap);
          }
        }

        // remove all event definitions and event
        EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
        StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
        for (int i = 0; i < definitions.size(); i++) {
          StudyEventDefinitionBean definition = (StudyEventDefinitionBean) definitions.get(i);
          definition.setStatus(Status.AVAILABLE);
          definition.setUpdater(ub);
          definition.setUpdatedDate(new Date());
          sefdao.update(definition);
          ArrayList edcs = (ArrayList) edcdao.findAllByDefinition(definition.getId());
          for (int j = 0; j < edcs.size(); j++) {
            EventDefinitionCRFBean edc = (EventDefinitionCRFBean) edcs.get(j);
            edc.setStatus(Status.AVAILABLE);
            edc.setUpdater(ub);
            edc.setUpdatedDate(new Date());
            edcdao.update(edc);
          }

          ArrayList events = (ArrayList) sedao.findAllByDefinition(definition.getId());
          EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());

          for (int j = 0; j < events.size(); j++) {
            StudyEventBean event = (StudyEventBean) events.get(j);
            event.setStatus(Status.AVAILABLE);
            event.setUpdater(ub);
            event.setUpdatedDate(new Date());
            sedao.update(event);

            ArrayList eventCRFs = ecdao.findAllByStudyEvent(event);

            ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
            for (int k = 0; k < eventCRFs.size(); k++) {
              EventCRFBean eventCRF = (EventCRFBean) eventCRFs.get(k);
              eventCRF.setStatus(Status.AVAILABLE);
              eventCRF.setUpdater(ub);
              eventCRF.setUpdatedDate(new Date());
              ecdao.update(eventCRF);

              ArrayList itemDatas = iddao.findAllByEventCRFId(eventCRF.getId());
              for (int a = 0; a < itemDatas.size(); a++) {
                ItemDataBean item = (ItemDataBean) itemDatas.get(a);
                item.setStatus(Status.AVAILABLE);
                item.setUpdater(ub);
                item.setUpdatedDate(new Date());
                iddao.update(item);
              }
            }
          }
        } // for definitions

        DatasetDAO datadao = new DatasetDAO(sm.getDataSource());
        ArrayList dataset = datadao.findAllByStudyId(study.getId());
        for (int i = 0; i < dataset.size(); i++) {
          DatasetBean data = (DatasetBean) dataset.get(i);
          data.setStatus(Status.AVAILABLE);
          data.setUpdater(ub);
          data.setUpdatedDate(new Date());
          datadao.update(data);
        }

        addPageMessage("This study has been restored successfully.");
        forwardPage(Page.STUDY_LIST_SERVLET);
      }
    }
  }
  private void submitStudy() {
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());

    StudyBean study1 = (StudyBean) session.getAttribute("newStudy");
    logger.info("study bean to be updated:" + study1.getName());
    study1.setUpdatedDate(new Date());
    study1.setUpdater((UserAccountBean) session.getAttribute("userBean"));
    System.out.println("study's parentId=" + study1.getParentStudyId());
    sdao.update(study1);

    StudyParameterValueBean spv = new StudyParameterValueBean();

    spv.setStudyId(study1.getId());
    spv.setParameter("collectDob");
    spv.setValue(new Integer(study1.getStudyParameterConfig().getCollectDob()).toString());
    updateParameter(spvdao, spv);

    spv.setParameter("discrepancyManagement");
    spv.setValue(study1.getStudyParameterConfig().getDiscrepancyManagement());
    updateParameter(spvdao, spv);

    spv.setParameter("genderRequired");
    spv.setValue(study1.getStudyParameterConfig().getGenderRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("subjectPersonIdRequired");
    spv.setValue(study1.getStudyParameterConfig().getSubjectPersonIdRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameRequired");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameDefault");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameDefault());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameEditable");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameEditable());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewDateRequired");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewDateDefault");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateDefault());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewDateEditable");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateEditable());
    updateParameter(spvdao, spv);

    spv.setParameter("subjectIdGeneration");
    spv.setValue(study1.getStudyParameterConfig().getSubjectIdGeneration());
    updateParameter(spvdao, spv);

    spv.setParameter("subjectIdPrefixSuffix");
    spv.setValue(study1.getStudyParameterConfig().getSubjectIdPrefixSuffix());
    updateParameter(spvdao, spv);

    spv.setParameter("personIdShownOnCRF");
    spv.setValue(study1.getStudyParameterConfig().getPersonIdShownOnCRF());
    updateParameter(spvdao, spv);

    StudyBean curStudy = (StudyBean) session.getAttribute("study");
    if (curStudy != null && study1.getId() == curStudy.getId()) {
      super.currentStudy = study1;
      session.setAttribute("study", study1);
    }
    // update manage_pedigrees for all sites
    ArrayList children = (ArrayList) sdao.findAllByParent(study1.getId());
    for (int i = 0; i < children.size(); i++) {
      StudyBean child = (StudyBean) children.get(i);
      child.setType(study1.getType()); // same as parent's type
      child.setUpdatedDate(new Date());
      child.setUpdater(ub);
      sdao.update(child);
      // YW << update "collectDob" and "genderRequired" for sites
      StudyParameterValueBean childspv = new StudyParameterValueBean();
      childspv.setStudyId(child.getId());
      childspv.setParameter("collectDob");
      childspv.setValue(new Integer(study1.getStudyParameterConfig().getCollectDob()).toString());
      updateParameter(spvdao, childspv);
      childspv.setParameter("genderRequired");
      childspv.setValue(study1.getStudyParameterConfig().getGenderRequired());
      updateParameter(spvdao, childspv);
      // YW >>
    }

    session.removeAttribute("newStudy");
    session.removeAttribute("interventions");
  }
  private void setUpServlet(Trigger trigger) throws Exception {
    FormProcessor fp2 = new FormProcessor(request);

    request.setAttribute(CreateJobImportServlet.JOB_NAME, trigger.getName());
    request.setAttribute(CreateJobImportServlet.JOB_DESC, trigger.getDescription());

    dataMap = trigger.getJobDataMap();
    String contactEmail = dataMap.getString(ImportSpringJob.EMAIL);
    System.out.println("found email: " + contactEmail);
    int userId = dataMap.getInt(ImportSpringJob.USER_ID);
    int hours = dataMap.getInt(CreateJobImportServlet.HOURS);
    int minutes = dataMap.getInt(CreateJobImportServlet.MINUTES);
    String directory = dataMap.getString(ImportSpringJob.DIRECTORY);
    String studyName = dataMap.getString(ImportSpringJob.STUDY_NAME);

    request.setAttribute(ImportSpringJob.EMAIL, contactEmail);
    request.setAttribute(ImportSpringJob.STUDY_NAME, studyName);
    request.setAttribute("filePath", directory);
    request.setAttribute("firstFilePath", IMPORT_DIR);
    request.setAttribute("hours", new Integer(hours).toString());
    request.setAttribute("minutes", new Integer(minutes).toString());

    Date jobDate = trigger.getNextFireTime();

    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    StudyDAO sdao = new StudyDAO(sm.getDataSource());

    // ArrayList studies = udao.findStudyByUser(ub.getName(), (ArrayList)
    // sdao.findAll());
    // request.setAttribute("studies", studies);
    ArrayList<StudyBean> all = (ArrayList<StudyBean>) sdao.findAll();
    ArrayList<StudyBean> finalList = new ArrayList<StudyBean>();
    for (StudyBean sb : all) {
      if (!(sb.getParentStudyId() > 0)) {
        finalList.add(sb);
        // System.out.println("found study name: " + sb.getName());
        finalList.addAll(sdao.findAllByParent(sb.getId()));
      }
    }
    // System.out.println("found list of studies: " + finalList.toString());
    addEntityList(
        "studies",
        finalList,
        respage.getString("a_user_cannot_be_created_no_study_as_active"),
        Page.ADMIN_SYSTEM);
    // tbh >>
    // HashMap presetValues = new HashMap();
    // Calendar calendar = new GregorianCalendar();
    // calendar.setTime(jobDate);
    // presetValues.put(CreateJobImportServlet.DATE_START_JOB + "Hour",
    // calendar.get(Calendar.HOUR_OF_DAY));
    // presetValues.put(CreateJobImportServlet.DATE_START_JOB + "Minute",
    // calendar.get(Calendar.MINUTE));
    // // TODO this will have to match l10n formatting
    // presetValues.put(CreateJobImportServlet.DATE_START_JOB + "Date",
    // (calendar.get(Calendar.MONTH) + 1) + "/" +
    // calendar.get(Calendar.DATE) + "/"
    // + calendar.get(Calendar.YEAR));
    // fp2.setPresetValues(presetValues);
    // setPresetValues(fp2.getPresetValues());

  }
  public SimpleTrigger generateTrigger(
      FormProcessor fp, UserAccountBean userAccount, StudyBean study, String locale) {
    Date startDateTime = fp.getDateTime(DATE_START_JOB);
    // check the above?
    int datasetId = fp.getInt(DATASET_ID);
    String period = fp.getString(PERIOD);
    String email = fp.getString(EMAIL);
    String jobName = fp.getString(JOB_NAME);
    String jobDesc = fp.getString(JOB_DESC);
    String spss = fp.getString(SPSS);
    String tab = fp.getString(TAB);
    String cdisc = fp.getString(CDISC);
    String cdisc12 = fp.getString(ExampleSpringJob.CDISC12);
    String cdisc13 = fp.getString(ExampleSpringJob.CDISC13);
    String cdisc13oc = fp.getString(ExampleSpringJob.CDISC13OC);
    BigInteger interval = new BigInteger("0");
    if ("monthly".equalsIgnoreCase(period)) {
      interval = new BigInteger("2419200000"); // how many
      // milliseconds in
      // a month? should
      // be 24192000000
    } else if ("weekly".equalsIgnoreCase(period)) {
      interval = new BigInteger("604800000"); // how many
      // milliseconds in
      // a week? should
      // be 6048000000
    } else { // daily
      interval = new BigInteger("86400000"); // how many
      // milliseconds in a
      // day?
    }
    // set up and commit job here

    SimpleTrigger trigger = new SimpleTrigger(jobName, "DEFAULT", 64000, interval.longValue());

    // set the job detail name,
    // based on our choice of format above
    // what if there is more than one detail?
    // what is the number of times it should repeat?
    // arbitrary large number, 64K should be enough :)

    trigger.setDescription(jobDesc);
    // set just the start date
    trigger.setStartTime(startDateTime);
    trigger.setName(jobName); // + datasetId);
    trigger.setGroup("DEFAULT"); // + datasetId);
    trigger.setMisfireInstruction(
        SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT);
    // set job data map
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put(DATASET_ID, datasetId);
    jobDataMap.put(PERIOD, period);
    jobDataMap.put(EMAIL, email);
    jobDataMap.put(TAB, tab);
    jobDataMap.put(CDISC, cdisc);
    jobDataMap.put(ExampleSpringJob.CDISC12, cdisc12);
    jobDataMap.put(ExampleSpringJob.LOCALE, locale);
    // System.out.println("found 1.2: " +
    // jobDataMap.get(ExampleSpringJob.CDISC12));
    jobDataMap.put(ExampleSpringJob.CDISC13, cdisc13);
    // System.out.println("found 1.3: " +
    // jobDataMap.get(ExampleSpringJob.CDISC13));
    jobDataMap.put(ExampleSpringJob.CDISC13OC, cdisc13oc);
    // System.out.println("found 1.3oc: " +
    // jobDataMap.get(ExampleSpringJob.CDISC13OC));
    jobDataMap.put(SPSS, spss);
    jobDataMap.put(USER_ID, userAccount.getId());
    // StudyDAO studyDAO = new StudyDAO();
    jobDataMap.put(STUDY_ID, study.getId());
    jobDataMap.put(STUDY_NAME, study.getName());
    jobDataMap.put(STUDY_OID, study.getOid());

    trigger.setJobDataMap(jobDataMap);
    // trigger.setRepeatInterval(interval.longValue());
    // System.out.println("default for volatile: " + trigger.isVolatile());
    trigger.setVolatility(false);
    return trigger;
  }
  public boolean validate(SubjectTransferBean subjectTransferBean)
      throws OpenClinicaSystemException {

    StudyDAO stdao = new StudyDAO(this.getDataSource());
    StudyBean study = stdao.findByUniqueIdentifier(subjectTransferBean.getStudyOid());
    if (study == null) {
      throw new OpenClinicaSystemException("Study you specified does not exist");
    }

    UserAccountBean ua = subjectTransferBean.getOwner();
    StudyUserRoleBean role = ua.getRoleByStudy(study);
    if (role.getId() == 0 || role.getRole().equals(Role.MONITOR)) {
      throw new OpenClinicaSystemException(
          "You do not have sufficient priviliges to run this service");
    }

    if (subjectTransferBean.getSiteIdentifier() != null) {
      study =
          stdao.findSiteByUniqueIdentifier(
              subjectTransferBean.getStudyOid(), subjectTransferBean.getSiteIdentifier());
    }
    subjectTransferBean.setStudy(study);
    if (study == null) {
      throw new OpenClinicaSystemException("Site you specified does not exist");
    }
    int handleStudyId = study.getParentStudyId() > 0 ? study.getParentStudyId() : study.getId();
    org.akaza.openclinica.dao.service.StudyParameterValueDAO spvdao =
        new StudyParameterValueDAO(this.getDataSource());
    StudyParameterValueBean studyParameter =
        spvdao.findByHandleAndStudy(handleStudyId, "subjectPersonIdRequired");
    String personId = subjectTransferBean.getPersonId();
    if ("required".equals(studyParameter.getValue())
        && (personId == null || personId.length() < 1)) {
      throw new OpenClinicaSystemException(
          "personId is required for the study: " + study.getName());
      // return false;
    }

    if (personId != null && personId.length() > 255) {
      throw new OpenClinicaSystemException("personId should not be longer than 255.");
      // return false;
    }

    String idSetting = "";
    StudyParameterValueBean subjectIdGenerationParameter =
        spvdao.findByHandleAndStudy(handleStudyId, "subjectIdGeneration");
    idSetting = subjectIdGenerationParameter.getValue();
    if (idSetting.equals("auto editable") || idSetting.equals("auto non-editable")) {
      int nextLabel = getStudySubjectDao().findTheGreatestLabel() + 1;
      subjectTransferBean.setStudySubjectId(new Integer(nextLabel).toString());
    }
    String studySubjectId = subjectTransferBean.getStudySubjectId();
    if (studySubjectId == null || studySubjectId.length() < 1) {
      logger.info("studySubjectId is required.");
      throw new OpenClinicaSystemException("studySubjectId is required.");
      // return false;
    } else if (studySubjectId.length() > 30) {
      throw new OpenClinicaSystemException("studySubjectId should not be longer than 30.");
      // return false;
    }

    String secondaryId = subjectTransferBean.getSecondaryId();
    if (secondaryId != null && secondaryId.length() > 30) {
      throw new OpenClinicaSystemException("secondaryId should not be longer than 30.");
      // return false;
    }
    String gender = subjectTransferBean.getGender() + "";
    studyParameter = spvdao.findByHandleAndStudy(handleStudyId, "genderRequired");
    if ("true".equals(studyParameter.getValue()) && (gender == null || gender.length() < 1)) {
      throw new OpenClinicaSystemException("gender is required for the study:" + study.getName());
      // return false;
    }

    Date dateOfBirth = subjectTransferBean.getDateOfBirth();
    String yearOfBirth = subjectTransferBean.getYearOfBirth();
    studyParameter = spvdao.findByHandleAndStudy(handleStudyId, "collectDob");
    if ("1".equals(studyParameter.getValue()) && (dateOfBirth == null)) {
      throw new OpenClinicaSystemException("date Of Birth is required:" + study.getName());
      // return false;
    } else if ("2".equals(studyParameter.getValue()) && (yearOfBirth == null)) {
      throw new OpenClinicaSystemException("Year Of Birth is required:" + study.getName());
    } else if ("2".equals(studyParameter.getValue()) && (yearOfBirth != null)) {
      try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        subjectTransferBean.setDateOfBirth(sdf.parse(subjectTransferBean.getYearOfBirth()));
      } catch (ParseException e) {
        throw new OpenClinicaSystemException("Year Of Birth not Valid:" + study.getName());
      }
    }

    Date enrollmentDate = subjectTransferBean.getEnrollmentDate();
    if (enrollmentDate == null) {
      throw new OpenClinicaSystemException("enrollmentDate is required.");
      // return false;
    } else {
      if ((new Date()).compareTo(enrollmentDate) < 0) {
        throw new OpenClinicaSystemException("enrollmentDate should be in the past.");
        // return false;
      }
    }

    return true;
  }
  @Override
  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    // need to generate a Locale so that user beans and other things will
    // generate normally
    Locale locale = new Locale("en-US");
    ResourceBundleProvider.updateLocale(locale);
    ResourceBundle pageMessages = ResourceBundleProvider.getPageMessagesBundle();
    // logger.debug("--");
    // logger.debug("-- executing a job " + message + " at " + new
    // java.util.Date().toString());
    JobDataMap dataMap = context.getMergedJobDataMap();
    SimpleTrigger trigger = (SimpleTrigger) context.getTrigger();
    try {
      ApplicationContext appContext =
          (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
      String studySubjectNumber =
          ((CoreResources) appContext.getBean("coreResources")).getField("extract.number");
      coreResources = (CoreResources) appContext.getBean("coreResources");
      ruleSetRuleDao = (RuleSetRuleDao) appContext.getBean("ruleSetRuleDao");
      dataSource = (DataSource) appContext.getBean("dataSource");
      mailSender = (OpenClinicaMailSender) appContext.getBean("openClinicaMailSender");
      AuditEventDAO auditEventDAO = new AuditEventDAO(dataSource);
      // Scheduler scheduler = context.getScheduler();
      // JobDetail detail = context.getJobDetail();
      // jobDetailBean = (JobDetailBean) detail;
      /*
       * data map here should coincide with the job data map found in
       * CreateJobExportServlet, with the following code: jobDataMap = new
       * JobDataMap(); jobDataMap.put(DATASET_ID, datasetId);
       * jobDataMap.put(PERIOD, period); jobDataMap.put(EMAIL, email);
       * jobDataMap.put(TAB, tab); jobDataMap.put(CDISC, cdisc);
       * jobDataMap.put(SPSS, spss);
       */
      String alertEmail = dataMap.getString(EMAIL);
      String localeStr = dataMap.getString(LOCALE);
      if (localeStr != null) {
        locale = new Locale(localeStr);
        ResourceBundleProvider.updateLocale(locale);
        pageMessages = ResourceBundleProvider.getPageMessagesBundle();
      }
      int dsId = dataMap.getInt(DATASET_ID);
      String tab = dataMap.getString(TAB);
      String cdisc = dataMap.getString(CDISC);
      String cdisc12 = dataMap.getString(CDISC12);
      if (cdisc12 == null) {
        cdisc12 = "0";
      }
      String cdisc13 = dataMap.getString(CDISC13);
      if (cdisc13 == null) {
        cdisc13 = "0";
      }
      String cdisc13oc = dataMap.getString(CDISC13OC);
      if (cdisc13oc == null) {
        cdisc13oc = "0";
      }
      String spss = dataMap.getString(SPSS);
      int userId = dataMap.getInt(USER_ID);
      int studyId = dataMap.getInt(STUDY_ID);

      // String datasetId = dataMap.getString(DATASET_ID);
      // int dsId = new Integer(datasetId).intValue();
      // String userAcctId = dataMap.getString(USER_ID);
      // int userId = new Integer(userAcctId).intValue();
      // why the flip-flop? if one property is set to 'true' we can
      // see jobs in another screen but all properties have to be
      // strings

      logger.debug("-- found the job: " + dsId + " dataset id");

      // for (Iterator it = dataMap.entrySet().iterator(); it.hasNext();)
      // {
      // java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
      // Object key = entry.getKey();
      // Object value = entry.getValue();
      // // logger.debug("-- found datamap property: " + key.toString() +
      // // " : " + value.toString());
      // }
      HashMap fileName = new HashMap<String, Integer>();
      if (dsId > 0) {
        // trying to not throw an error if there's no dataset id
        DatasetDAO dsdao = new DatasetDAO(dataSource);
        DatasetBean datasetBean = (DatasetBean) dsdao.findByPK(dsId);
        StudyDAO studyDao = new StudyDAO(dataSource);
        UserAccountDAO userAccountDAO = new UserAccountDAO(dataSource);
        // hmm, three lines in the if block DRY?
        String generalFileDir = "";
        String generalFileDirCopy = "";
        String exportFilePath = SQLInitServlet.getField("exportFilePath");
        String pattern =
            "yyyy"
                + File.separator
                + "MM"
                + File.separator
                + "dd"
                + File.separator
                + "HHmmssSSS"
                + File.separator;
        SimpleDateFormat sdfDir = new SimpleDateFormat(pattern);
        generalFileDir =
            DATASET_DIR
                + datasetBean.getId()
                + File.separator
                + sdfDir.format(new java.util.Date());
        if (!"".equals(exportFilePath)) {
          generalFileDirCopy =
              SQLInitServlet.getField("filePath") + exportFilePath + File.separator;
        }
        // logger.debug("-- created the following dir: " +
        // generalFileDir);
        long sysTimeBegin = System.currentTimeMillis();
        // set up the user bean here, tbh
        // logger.debug("-- gen tab file 00");

        userBean = (UserAccountBean) userAccountDAO.findByPK(userId);
        // needs to also be captured by the servlet, tbh
        // logger.debug("-- gen tab file 00");
        generateFileService =
            new GenerateExtractFileService(dataSource, userBean, coreResources, ruleSetRuleDao);

        // logger.debug("-- gen tab file 00");

        // tbh #5796 - covers a bug when the user changes studies, 10/2010
        StudyBean activeStudy = (StudyBean) studyDao.findByPK(studyId);
        StudyBean parentStudy = new StudyBean();
        logger.debug(
            "active study: " + studyId + " parent study: " + activeStudy.getParentStudyId());
        if (activeStudy.getParentStudyId() > 0) {
          // StudyDAO sdao = new StudyDAO(sm.getDataSource());
          parentStudy = (StudyBean) studyDao.findByPK(activeStudy.getParentStudyId());
        } else {
          parentStudy = activeStudy;
          // covers a bug in tab file creation, tbh 01/2009
        }

        logger.debug("-- found extract bean ");

        ExtractBean eb =
            generateFileService.generateExtractBean(datasetBean, activeStudy, parentStudy);
        MessageFormat mf = new MessageFormat("");
        StringBuffer message = new StringBuffer();
        StringBuffer auditMessage = new StringBuffer();
        // use resource bundle page messages to generate the email, tbh
        // 02/2009
        // message.append(pageMessages.getString("html_email_header_1")
        // + " " + alertEmail +
        // pageMessages.getString("html_email_header_2") + "<br/>");
        message.append(
            "<p>"
                + pageMessages.getString("email_header_1")
                + " "
                + EmailEngine.getAdminEmail()
                + " "
                + pageMessages.getString("email_header_2")
                + " Job Execution "
                + pageMessages.getString("email_header_3")
                + "</p>");
        message.append("<P>Dataset: " + datasetBean.getName() + "</P>");
        message.append("<P>Study: " + activeStudy.getName() + "</P>");
        message.append(
            "<p>"
                + pageMessages.getString("html_email_body_1")
                + datasetBean.getName()
                + pageMessages.getString("html_email_body_2")
                + SQLInitServlet.getField("sysURL")
                + pageMessages.getString("html_email_body_3")
                + "</p>");
        // logger.debug("-- gen tab file 00");
        if ("1".equals(tab)) {

          logger.debug("-- gen tab file 01");
          fileName =
              generateFileService.createTabFile(
                  eb,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  generalFileDirCopy);
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");
          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_tab_delimited"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your tab-delimited file <a href='AccessFile?fileId="
          // + getFileIdInt(fileName) + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_tab_delimited")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        if ("1".equals(cdisc)) {
          String odmVersion = "oc1.2";
          fileName =
              generateFileService.createODMFile(
                  odmVersion,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy,
                  generalFileDirCopy,
                  eb,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  studySubjectNumber,
                  true,
                  true,
                  true,
                  null);
          logger.debug("-- gen odm file");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_odm_12"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your ODM 1.2 w/OpenClinica Extension XML file <a
          // href='AccessFile?fileId="
          // + getFileIdInt(fileName)
          // + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_odm_12")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        if ("1".equals(cdisc12)) {
          String odmVersion = "1.2";
          fileName =
              generateFileService.createODMFile(
                  odmVersion,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy,
                  generalFileDirCopy,
                  eb,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  studySubjectNumber,
                  true,
                  true,
                  true,
                  null);
          logger.debug("-- gen odm file 1.2 default");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_odm_12_xml"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));
          // // auditMessage.append(
          // "You can access your ODM 1.2 XML file <a href='AccessFile?fileId="
          // + getFileIdInt(fileName) + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_odm_12_xml")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        if ("1".equals(cdisc13)) {
          String odmVersion = "1.3";
          fileName =
              generateFileService.createODMFile(
                  odmVersion,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy,
                  generalFileDirCopy,
                  eb,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  studySubjectNumber,
                  true,
                  true,
                  true,
                  null);
          logger.debug("-- gen odm file 1.3");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_odm_13"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your ODM 1.3 XML file <a href='AccessFile?fileId="
          // + getFileIdInt(fileName) + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_odm_13")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        if ("1".equals(cdisc13oc)) {
          String odmVersion = "oc1.3";
          fileName =
              generateFileService.createODMFile(
                  odmVersion,
                  sysTimeBegin,
                  generalFileDir,
                  datasetBean,
                  activeStudy,
                  generalFileDirCopy,
                  eb,
                  activeStudy.getId(),
                  parentStudy.getId(),
                  studySubjectNumber,
                  true,
                  true,
                  true,
                  null);
          logger.debug("-- gen odm file 1.3 oc");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_odm_13_xml"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your ODM 1.3 w/OpenClinica Extension XML file <a
          // href='AccessFile?fileId="
          // + getFileIdInt(fileName)
          // + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_odm_13_xml")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }
        if ("1".equals(spss)) {
          SPSSReportBean answer = new SPSSReportBean();
          fileName =
              generateFileService.createSPSSFile(
                  datasetBean,
                  eb,
                  activeStudy,
                  parentStudy,
                  sysTimeBegin,
                  generalFileDir,
                  answer,
                  generalFileDirCopy);
          logger.debug("-- gen spss file");
          message.append(
              "<p>"
                  + pageMessages.getString("html_email_body_4")
                  + " "
                  + getFileNameStr(fileName)
                  + pageMessages.getString("html_email_body_4_5")
                  + SQLInitServlet.getField("sysURL.base")
                  + "AccessFile?fileId="
                  + getFileIdInt(fileName)
                  + pageMessages.getString("html_email_body_3")
                  + "</p>");

          // MessageFormat mf = new MessageFormat("");
          // mf.applyPattern(pageMessages.getString(
          // "you_can_access_spss"));
          // Object[] arguments = { getFileIdInt(fileName) };
          // auditMessage.append(mf.format(arguments));

          // auditMessage.append(
          // "You can access your SPSS files <a href='AccessFile?fileId="
          // + getFileIdInt(fileName) + "'>here</a>.<br/>");
          auditMessage.append(
              pageMessages.getString("you_can_access_spss")
                  + getFileIdInt(fileName)
                  + pageMessages.getString("access_end"));
        }

        // wrap up the message, and send the email
        message.append(
            "<p>"
                + pageMessages.getString("html_email_body_5")
                + "</P><P>"
                + pageMessages.getString("email_footer"));
        try {
          mailSender.sendEmail(
              alertEmail.trim(),
              pageMessages.getString("job_ran_for") + " " + datasetBean.getName(),
              message.toString(),
              true);
        } catch (OpenClinicaSystemException ose) {
          // Do Nothing, In the future we might want to have an email
          // status added to system.
        }
        TriggerBean triggerBean = new TriggerBean();
        triggerBean.setDataset(datasetBean);
        triggerBean.setUserAccount(userBean);
        triggerBean.setFullName(trigger.getName());
        auditEventDAO.createRowForExtractDataJobSuccess(triggerBean, auditMessage.toString());
      } else {
        TriggerBean triggerBean = new TriggerBean();
        // triggerBean.setDataset(datasetBean);
        triggerBean.setUserAccount(userBean);
        triggerBean.setFullName(trigger.getName());
        auditEventDAO.createRowForExtractDataJobFailure(triggerBean);
        // logger.debug("-- made it here for some reason, ds id: "
        // + dsId);
      }

      // logger.debug("-- generated file: " + fileNameStr);
      // dataSource.
    } catch (Exception e) {
      // TODO Auto-generated catch block -- ideally should generate a fail
      // msg here, tbh 02/2009
      logger.debug("-- found exception: " + e.getMessage());
      e.printStackTrace();
    }
  }
  /*
   * Purpose: Iterates over ODM to populate 2 objects: 1. importCRFList: A List of EventCRFs and information on how to
   * process them. 2. importCRFMap: A Map multi-layer map of Subject/Event/Form only populated when the subsequent
   * EventCRF passes the UpsertOn rules.
   */
  public ImportCRFInfoContainer(ODMContainer odmContainer, DataSource ds) {
    importCRFList = new ArrayList<ImportCRFInfo>();

    ArrayList<EventCRFBean> eventCRFBeans = new ArrayList<EventCRFBean>();
    ArrayList<Integer> eventCRFBeanIds = new ArrayList<Integer>();
    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);
    UpsertOnBean upsert = odmContainer.getCrfDataPostImportContainer().getUpsertOn();
    // If Upsert bean is not present, create one with default settings
    if (upsert == null) upsert = new UpsertOnBean();
    String studyOID = odmContainer.getCrfDataPostImportContainer().getStudyOID();
    StudyBean studyBean = studyDAO.findByOid(studyOID);
    ArrayList<SubjectDataBean> subjectDataBeans =
        odmContainer.getCrfDataPostImportContainer().getSubjectData();

    Map<String, Map<String, Map<String, String>>> subjectMap =
        new HashMap<String, Map<String, Map<String, String>>>();
    for (SubjectDataBean subjectDataBean : subjectDataBeans) {
      ArrayList<StudyEventDataBean> studyEventDataBeans = subjectDataBean.getStudyEventData();
      StudySubjectBean studySubjectBean =
          studySubjectDAO.findByOidAndStudy(subjectDataBean.getSubjectOID(), studyBean.getId());

      Map<String, Map<String, String>> eventMap = new HashMap<String, Map<String, String>>();
      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));
        // @pgawade 16-March-2011 Do not allow the data import
        // if event status is one of the - stopped, signed,
        // locked
        Map<String, String> formMap = new HashMap<String, String>();
        for (FormDataBean formDataBean : formDataBeans) {

          CRFVersionDAO crfVersionDAO = new CRFVersionDAO(ds);
          ArrayList<CRFVersionBean> crfVersionBeans =
              crfVersionDAO.findAllByOid(formDataBean.getFormOID());
          for (CRFVersionBean crfVersionBean : crfVersionBeans) {

            ArrayList<EventCRFBean> eventCrfBeans =
                eventCrfDAO.findByEventSubjectVersion(
                    studyEventBean, studySubjectBean, crfVersionBean);
            // what if we have begun with creating a study
            // event, but haven't entered data yet? this would
            // have us with a study event, but no corresponding
            // event crf, yet.
            if (eventCrfBeans.isEmpty()) {
              logger.debug(
                  "   found no event crfs from Study Event id "
                      + studyEventBean.getId()
                      + ", location "
                      + studyEventBean.getLocation());

              ImportCRFInfo importCrfInfo =
                  new ImportCRFInfo(
                      studyOID,
                      subjectDataBean.getSubjectOID(),
                      studyEventDataBean.getStudyEventOID(),
                      formDataBean.getFormOID());
              importCrfInfo.setPreImportStage(DataEntryStage.UNCOMPLETED);
              String crfStatus = formDataBean.getEventCRFStatus();
              if (crfStatus != null
                  && crfStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()))
                importCrfInfo.setPostImportStage(DataEntryStage.INITIAL_DATA_ENTRY);
              if ((studyEventBean.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED)
                  || studyEventBean
                      .getSubjectEventStatus()
                      .equals(SubjectEventStatus.DATA_ENTRY_STARTED)
                  || studyEventBean.getSubjectEventStatus().equals(SubjectEventStatus.COMPLETED))) {

                if (!upsert.isNotStarted()) {
                  importCrfInfo.setProcessImport(false);
                  importCrfInfo.setEventCRFID(null);
                }
              }
              importCRFList.add(importCrfInfo);
              if (importCrfInfo.isProcessImport()) formMap.put(formDataBean.getFormOID(), "true");
            }

            for (EventCRFBean ecb : eventCrfBeans) {
              ImportCRFInfo importCrfInfo =
                  new ImportCRFInfo(
                      studyOID,
                      subjectDataBean.getSubjectOID(),
                      studyEventDataBean.getStudyEventOID(),
                      formDataBean.getFormOID());
              importCrfInfo.setPreImportStage(ecb.getStage());
              String crfStatus = formDataBean.getEventCRFStatus();
              if (crfStatus != null
                  && crfStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()))
                importCrfInfo.setPostImportStage(DataEntryStage.INITIAL_DATA_ENTRY);
              importCrfInfo.setEventCRFID(new Integer(ecb.getId()));
              if (!(ecb.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY)
                      && upsert.isDataEntryStarted())
                  && !(ecb.getStage().equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE)
                      && upsert.isDataEntryComplete())) importCrfInfo.setProcessImport(false);
              importCRFList.add(importCrfInfo);
              if (importCrfInfo.isProcessImport()) formMap.put(formDataBean.getFormOID(), "true");
            }
          }
        } // formdata loop
        if (formMap.size() > 0) eventMap.put(studyEventDataBean.getStudyEventOID(), formMap);
      } // study event loop
      if (eventMap.size() > 0) subjectMap.put(subjectDataBean.getSubjectOID(), eventMap);
    } // subject data loop
    importCRFMap = subjectMap;
  }
  @RequestMapping(method = RequestMethod.GET)
  public ModelMap handleMainPage(HttpServletRequest request) {
    ModelMap map = new ModelMap();
    // setUpSidebar(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 = ruleSets != null ? ruleSets.size() : 0;

    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.addObject(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);

    UserAccountBean userBean = (UserAccountBean) request.getSession().getAttribute("userBean");
    request.setAttribute("userBean", userBean);
    request.setAttribute("statusMap", Status.toStudyUpdateMembersList());

    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");
    }
    return map;
  }
  private void submitStudy(StudyBean newStudy) {
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());

    StudyBean study1 = newStudy;
    logger.info("study bean to be updated:" + study1.getName());
    study1.setUpdatedDate(new Date());
    study1.setUpdater((UserAccountBean) session.getAttribute("userBean"));
    sdao.update(study1);

    ArrayList siteList = (ArrayList) sdao.findAllByParent(newStudy.getId());
    if (siteList.size() > 0) {
      sdao.updateSitesStatus(study1);
    }

    StudyParameterValueBean spv = new StudyParameterValueBean();

    spv.setStudyId(study1.getId());
    spv.setParameter("collectDob");
    spv.setValue(new Integer(study1.getStudyParameterConfig().getCollectDob()).toString());
    updateParameter(spvdao, spv);

    spv.setParameter("discrepancyManagement");
    spv.setValue(study1.getStudyParameterConfig().getDiscrepancyManagement());
    updateParameter(spvdao, spv);

    spv.setParameter("genderRequired");
    spv.setValue(study1.getStudyParameterConfig().getGenderRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("subjectPersonIdRequired");
    spv.setValue(study1.getStudyParameterConfig().getSubjectPersonIdRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameRequired");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameDefault");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameDefault());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewerNameEditable");
    spv.setValue(study1.getStudyParameterConfig().getInterviewerNameEditable());
    updateParameter(spvdao, spv);

    // BWP 1/12/2009 3169 Update interviewerNameEditable and
    // interviewDateEditable parameters for all sites>>
    List<StudyBean> sites = new ArrayList<StudyBean>();
    sites = (ArrayList) sdao.findAllByParent(newStudy.getId());
    if (sites != null && (!sites.isEmpty())) {
      updateInterviewerForSites(newStudy, sites, spvdao, "interviewerNameEditable");
    }
    // >>

    spv.setParameter("interviewDateRequired");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateRequired());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewDateDefault");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateDefault());
    updateParameter(spvdao, spv);

    spv.setParameter("interviewDateEditable");
    spv.setValue(study1.getStudyParameterConfig().getInterviewDateEditable());
    updateParameter(spvdao, spv);
    // BWP 1/12/2009 3169>>
    if (sites != null && (!sites.isEmpty())) {
      updateInterviewerForSites(newStudy, sites, spvdao, "interviewDateEditable");
    }
    // >>
    spv.setParameter("subjectIdGeneration");
    spv.setValue(study1.getStudyParameterConfig().getSubjectIdGeneration());
    updateParameter(spvdao, spv);

    spv.setParameter("subjectIdPrefixSuffix");
    spv.setValue(study1.getStudyParameterConfig().getSubjectIdPrefixSuffix());
    updateParameter(spvdao, spv);

    spv.setParameter("personIdShownOnCRF");
    spv.setValue(study1.getStudyParameterConfig().getPersonIdShownOnCRF());
    updateParameter(spvdao, spv);
    spv.setParameter("secondaryLabelViewable");
    spv.setValue(study1.getStudyParameterConfig().getSecondaryLabelViewable());
    updateParameter(spvdao, spv);

    // tbh, 06/04/2009 3684>>
    spv.setParameter("adminForcedReasonForChange");
    spv.setValue(study1.getStudyParameterConfig().getAdminForcedReasonForChange());
    updateParameter(spvdao, spv);
    // >>

    StudyBean curStudy = (StudyBean) session.getAttribute("study");
    if (curStudy != null && study1.getId() == curStudy.getId()) {
      super.currentStudy = study1;

      session.setAttribute("study", study1);
    }
    // update manage_pedigrees for all sites
    ArrayList children = (ArrayList) sdao.findAllByParent(study1.getId());
    for (int i = 0; i < children.size(); i++) {
      StudyBean child = (StudyBean) children.get(i);
      child.setType(study1.getType()); // same as parent's type
      child.setUpdatedDate(new Date());
      child.setUpdater(ub);
      sdao.update(child);
      // YW << update "collectDob" and "genderRequired" for sites
      StudyParameterValueBean childspv = new StudyParameterValueBean();
      childspv.setStudyId(child.getId());
      childspv.setParameter("collectDob");
      childspv.setValue(new Integer(study1.getStudyParameterConfig().getCollectDob()).toString());
      updateParameter(spvdao, childspv);
      childspv.setParameter("genderRequired");
      childspv.setValue(study1.getStudyParameterConfig().getGenderRequired());
      updateParameter(spvdao, childspv);
    }
  }
  @Override
  public void processRequest() throws Exception {
    resetPanel();
    FormProcessor fp = new FormProcessor(request);
    Validator v = new Validator(request);
    int studyId = fp.getInt("id");
    studyId = studyId == 0 ? fp.getInt("studyId") : studyId;
    String action = fp.getString("action");
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    boolean isInterventional = false;

    study = (StudyBean) sdao.findByPK(studyId);
    if (study.getId() != currentStudy.getId()) {
      addPageMessage(
          respage.getString("not_current_study")
              + respage.getString("change_study_contact_sysadmin"));
      forwardPage(Page.MENU_SERVLET);
      return;
    }

    study.setId(studyId);
    StudyConfigService scs = new StudyConfigService(sm.getDataSource());
    study = scs.setParametersForStudy(study);
    request.setAttribute("studyToView", study);

    request.setAttribute("studyId", studyId + "");
    request.setAttribute("studyPhaseMap", CreateStudyServlet.studyPhaseMap);
    ArrayList statuses = Status.toStudyUpdateMembersList();
    statuses.add(Status.PENDING);
    request.setAttribute("statuses", statuses);

    String interventional = resadmin.getString("interventional");
    isInterventional = interventional.equalsIgnoreCase(study.getProtocolType());

    request.setAttribute("isInterventional", isInterventional ? "1" : "0");
    String protocolType = study.getProtocolTypeKey();

    // A. Hamid. 5001
    if (study.getParentStudyId() > 0) {
      StudyBean parentStudy = (StudyBean) sdao.findByPK(study.getParentStudyId());
      request.setAttribute("parentStudy", parentStudy);
    }

    ArrayList interventionArray = new ArrayList();
    if (isInterventional) {
      interventionArray = parseInterventions((study));
      setMaps(isInterventional, interventionArray);
    } else {
      setMaps(isInterventional, interventionArray);
    }

    if (!action.equals("submit")) {

      // First Load First Form
      if (study.getDatePlannedStart() != null) {
        fp.addPresetValue(INPUT_START_DATE, local_df.format(study.getDatePlannedStart()));
      }
      if (study.getDatePlannedEnd() != null) {
        fp.addPresetValue(INPUT_END_DATE, local_df.format(study.getDatePlannedEnd()));
      }
      if (study.getProtocolDateVerification() != null) {
        fp.addPresetValue(INPUT_VER_DATE, local_df.format(study.getProtocolDateVerification()));
      }
      setPresetValues(fp.getPresetValues());
      // first load 2nd form
    }
    if (study == null) {
      addPageMessage(respage.getString("please_choose_a_study_to_edit"));
      forwardPage(Page.STUDY_LIST_SERVLET);
      return;
    }
    if (action.equals("submit")) {

      validateStudy1(fp, v);
      validateStudy2(fp, v);
      validateStudy3(isInterventional, v, fp);
      validateStudy4(fp, v);
      validateStudy5(fp, v);
      validateStudy6(fp, v);
      confirmWholeStudy(fp, v);

      request.setAttribute("studyToView", study);
      if (!errors.isEmpty()) {
        System.out.println("found errors : " + errors.toString());
        request.setAttribute("formMessages", errors);

        forwardPage(Page.UPDATE_STUDY_NEW);
      } else {
        study.setProtocolType(protocolType);
        submitStudy(study);
        addPageMessage(respage.getString("the_study_has_been_updated_succesfully"));
        ArrayList pageMessages = (ArrayList) request.getAttribute(PAGE_MESSAGE);
        session.setAttribute("pageMessages", pageMessages);
        response.sendRedirect(request.getContextPath() + "/pages/studymodule");
        // forwardPage(Page.MANAGE_STUDY_MODULE);
      }
    } else {
      forwardPage(Page.UPDATE_STUDY_NEW);
    }
  }
  private void collectMetaDataVersion() {
    ArrayList<StudyEventDefinitionBean> sedBeansInStudy =
        (ArrayList<StudyEventDefinitionBean>) studyBase.getSedBeansInStudy();
    if (sedBeansInStudy == null || sedBeansInStudy.size() < 1) {
      logger.info("null, because there is no study event definition in this study.");
      return;
    }

    StudyBean study = studyBase.getStudy();
    MetaDataVersionBean metadata = this.odmStudy.getMetaDataVersion();

    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(this.ds);
    int parentId = study.getParentStudyId() > 0 ? study.getParentStudyId() : study.getId();
    StudyParameterValueBean spv = spvdao.findByHandleAndStudy(parentId, "discrepancyManagement");
    metadata.setSoftHard(spv.getValue().equalsIgnoreCase("true") ? "Hard" : "Soft");

    OdmExtractDAO oedao = new OdmExtractDAO(this.ds);
    int studyId = study.getId();
    int parentStudyId = study.getParentStudyId() > 0 ? study.getParentStudyId() : studyId;
    if (this.getCategory() == 1 && study.isSite(study.getParentStudyId())) {
      // populate MetaDataVersion attributes
      if (dataset != null) {
        metadata.setOid(dataset.getODMMetaDataVersionOid() + "-" + study.getOid());
        metadata.setName(dataset.getODMMetaDataVersionName() + "-" + study.getOid());
        this.setParentMetaDataVersionOid(dataset.getODMMetaDataVersionOid());
      }
      if (metadata.getOid() == null || metadata.getOid().length() <= 0) {
        metadata.setOid("v1.0.0" + "-" + study.getOid());
        this.setParentMetaDataVersionOid("v1.0.0");
      }
      if (metadata.getName() == null || metadata.getName().length() <= 0) {
        metadata.setName("MetaDataVersion_v1.0.0" + "-" + study.getOid());
      }

      // populate Include
      this.collectIncludeFromParentInSameFile();

      // populate protocol
      oedao.getUpdatedSiteMetadata(parentStudyId, studyId, metadata, this.odmBean.getODMVersion());
    } else {
      if (dataset != null) {
        metadata.setOid(dataset.getODMMetaDataVersionOid());
        metadata.setName(dataset.getODMMetaDataVersionName());
      }
      if (metadata.getOid() == null || metadata.getOid().length() <= 0) {
        metadata.setOid("v1.0.0");
      }
      if (metadata.getName() == null || metadata.getName().length() <= 0) {
        metadata.setName("MetaDataVersion_v1.0.0");
      }

      // populate Include
      String psOid = new String();
      String pmOid = new String();
      if (dataset != null) {
        psOid = dataset.getODMPriorStudyOid();
        pmOid = dataset.getODMPriorMetaDataVersionOid();
      }
      if (pmOid != null && pmOid.length() > 0) {
        MetaDataVersionIncludeBean ib = metadata.getInclude();
        ib.setMetaDataVersionOID(pmOid);
        if (psOid != null && psOid.length() > 0) {
          ib.setStudyOID(psOid);
        } else {
          ib.setStudyOID(study.getOid());
        }
      }

      // populate protocol
      // Set<Integer> nullCodeSet = oedao.getMetadata(parentStudyId,
      // studyId,
      // metadata, this.getODMBean().getODMVersion());
      // studyBase.setNullClSet(nullCodeSet);
      oedao.getMetadata(parentStudyId, studyId, metadata, this.odmBean.getODMVersion());
    }
  }