/**
   * Send email to the user, director and administrator
   *
   * @param request
   * @param response
   */
  private String sendEmail(UserAccountBean u, StudyUserRoleBean sub) throws Exception {

    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    StudyBean study = (StudyBean) sdao.findByPK(sub.getStudyId());
    logger.info("Sending email...");
    String body =
        u.getFirstName()
            + " "
            + u.getLastName()
            + " ("
            + resword.getString("username")
            + ": "
            + u.getName()
            + ") "
            + respage.getString("has_been_granted_the_role")
            + " "
            + sub.getRoleName()
            + " "
            + respage.getString("in_the_study_site")
            + " "
            + study.getName()
            + ".";

    //        boolean emailSent = sendEmail(u.getEmail().trim(), respage.getString("set_user_role"),
    // body, false);
    //        if (emailSent) {
    //            sendEmail(ub.getEmail().trim(), respage.getString("set_user_role"), body, false);
    //            sendEmail(EmailEngine.getAdminEmail(), respage.getString("set_user_role"), body,
    // false);
    //        }
    return body;
  }
  @Override
  protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    TriggerService triggerService = new TriggerService();
    String action = fp.getString("action");
    String triggerName = fp.getString("tname");
    scheduler = getScheduler();
    System.out.println("found trigger name " + triggerName);
    Trigger trigger = scheduler.getTrigger(triggerName.trim(), TRIGGER_IMPORT_GROUP);
    System.out.println("found trigger from the other side " + trigger.getFullName());
    if (StringUtil.isBlank(action)) {
      setUpServlet(trigger);
      forwardPage(Page.UPDATE_JOB_IMPORT);
    } else if ("confirmall".equalsIgnoreCase(action)) {
      HashMap errors =
          triggerService.validateImportJobForm(
              fp, request, scheduler.getTriggerNames("DEFAULT"), trigger.getName());
      if (!errors.isEmpty()) {
        // send back
        addPageMessage(
            "Your modifications caused an error, please see the messages for more information.");
        setUpServlet(trigger);
        forwardPage(Page.UPDATE_JOB_IMPORT);
      } else {
        StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
        int studyId = fp.getInt(CreateJobImportServlet.STUDY_ID);
        StudyBean study = (StudyBean) studyDAO.findByPK(studyId);
        // in the place of a users' current study, tbh
        Date startDate = trigger.getStartTime();
        trigger =
            triggerService.generateImportTrigger(
                fp, sm.getUserBean(), study, startDate, request.getLocale().getLanguage());
        // scheduler = getScheduler();
        JobDetailBean jobDetailBean = new JobDetailBean();
        jobDetailBean.setGroup(TRIGGER_IMPORT_GROUP);
        jobDetailBean.setName(trigger.getName());
        jobDetailBean.setJobClass(org.akaza.openclinica.web.job.ImportStatefulJob.class);
        jobDetailBean.setJobDataMap(trigger.getJobDataMap());
        jobDetailBean.setDurability(true); // need durability?
        jobDetailBean.setVolatility(false);

        try {
          scheduler.deleteJob(triggerName, TRIGGER_IMPORT_GROUP);
          Date dateStart = scheduler.scheduleJob(jobDetailBean, trigger);

          addPageMessage("Your job has been successfully modified.");
          forwardPage(Page.VIEW_IMPORT_JOB_SERVLET);
        } catch (SchedulerException se) {
          se.printStackTrace();
          // set a message here with the exception message
          setUpServlet(trigger);
          addPageMessage(
              "There was an unspecified error with your creation, please contact an administrator.");
          forwardPage(Page.UPDATE_JOB_IMPORT);
        }
      }
    }
  }
  /**
   * This method creates a List of DisplaySectionBeans, returning them in the order that the
   * sections appear in a CRF. This List is "lazily" initialized the first time it is requested.
   *
   * @return A List of DisplaySectionBeans.
   * @see org.akaza.openclinica.control.managestudy.PrintCRFServlet
   * @see org.akaza.openclinica.control.managestudy.PrintDataEntryServlet
   */
  public List<DisplaySectionBean> getDisplaySectionBeans() {
    FormBeanUtil formBeanUtil;
    ViewPersistanceHandler persistanceHandler;
    ArrayList<SectionBean> allCrfSections;
    // DAO classes for getting item definitions
    SectionDAO sectionDao;
    CRFVersionDAO crfVersionDao;

    if (displaySectionBeans == null) {
      displaySectionBeans = new ArrayList<DisplaySectionBean>();
      formBeanUtil = new FormBeanUtil();
      if (hasStoredData) persistanceHandler = new ViewPersistanceHandler();

      // We need a CRF version id to populate the form display
      if (this.crfVersionId == 0) {
        return displaySectionBeans;
      }

      sectionDao = new SectionDAO(dataSource);
      allCrfSections = (ArrayList) sectionDao.findByVersionId(this.crfVersionId);

      // for the purposes of null values, try to obtain a valid
      // eventCrfDefinition id
      EventDefinitionCRFBean eventDefBean = null;
      EventCRFBean eventCRFBean = new EventCRFBean();
      if (eventCRFId > 0) {
        EventCRFDAO ecdao = new EventCRFDAO(dataSource);
        eventCRFBean = (EventCRFBean) ecdao.findByPK(eventCRFId);
        StudyEventDAO sedao = new StudyEventDAO(dataSource);
        StudyEventBean studyEvent = (StudyEventBean) sedao.findByPK(eventCRFBean.getStudyEventId());

        EventDefinitionCRFDAO eventDefinitionCRFDAO = new EventDefinitionCRFDAO(dataSource);
        StudyDAO sdao = new StudyDAO(dataSource);
        StudyBean study = sdao.findByStudySubjectId(eventCRFBean.getStudySubjectId());
        eventDefBean =
            eventDefinitionCRFDAO.findByStudyEventIdAndCRFVersionId(
                study, studyEvent.getId(), this.crfVersionId);
      }
      eventDefBean = eventDefBean == null ? new EventDefinitionCRFBean() : eventDefBean;
      // Create an array or List of DisplaySectionBeans representing each
      // section
      // for printing
      DisplaySectionBean displaySectionBean;
      for (SectionBean sectionBean : allCrfSections) {
        displaySectionBean =
            formBeanUtil.createDisplaySectionBWithFormGroups(
                sectionBean.getId(),
                this.crfVersionId,
                dataSource,
                eventDefBean.getId(),
                eventCRFBean,
                context);
        displaySectionBeans.add(displaySectionBean);
      }
    }
    return displaySectionBeans;
  }
  /** 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);
  }
  @Override
  public void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    StudyGroupClassDAO sgcdao = new StudyGroupClassDAO(sm.getDataSource());
    // YW <<
    StudyDAO stdao = new StudyDAO(sm.getDataSource());
    int parentStudyId = currentStudy.getParentStudyId();
    ArrayList groups = new ArrayList();
    if (parentStudyId > 0) {
      StudyBean parentStudy = (StudyBean) stdao.findByPK(parentStudyId);
      groups = sgcdao.findAllByStudy(parentStudy);
    } else {
      groups = sgcdao.findAllByStudy(currentStudy);
    }
    // YW >>
    String isReadOnly = request.getParameter("read");

    StudyGroupDAO sgdao = new StudyGroupDAO(sm.getDataSource());
    for (int i = 0; i < groups.size(); i++) {
      StudyGroupClassBean group = (StudyGroupClassBean) groups.get(i);
      ArrayList studyGroups = sgdao.findAllByGroupClass(group);
      group.setStudyGroups(studyGroups);
    }
    EntityBeanTable table = fp.getEntityBeanTable();
    ArrayList allGroupRows = StudyGroupClassRow.generateRowsFromBeans(groups);
    boolean isParentStudy = currentStudy.getParentStudyId() > 0 ? false : true;
    request.setAttribute("isParentStudy", isParentStudy);

    String[] columns = {
      resword.getString("subject_group_class"),
      resword.getString("type"),
      resword.getString("subject_assignment"),
      resword.getString("study_name"),
      resword.getString("subject_groups"),
      resword.getString("status"),
      resword.getString("actions")
    };
    table.setColumns(new ArrayList(Arrays.asList(columns)));
    table.hideColumnLink(4);
    table.hideColumnLink(6);
    table.setQuery("ListSubjectGroupClass", new HashMap());
    // if (isParentStudy && (!currentStudy.getStatus().isLocked())) {
    // table.addLink(resword.getString("create_a_subject_group_class"),
    // "CreateSubjectGroupClass");
    // }
    table.setRows(allGroupRows);
    table.computeDisplay();

    request.setAttribute("table", table);
    if (request.getParameter("read") != null && request.getParameter("read").equals("true")) {
      request.setAttribute("readOnly", true);
    }
    forwardPage(Page.SUBJECT_GROUP_CLASS_LIST);
  }
  @RequestMapping(value = "/studies/{study}/validateAndSaveRule", method = RequestMethod.POST)
  public @ResponseBody Response validateAndSave(
      @RequestBody org.openclinica.ns.rules.v31.Rules rules,
      Model model,
      HttpSession session,
      @PathVariable("study") String studyOid,
      @RequestParam("ignoreDuplicates") Boolean ignoreDuplicates)
      throws Exception {
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    RulesPostImportContainer rpic = mapRulesToRulesPostImportContainer(rules);
    StudyDAO studyDao = new StudyDAO(dataSource);
    StudyBean currentStudy = studyDao.findByOid(studyOid);

    UserAccountBean userAccount = getUserAccount();
    mayProceed(userAccount, currentStudy);

    getRulePostImportContainerService(currentStudy, userAccount);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleDefs(rpic);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleSetDefs(rpic);
    Response response = new Response();
    response.setValid(Boolean.TRUE);
    if (rpic.getInValidRuleDefs().size() > 0 || rpic.getInValidRuleSetDefs().size() > 0) {
      response.setValid(Boolean.FALSE);
      for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getInValidRuleDefs()) {
        for (String error : beanWrapper.getImportErrors()) {
          org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
          messageType.setMessage(error);
          response.getMessages().add(messageType);
        }
      }
      for (AuditableBeanWrapper<RuleSetBean> beanWrapper : rpic.getInValidRuleSetDefs()) {
        for (String error : beanWrapper.getImportErrors()) {
          org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
          messageType.setMessage(error);
          response.getMessages().add(messageType);
        }
      }
    } else if ((rpic.getDuplicateRuleDefs().size() > 0) && !ignoreDuplicates) {
      response.setValid(Boolean.FALSE);
      for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getDuplicateRuleDefs()) {
        org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
        messageType.setMessage(DUPLICATE_MESSAGE);
        response.getMessages().add(messageType);
      }
    } else {
      getRuleSetService().saveImportFromDesigner(rpic);
    }
    logger.debug("RPIC READY");
    return response;
  }
  public StudySubjectBean getSSBean(HashMap<String, String> userContext) throws Exception {
    String studySubjectOid = userContext.get("studySubjectOID");
    StudySubjectBean ssBean = null;
    StudySubjectDAO ssdao = new StudySubjectDAO(dataSource);
    SubjectDAO subjectdao = new SubjectDAO(dataSource);
    UserAccountDAO udao = new UserAccountDAO(dataSource);
    if (studySubjectOid != null) {
      ssBean = ssdao.findByOid(studySubjectOid);
    } else {
      String studyOid = userContext.get("studyOID");

      StudyBean studyBean = sdao.findByOid(studyOid);
      int studyEventDefnId = Integer.valueOf(userContext.get("studyEventDefinitionID"));
      int studyEventOrdinal = Integer.valueOf(userContext.get("studyEventOrdinal"));
      UserAccountBean uBean = (UserAccountBean) udao.findByPK(1);
      // build Subject Account
      SubjectBean subjectBean = createSubjectBean(uBean);
      subjectBean = (SubjectBean) subjectdao.findByPK(subjectBean.getId());
      // build StudySubject Account
      ssBean = createStudySubjectBean(studyBean, subjectBean, uBean);
      ssBean = (StudySubjectBean) ssdao.findByPK(ssBean.getId());
      System.out.println("study subject oid:  " + ssBean.getOid());
      // build User Account
      UserAccountBean userAccountBean = createUserAccount(uBean, studyBean, ssBean);
      userAccountBean = (UserAccountBean) udao.findByPK(userAccountBean.getId());
      // build and schedule study Event
      StudyEventBean studyEventBean =
          createStudyEventBean(ssBean, studyEventDefnId, studyEventOrdinal, userAccountBean);
    }
    return ssBean;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.akaza.openclinica.control.core.SecureController#processRequest()
   */
  @Override
  protected void processRequest() throws Exception {

    // find last 5 modifed studies
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    ArrayList studies = (ArrayList) sdao.findAllByLimit(true);
    request.setAttribute("studies", studies);
    ArrayList allStudies = (ArrayList) sdao.findAll();
    request.setAttribute("allStudyNumber", new Integer(allStudies.size()));

    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    ArrayList users = (ArrayList) udao.findAllByLimit(true);
    request.setAttribute("users", users);
    ArrayList allUsers = (ArrayList) udao.findAll();
    request.setAttribute("allUserNumber", new Integer(allUsers.size()));

    SubjectDAO subdao = new SubjectDAO(sm.getDataSource());
    ArrayList subjects = (ArrayList) subdao.findAllByLimit(true);
    request.setAttribute("subjects", subjects);
    ArrayList allSubjects = (ArrayList) subdao.findAll();
    request.setAttribute("allSubjectNumber", new Integer(allSubjects.size()));

    CRFDAO cdao = new CRFDAO(sm.getDataSource());
    ArrayList crfs = (ArrayList) cdao.findAllByLimit(true);
    request.setAttribute("crfs", crfs);
    ArrayList allCrfs = (ArrayList) cdao.findAll();
    request.setAttribute("allCrfNumber", new Integer(allCrfs.size()));

    resetPanel();
    panel.setOrderedData(true);
    setToPanel(resword.getString("in_the_application"), "");
    if (allSubjects.size() > 0) {
      setToPanel(resword.getString("subjects"), new Integer(allSubjects.size()).toString());
    }
    if (allUsers.size() > 0) {
      setToPanel(resword.getString("users"), new Integer(allUsers.size()).toString());
    }
    if (allStudies.size() > 0) {
      setToPanel(resword.getString("studies"), new Integer(allStudies.size()).toString());
    }
    if (allCrfs.size() > 0) {
      setToPanel(resword.getString("CRFs"), new Integer(allCrfs.size()).toString());
    }

    panel.setStudyInfoShown(false);
    forwardPage(Page.ADMIN_SYSTEM);
  }
 private StudyBean getParentStudy(String studyOid) {
   StudyBean study = getStudy(studyOid);
   if (study.getParentStudyId() == 0) {
     return study;
   } else {
     StudyBean parentStudy = (StudyBean) sdao.findByPK(study.getParentStudyId());
     return parentStudy;
   }
 }
  @RequestMapping(method = RequestMethod.POST)
  public String processSubmit(
      @ModelAttribute("studyModuleStatus") StudyModuleStatus studyModuleStatus,
      BindingResult result,
      SessionStatus status,
      HttpServletRequest request) {
    StudyBean currentStudy = (StudyBean) request.getSession().getAttribute("study");
    studyModuleStatusDao.saveOrUpdate(studyModuleStatus);
    status.setComplete();

    currentStudy.setStatus(Status.get(studyModuleStatus.getStudyStatus()));
    if (currentStudy.getParentStudyId() > 0) {
      studyDao.updateStudyStatus(currentStudy);
    } else {
      studyDao.updateStudyStatus(currentStudy);
    }

    return "redirect:studymodule";
  }
  @RequestMapping(value = "/studies/{study}/connect", method = RequestMethod.POST)
  public @ResponseBody org.openclinica.ns.response.v31.Response create(
      @RequestBody org.openclinica.ns.response.v31.Response responeType,
      Model model,
      HttpSession session,
      @PathVariable("study") String studyOid)
      throws Exception {
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    StudyDAO studyDao = new StudyDAO(dataSource);
    StudyBean currentStudy = studyDao.findByOid(studyOid);

    UserAccountBean userAccount = getUserAccount();
    mayProceed(userAccount, currentStudy);

    Response response = new Response();
    response.setValid(Boolean.TRUE);
    org.openclinica.ns.response.v31.MessagesType theMessageType = new MessagesType();
    theMessageType.setMessage("Hello");
    response.getMessages().add(theMessageType);
    logger.debug("RPIC READY");
    return response;
    // model.addAttribute("response", response);
  }
  @Override
  public void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    int studySubId = fp.getInt(STUDY_SUB_ID, true);
    int eventCRFId = fp.getInt(EVENT_CRF_ID);

    String action = request.getParameter("action");

    StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
    StudySubjectDAO subdao = new StudySubjectDAO(sm.getDataSource());
    EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());
    StudyDAO sdao = new StudyDAO(sm.getDataSource());

    if (eventCRFId == 0) {
      addPageMessage(respage.getString("please_choose_an_event_CRF_to_delete"));
      request.setAttribute("id", new Integer(studySubId).toString());
      forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
    } else {
      EventCRFBean eventCRF = (EventCRFBean) ecdao.findByPK(eventCRFId);

      StudySubjectBean studySub = (StudySubjectBean) subdao.findByPK(studySubId);
      request.setAttribute("studySub", studySub);

      // construct info needed on view event crf page
      CRFDAO cdao = new CRFDAO(sm.getDataSource());
      CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());

      int crfVersionId = eventCRF.getCRFVersionId();
      CRFBean cb = cdao.findByVersionId(crfVersionId);
      eventCRF.setCrf(cb);

      CRFVersionBean cvb = (CRFVersionBean) cvdao.findByPK(crfVersionId);
      eventCRF.setCrfVersion(cvb);

      // then get the definition so we can call
      // DisplayEventCRFBean.setFlags
      int studyEventId = eventCRF.getStudyEventId();

      StudyEventBean event = (StudyEventBean) sedao.findByPK(studyEventId);

      int studyEventDefinitionId = sedao.getDefinitionIdFromStudyEventId(studyEventId);
      StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
      StudyEventDefinitionBean sed =
          (StudyEventDefinitionBean) seddao.findByPK(studyEventDefinitionId);
      event.setStudyEventDefinition(sed);
      request.setAttribute("event", event);

      EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());

      StudyBean study = (StudyBean) sdao.findByPK(studySub.getStudyId());
      EventDefinitionCRFBean edc =
          edcdao.findByStudyEventDefinitionIdAndCRFId(study, studyEventDefinitionId, cb.getId());

      DisplayEventCRFBean dec = new DisplayEventCRFBean();
      dec.setEventCRF(eventCRF);
      dec.setFlags(eventCRF, ub, currentRole, edc.isDoubleEntry());

      // find all item data
      ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
      dnDao = new DiscrepancyNoteDAO(sm.getDataSource());
      ArrayList<ItemDataBean> itemData = iddao.findAllByEventCRFId(eventCRF.getId());
      request.setAttribute("items", itemData);

      if ("confirm".equalsIgnoreCase(action)) {

        request.setAttribute("displayEventCRF", dec);

        forwardPage(Page.DELETE_EVENT_CRF);
      } else {
        logger.info("submit to delete the event CRF from event");

        // OC-6303  Deleting Event CRF resets Show / Hide logic
        // delete records from DynamicItemForm and DynamicItemGroup
        getDynamicsItemFormMetadataDao().delete(eventCRFId);
        getDynamicsItemGroupMetadataDao().delete(eventCRFId);

        eventCRF.setOldStatus(eventCRF.getStatus());
        eventCRF.setStatus(Status.RESET);
        eventCRF.setUpdater(ub);
        ecdao.update(eventCRF);

        for (ItemDataBean itemdata : itemData) {
          // OC-6343 Rule behaviour must be reset if an Event CRF is deleted
          // delete the records from ruleActionRunLogDao
          getRuleActionRunLogDao().delete(itemdata.getId());

          // OC-6344 Notes & Discrepancies must be set to "closed" when event CRF is deleted
          // parentDiscrepancyNoteList is the list of the parent DNs records only
          ArrayList<DiscrepancyNoteBean> parentDiscrepancyNoteList =
              getDnDao().findParentNotesOnlyByItemData(itemdata.getId());
          for (DiscrepancyNoteBean parentDiscrepancyNote : parentDiscrepancyNoteList) {
            if (parentDiscrepancyNote.getResolutionStatusId()
                != 4) { // if the DN's resolution status is not set to Closed
              String description = resword.getString("dn_auto-closed_description");
              String detailedNotes = resword.getString("dn_auto_closed_detailed_notes");
              // create new DN record , new DN Map record , also update the parent record
              createDiscrepancyNoteBean(
                  description, detailedNotes, itemdata.getId(), study, ub, parentDiscrepancyNote);
            }
          }
          iddao = new ItemDataDAO(sm.getDataSource());
          ifmdao = new ItemFormMetadataDAO(sm.getDataSource());
          ItemDataBean idBean = (ItemDataBean) iddao.findByPK(itemdata.getId());

          ItemFormMetadataBean ifmBean =
              ifmdao.findByItemIdAndCRFVersionId(idBean.getItemId(), crfVersionId);

          // Updating Dn_item_data_map actovated column into false for the existing DNs
          ArrayList<DiscrepancyNoteBean> dnBeans =
              getDnDao().findExistingNotesForItemData(itemdata.getId());
          if (dnBeans.size() != 0) {
            DiscrepancyNoteBean dnBean = new DiscrepancyNoteBean();
            dnBean.setEntityId(itemdata.getId());
            dnBean.setActivated(false);
            getDnDao().updateDnMapActivation(dnBean);
          }

          // Default Values are not addressed

          itemdata.setValue("");
          itemdata.setOldStatus(itemdata.getStatus());
          itemdata.setOwner(ub);
          itemdata.setStatus(Status.AVAILABLE);
          itemdata.setUpdater(ub);
          iddao.updateUser(itemdata);
          iddao.update(itemdata);
        }
        // OC-6291 event_crf status change

        eventCRF.setOldStatus(eventCRF.getStatus());
        eventCRF.setStatus(Status.AVAILABLE);
        eventCRF.setUpdater(ub);
        ecdao.update(eventCRF);

        if (event.getSubjectEventStatus().isCompleted()
            || event.getSubjectEventStatus().isSigned()) {
          event.setSubjectEventStatus(SubjectEventStatus.DATA_ENTRY_STARTED);
          event.setUpdater(ub);
          sedao = new StudyEventDAO(sm.getDataSource());
          sedao.update(event);
        }

        String emailBody =
            respage.getString("the_event_CRF")
                + cb.getName()
                + respage.getString("has_been_deleted_from_the_event")
                + event.getStudyEventDefinition().getName()
                + ". "
                + respage.getString("has_been_deleted_from_the_event_cont");

        addPageMessage(emailBody);
        // sendEmail(emailBody);
        request.setAttribute("id", new Integer(studySubId).toString());
        forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
      }
    }
  }
  @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;
  }
  @Override
  public void processRequest() throws Exception {
    String studySubIdString = request.getParameter("id"); // studySubjectId
    String subIdString = request.getParameter("subjectId");
    String studyIdString = request.getParameter("studyId");

    SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
    StudySubjectDAO subdao = new StudySubjectDAO(sm.getDataSource());

    if (StringUtil.isBlank(studySubIdString)
        || StringUtil.isBlank(subIdString)
        || StringUtil.isBlank(studyIdString)) {
      addPageMessage(respage.getString("please_choose_a_study_subject_to_remove"));
      forwardPage(Page.LIST_STUDY_SUBJECT_SERVLET);
    } else {
      int studyId = Integer.valueOf(studyIdString.trim()).intValue();
      int studySubId = Integer.valueOf(studySubIdString.trim()).intValue();
      int subjectId = Integer.valueOf(subIdString.trim()).intValue();

      SubjectBean subject = (SubjectBean) sdao.findByPK(subjectId);

      StudySubjectBean studySub = (StudySubjectBean) subdao.findByPK(studySubId);

      StudyDAO studydao = new StudyDAO(sm.getDataSource());
      StudyBean study = (StudyBean) studydao.findByPK(studyId);

      // find study events
      StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
      ArrayList events = sedao.findAllByStudyAndStudySubjectId(study, studySubId);

      String action = request.getParameter("action");
      if ("confirm".equalsIgnoreCase(action)) {
        if (!studySub.getStatus().equals(Status.AVAILABLE)) {
          addPageMessage(
              respage.getString("this_subject_is_not_available_for_this_study")
                  + " "
                  + respage.getString("please_contact_sysadmin_for_more_information"));
          forwardPage(Page.LIST_STUDY_SUBJECT_SERVLET);
          return;
        }

        request.setAttribute("subject", subject);
        request.setAttribute("study", study);
        request.setAttribute("studySub", studySub);
        request.setAttribute("events", events);

        forwardPage(Page.REMOVE_STUDY_SUBJECT);
      } else {
        logger.info("submit to remove the subject from study");
        // remove subject from study
        studySub.setStatus(Status.DELETED);
        studySub.setUpdater(ub);
        studySub.setUpdatedDate(new Date());
        subdao.update(studySub);

        // remove all study events
        // remove all event crfs
        EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());

        for (int j = 0; j < events.size(); j++) {
          StudyEventBean event = (StudyEventBean) events.get(j);
          if (!event.getStatus().equals(Status.DELETED)) {
            event.setStatus(Status.AUTO_DELETED);
            event.setUpdater(ub);
            event.setUpdatedDate(new Date());
            sedao.update(event);

            ArrayList eventCRFs = ecdao.findAllByStudyEvent(event);

            ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
            for (int k = 0; k < eventCRFs.size(); k++) {
              EventCRFBean eventCRF = (EventCRFBean) eventCRFs.get(k);
              if (!eventCRF.getStatus().equals(Status.DELETED)) {
                eventCRF.setStatus(Status.AUTO_DELETED);
                eventCRF.setUpdater(ub);
                eventCRF.setUpdatedDate(new Date());
                ecdao.update(eventCRF);
                // remove all the item data
                ArrayList itemDatas = iddao.findAllByEventCRFId(eventCRF.getId());
                for (int a = 0; a < itemDatas.size(); a++) {
                  ItemDataBean item = (ItemDataBean) itemDatas.get(a);
                  if (!item.getStatus().equals(Status.DELETED)) {
                    item.setStatus(Status.AUTO_DELETED);
                    item.setUpdater(ub);
                    item.setUpdatedDate(new Date());
                    iddao.update(item);
                  }
                }
              }
            }
          }
        }

        String emailBody =
            respage.getString("the_subject")
                + " "
                + subject.getName()
                + " "
                + respage.getString("has_been_removed_from_the_study")
                + study.getName()
                + ".";

        addPageMessage(emailBody);
        sendEmail(emailBody);
        forwardPage(Page.LIST_STUDY_SUBJECT_SERVLET);
      }
    }
  }
  @RequestMapping(value = "/studies/{study}/validateAndTestRule", method = RequestMethod.POST)
  public @ResponseBody org.openclinica.ns.rules_test.v31.RulesTest create(
      @RequestBody org.openclinica.ns.rules_test.v31.RulesTest ruleTest,
      Model model,
      HttpSession session,
      @PathVariable("study") String studyOid)
      throws Exception {
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    RulesPostImportContainer rpic = mapRulesToRulesPostImportContainer(ruleTest.getRules());
    StudyDAO studyDao = new StudyDAO(dataSource);
    StudyBean currentStudy = studyDao.findByOid(studyOid);

    UserAccountBean userAccount = getUserAccount();
    mayProceed(userAccount, currentStudy);

    getRulePostImportContainerService(currentStudy, userAccount);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleDefs(rpic);
    rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleSetDefs(rpic);
    Response response = new Response();
    response.setValid(Boolean.TRUE);
    if (rpic.getInValidRuleDefs().size() > 0 || rpic.getInValidRuleSetDefs().size() > 0) {
      response.setValid(Boolean.FALSE);
      for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getInValidRuleDefs()) {
        for (String error : beanWrapper.getImportErrors()) {
          org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
          messageType.setMessage(error);
          response.getMessages().add(messageType);
        }
      }
      for (AuditableBeanWrapper<RuleSetBean> beanWrapper : rpic.getInValidRuleSetDefs()) {
        for (String error : beanWrapper.getImportErrors()) {
          org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
          messageType.setMessage(error);
          response.getMessages().add(messageType);
        }
      }
    }

    HashMap<String, String> p = new HashMap<String, String>();
    for (ParameterType parameterType : ruleTest.getParameters()) {
      p.put(parameterType.getKey(), parameterType.getValue());
    }
    ExpressionObjectWrapper eow =
        new ExpressionObjectWrapper(
            dataSource,
            currentStudy,
            rpic.getRuleDefs().get(0).getExpression(),
            rpic.getRuleSets().get(0));
    ExpressionProcessor ep = ExpressionProcessorFactory.createExpressionProcessor(eow);

    // Run expression with populated HashMap
    DateTime start = new DateTime();
    HashMap<String, String> result = ep.testEvaluateExpression(p);
    DateTime end = new DateTime();
    Duration dur = new Duration(start, end);
    PeriodFormatter yearsAndMonths =
        new PeriodFormatterBuilder()
            .printZeroAlways()
            .appendSecondsWithMillis()
            .appendSuffix(" second", " seconds")
            .toFormatter();
    yearsAndMonths.print(dur.toPeriod());

    // Run expression with empty HashMap to check rule validity, because
    // using illegal test values will cause invalidity
    HashMap<String, String> k = new HashMap<String, String>();
    HashMap<String, String> theResult = ep.testEvaluateExpression(k);
    ruleTest.getParameters().clear();
    for (Map.Entry<String, String> entry : result.entrySet()) {
      ParameterType parameterType = new ParameterType();
      parameterType.setKey(entry.getKey());
      parameterType.setValue(entry.getValue());
      ruleTest.getParameters().add(parameterType);
    }
    // if (theResult.get("ruleValidation").equals("rule_valid") &&
    // result.get("ruleValidation").equals("rule_invalid")) {
    // result.put("ruleValidation", "rule_valid");
    // result.put("ruleEvaluatesTo", resword.getString("test_rules_rule_fail") + " " +
    // result.get("ruleValidationFailMessage"));
    // result.remove("ruleValidationFailMessage");
    // }
    // Put on screen
    // request.setAttribute("duration", yearsAndMonths.print(dur.toPeriod()));
    RulesTestMessagesType messageType = new RulesTestMessagesType();
    messageType.setKey("duration");
    messageType.setValue(yearsAndMonths.print(dur.toPeriod()));
    ruleTest.getRulesTestMessages().add(messageType);

    return ruleTest;
  }
  /*
   * 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;
  }
  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 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);
      }
    }
  }
  @Override
  public void processRequest() throws Exception {
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    String name = request.getParameter("name");
    String studyIdString = request.getParameter("studyId");
    if (StringUtil.isBlank(name) || StringUtil.isBlank(studyIdString)) {
      addPageMessage(respage.getString("please_choose_a_user_to_set_role_for"));
      forwardPage(Page.LIST_USER_IN_STUDY_SERVLET);
    } else {
      String action = request.getParameter("action");
      FormProcessor fp = new FormProcessor(request);
      UserAccountBean user = (UserAccountBean) udao.findByUserName(name);
      StudyBean userStudy = (StudyBean) sdao.findByPK(fp.getInt("studyId"));
      if ("confirm".equalsIgnoreCase(action)) {
        int studyId = Integer.valueOf(studyIdString.trim()).intValue();

        request.setAttribute("user", user);

        StudyUserRoleBean uRole = udao.findRoleByUserNameAndStudyId(name, studyId);
        uRole.setStudyName(userStudy.getName());
        request.setAttribute("uRole", uRole);

        ArrayList roles = Role.toArrayList();
        roles.remove(Role.ADMIN); // admin is not a user role, only used for tomcat

        StudyBean studyBean = (StudyBean) sdao.findByPK(uRole.getStudyId());

        if (currentStudy.getParentStudyId() > 0) {
          roles.remove(Role.COORDINATOR);
          roles.remove(Role.STUDYDIRECTOR);
        } else if (studyBean.getParentStudyId() > 0) {
          roles.remove(Role.COORDINATOR);
          roles.remove(Role.STUDYDIRECTOR);
          // TODO: redo this fix
          Role r = Role.RESEARCHASSISTANT;
          r.setDescription("site_Data_Entry_Person");
          roles.remove(Role.RESEARCHASSISTANT);
          roles.add(r);
          Role ri = Role.INVESTIGATOR;
          ri.setDescription("site_investigator");
          roles.remove(Role.INVESTIGATOR);

          roles.add(ri);
        }
        request.setAttribute("roles", roles);

        forwardPage(Page.SET_USER_ROLE_IN_STUDY);
      } else {
        // set role

        String userName = fp.getString("name");
        int studyId = fp.getInt("studyId");
        int roleId = fp.getInt("roleId");
        StudyUserRoleBean sur = new StudyUserRoleBean();
        sur.setName(userName);
        sur.setRole(Role.get(roleId));
        sur.setStudyId(studyId);
        sur.setStudyName(userStudy.getName());
        sur.setStatus(Status.AVAILABLE);
        sur.setUpdater(ub);
        sur.setUpdatedDate(new Date());
        udao.updateStudyUserRole(sur, userName);
        addPageMessage(sendEmail(user, sur));
        forwardPage(Page.LIST_USER_IN_STUDY_SERVLET);
      }
    }
  }
 private StudyBean getStudy(String oid) {
   sdao = new StudyDAO(dataSource);
   StudyBean studyBean = (StudyBean) sdao.findByOid(oid);
   return studyBean;
 }
  @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();
    }
  }
  /**
   * @api {get} /rest2/openrosa/:studyOID/formList Get Form List
   * @apiName getFormList
   * @apiPermission admin
   * @apiVersion 1.0.0
   * @apiParam {String} studyOID Study Oid.
   * @apiGroup Form
   * @apiDescription Retrieves a listing of the available OpenClinica forms.
   * @apiParamExample {json} Request-Example: { "studyOid": "S_SAMPLTE", }
   * @apiSuccessExample {xml} Success-Response: HTTP/1.1 200 OK { <xforms
   *     xmlns="http://openrosa.org/xforms/xformsList"> <xform> <formID>F_FIRSTFORM_1</formID>
   *     <name>First Form</name> <majorMinorVersion>1</majorMinorVersion> <version>1</version>
   *     <hash>8678370cd92814d4e3216d58d821403f</hash>
   *     <downloadUrl>http://oc1.openclinica.com/OpenClinica-web/rest2/openrosa/S_SAMPLTE/formXml?
   *     formId=F_FIRSTFORM_1</downloadUrl> </xform> <xform> <formID>F_SECONDFORM_1</formID>
   *     <name>Second Form</name> <majorMinorVersion>1</majorMinorVersion> <version>1</version>
   *     <hash>7ee60d1c6516b730bbe9bdbd7cad942f</hash>
   *     <downloadUrl>http://oc1.openclinica.com/OpenClinica-web/rest2/openrosa/S_SAMPLTE/formXml?
   *     formId=F_SECONDFORM_1</downloadUrl> </xform> </xforms>
   */
  @GET
  @Path("/{studyOID}/formList")
  @Produces(MediaType.TEXT_XML)
  public String getFormList(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response,
      @PathParam("studyOID") String studyOID,
      @QueryParam("formID") String crfOID,
      @RequestHeader("Authorization") String authorization,
      @Context ServletContext context)
      throws Exception {
    if (!mayProceedPreview(studyOID)) return null;

    StudyDAO sdao = new StudyDAO(getDataSource());
    StudyBean study = sdao.findByOid(studyOID);

    CRFDAO cdao = new CRFDAO(getDataSource());
    Collection<CRFBean> crfs = cdao.findAll();

    CRFVersionDAO cVersionDao = new CRFVersionDAO(getDataSource());
    Collection<CRFVersionBean> crfVersions = cVersionDao.findAll();

    CrfVersionMediaDao mediaDao =
        (CrfVersionMediaDao)
            SpringServletAccess.getApplicationContext(context).getBean("crfVersionMediaDao");

    try {
      XFormList formList = new XFormList();
      for (CRFBean crf : crfs) {
        for (CRFVersionBean version : crfVersions) {
          if (version.getCrfId() == crf.getId()) {
            XForm form = new XForm(crf, version);
            // TODO: Need to generate hash based on contents of
            // XForm. Will be done in a later story.
            // TODO: For now all XForms get a date based hash to
            // trick Enketo into always downloading
            // TODO: them.
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            form.setHash(DigestUtils.md5Hex(String.valueOf(cal.getTimeInMillis())));

            String urlBase =
                getCoreResources().getDataInfo().getProperty("sysURL").split("/MainMenu")[0];
            form.setDownloadURL(
                urlBase + "/rest2/openrosa/" + studyOID + "/formXml?formId=" + version.getOid());

            List<CrfVersionMedia> mediaList = mediaDao.findByCrfVersionId(version.getId());
            if (mediaList != null && mediaList.size() > 0) {
              form.setManifestURL(
                  urlBase + "/rest2/openrosa/" + studyOID + "/manifest?formId=" + version.getOid());
            }
            formList.add(form);
          }
        }
      }

      // Create the XML formList using a Castor mapping file.
      XMLContext xmlContext = new XMLContext();
      Mapping mapping = xmlContext.createMapping();
      mapping.loadMapping(getCoreResources().getURL("openRosaFormListMapping.xml"));
      xmlContext.addMapping(mapping);

      Marshaller marshaller = xmlContext.createMarshaller();
      StringWriter writer = new StringWriter();
      marshaller.setWriter(writer);
      marshaller.marshal(formList);

      // Set response headers
      Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
      Date currentDate = new Date();
      cal.setTime(currentDate);
      SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz");
      format.setCalendar(cal);
      response.setHeader("Content-Type", "text/xml; charset=UTF-8");
      response.setHeader("Date", format.format(currentDate));
      response.setHeader("X-OpenRosa-Version", "1.0");
      return writer.toString();
    } catch (Exception e) {
      LOGGER.error(e.getMessage());
      LOGGER.error(ExceptionUtils.getStackTrace(e));
      return "<Error>" + e.getMessage() + "</Error>";
    }
  }
  @RequestMapping(value = "/studies/{study}/metadata", method = RequestMethod.GET)
  public ModelAndView studyMetadata(
      Model model,
      HttpSession session,
      @PathVariable("study") String studyOid,
      HttpServletResponse response)
      throws Exception {
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    StudyBean currentStudy = (StudyBean) session.getAttribute("study");
    UserAccountBean userAccount = (UserAccountBean) session.getAttribute("userBean");

    UserAccountDAO userAccountDao = new UserAccountDAO(dataSource);
    userAccount = (UserAccountBean) userAccountDao.findByUserName("root");

    StudyDAO studyDao = new StudyDAO(dataSource);
    currentStudy = studyDao.findByOid(studyOid);

    MetaDataCollector mdc = new MetaDataCollector(dataSource, currentStudy, getRuleSetRuleDao());
    AdminDataCollector adc = new AdminDataCollector(dataSource, currentStudy);
    // RulesDataCollector rdc = new RulesDataCollector(sm.getDataSource(),
    // currentStudy,getRuleSetRuleDao());
    MetaDataCollector.setTextLength(200);

    ODMBean odmb = mdc.getODMBean();
    odmb.setSchemaLocation("http://www.cdisc.org/ns/odm/v1.3 OpenClinica-ODM1-3-0-OC2-0.xsd");
    ArrayList<String> xmlnsList = new ArrayList<String>();
    xmlnsList.add("xmlns=\"http://www.cdisc.org/ns/odm/v1.3\"");
    // xmlnsList.add("xmlns:OpenClinica=\"http://www.openclinica.org/ns/openclinica_odm/v1.3\"");
    xmlnsList.add("xmlns:OpenClinica=\"http://www.openclinica.org/ns/odm_ext_v130/v3.1\"");
    xmlnsList.add("xmlns:OpenClinicaRules=\"http://www.openclinica.org/ns/rules/v3.1\"");
    odmb.setXmlnsList(xmlnsList);
    odmb.setODMVersion("oc1.3");
    mdc.setODMBean(odmb);
    adc.setOdmbean(odmb);
    // rdc.setOdmbean(odmb);

    mdc.collectFileData();
    MetaDataReportBean metaReport = new MetaDataReportBean(mdc.getOdmStudyMap(), coreResources);
    metaReport.setODMVersion("oc1.3");
    metaReport.setOdmBean(mdc.getODMBean());
    metaReport.createChunkedOdmXml(Boolean.FALSE);

    adc.collectFileData();
    AdminDataReportBean adminReport = new AdminDataReportBean(adc.getOdmAdminDataMap());
    adminReport.setODMVersion("oc1.3");
    adminReport.setOdmBean(mdc.getODMBean());
    adminReport.createChunkedOdmXml(Boolean.FALSE);

    // rdc.collectFileData();
    // RulesDataReportBean rulesReport = new
    // RulesDataReportBean(rdc.getOdmRulesDataMap(),getCoreResources());
    // rulesReport.setODMVersion("oc1.3");
    // rulesReport.setOdmBean(mdc.getODMBean());
    // rulesReport.createChunkedOdmXml(Boolean.FALSE);

    FullReportBean report = new FullReportBean();
    report.setAdminDataMap(adc.getOdmAdminDataMap());
    report.setOdmStudyMap(mdc.getOdmStudyMap());
    report.setCoreResources(coreResources);
    // report.setRulesDataMap(rdc.getOdmRulesDataMap());
    report.setOdmBean(mdc.getODMBean());
    report.setODMVersion("oc1.3");
    report.createStudyMetaOdmXml(Boolean.FALSE);

    response.setContentType("application/xml");
    PrintWriter out = response.getWriter();
    out.print(report.getXmlOutput().toString().trim());

    return null;
  }
  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);
    }
  }
  protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);

    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    addEntityList(
        "studies",
        sdao.findAll(),
        "A user cannot be created, because there is no study to set as an active study for the user.",
        Page.ADMIN_SYSTEM);
    addEntityList(
        "roles",
        getRoles(),
        "A user cannot be created, because there are no roles to set as a role within the active study for the user.",
        Page.ADMIN_SYSTEM);

    ArrayList types = UserType.toArrayList();
    types.remove(UserType.INVALID);
    if (!ub.isTechAdmin()) {
      types.remove(UserType.TECHADMIN);
    }
    addEntityList(
        "types",
        types,
        "A user cannot be created, because there are no user types within the active study for the user.",
        Page.ADMIN_SYSTEM);

    if (!fp.isSubmitted()) {
      forwardPage(Page.CREATE_ACCOUNT);
    } else {
      UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
      Validator v = new Validator(request);

      // username must not be blank,
      // must be in the format specified by Validator.USERNAME,
      // and must be unique
      v.addValidation(INPUT_USERNAME, Validator.NO_BLANKS);
      v.addValidation(
          INPUT_USERNAME,
          Validator.LENGTH_NUMERIC_COMPARISON,
          NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
          64);
      v.addValidation(INPUT_USERNAME, Validator.IS_A_USERNAME);

      v.addValidation(INPUT_USERNAME, Validator.USERNAME_UNIQUE, udao);

      v.addValidation(INPUT_FIRST_NAME, Validator.NO_BLANKS);
      v.addValidation(INPUT_LAST_NAME, Validator.NO_BLANKS);
      v.addValidation(
          INPUT_FIRST_NAME,
          Validator.LENGTH_NUMERIC_COMPARISON,
          NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
          50);
      v.addValidation(
          INPUT_LAST_NAME,
          Validator.LENGTH_NUMERIC_COMPARISON,
          NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
          50);

      v.addValidation(INPUT_EMAIL, Validator.NO_BLANKS);
      v.addValidation(
          INPUT_EMAIL,
          Validator.LENGTH_NUMERIC_COMPARISON,
          NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
          120);
      v.addValidation(INPUT_EMAIL, Validator.IS_A_EMAIL);

      v.addValidation(INPUT_INSTITUTION, Validator.NO_BLANKS);
      v.addValidation(
          INPUT_INSTITUTION,
          Validator.LENGTH_NUMERIC_COMPARISON,
          NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
          255);

      v.addValidation(INPUT_STUDY, Validator.ENTITY_EXISTS, sdao);
      v.addValidation(INPUT_ROLE, Validator.IS_VALID_TERM, TermType.ROLE);

      HashMap errors = v.validate();

      if (errors.isEmpty()) {
        UserAccountBean createdUserAccountBean = new UserAccountBean();
        createdUserAccountBean.setName(fp.getString(INPUT_USERNAME));
        createdUserAccountBean.setFirstName(fp.getString(INPUT_FIRST_NAME));
        createdUserAccountBean.setLastName(fp.getString(INPUT_LAST_NAME));
        createdUserAccountBean.setEmail(fp.getString(INPUT_EMAIL));
        createdUserAccountBean.setInstitutionalAffiliation(fp.getString(INPUT_INSTITUTION));

        SecurityManager secm = SecurityManager.getInstance();
        String password = secm.genPassword();
        String passwordHash = secm.encrytPassword(password);

        createdUserAccountBean.setPasswd(passwordHash);

        createdUserAccountBean.setPasswdTimestamp(null);
        createdUserAccountBean.setLastVisitDate(null);

        createdUserAccountBean.setStatus(Status.AVAILABLE);
        createdUserAccountBean.setPasswdChallengeQuestion("");
        createdUserAccountBean.setPasswdChallengeAnswer("");
        createdUserAccountBean.setPhone("");
        createdUserAccountBean.setOwner(ub);

        int studyId = fp.getInt(INPUT_STUDY);
        Role r = Role.get(fp.getInt(INPUT_ROLE));
        createdUserAccountBean = addActiveStudyRole(createdUserAccountBean, studyId, r);
        UserType type = UserType.get(fp.getInt("type"));
        logger.warning("*** found type: " + fp.getInt("type"));
        logger.warning("*** setting type: " + type.getDescription());
        createdUserAccountBean.addUserType(type);
        createdUserAccountBean = (UserAccountBean) udao.create(createdUserAccountBean);
        String displayPwd = fp.getString(INPUT_DISPLAY_PWD);

        if (createdUserAccountBean.isActive()) {
          addPageMessage(
              "The user account \""
                  + createdUserAccountBean.getName()
                  + "\" was created successfully. ");
          if ("no".equalsIgnoreCase(displayPwd)) {
            try {
              sendNewAccountEmail(createdUserAccountBean, password);
            } catch (Exception e) {
              addPageMessage(
                  "There was an error sending the account-creating email.  Please contact the user directly regarding account creation.  You may reset the user's password by editing the user's account.");
            }
          } else {
            addPageMessage(
                "User Password: "******". Please write down the password and provide it directly to the user.");
          }
        } else {
          addPageMessage(
              "The user account \""
                  + createdUserAccountBean.getName()
                  + "\" could not be created due to a database error.");
        }
        if (createdUserAccountBean.isActive()) {
          request.setAttribute(
              ViewUserAccountServlet.ARG_USER_ID,
              new Integer(createdUserAccountBean.getId()).toString());
          forwardPage(Page.VIEW_USER_ACCOUNT_SERVLET);
        } else {
          forwardPage(Page.LIST_USER_ACCOUNTS_SERVLET);
        }
      } else {
        String textFields[] = {
          INPUT_USERNAME,
          INPUT_FIRST_NAME,
          INPUT_LAST_NAME,
          INPUT_EMAIL,
          INPUT_INSTITUTION,
          INPUT_DISPLAY_PWD
        };
        fp.setCurrentStringValuesAsPreset(textFields);

        String ddlbFields[] = {INPUT_STUDY, INPUT_ROLE, INPUT_TYPE};
        fp.setCurrentIntValuesAsPreset(ddlbFields);

        HashMap presetValues = fp.getPresetValues();
        setPresetValues(presetValues);

        setInputMessages(errors);
        addPageMessage("There were some errors in your submission.  See below for details.");

        forwardPage(Page.CREATE_ACCOUNT);
      }
    }
  }
  @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 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");
  }
  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;
  }
  /** 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);
  }
 private StudyBean getStudy(Integer id) {
   sdao = new StudyDAO(dataSource);
   StudyBean studyBean = (StudyBean) sdao.findByPK(id);
   return studyBean;
 }