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;
  }
  private UserAccountBean createUserAccount(
      UserAccountBean rootUserAccount, StudyBean studyBean, StudySubjectBean studySubjectBean)
      throws Exception {

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

    UserAccountDAO udao = new UserAccountDAO(dataSource);
    createdUserAccountBean = (UserAccountBean) udao.create(createdUserAccountBean);
    // authoritiesDao.saveOrUpdate(new AuthoritiesBean(createdUserAccountBean.getName()));
    return createdUserAccountBean;
  }
 private UserAccountBean getUserAccount() {
   Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
   String username = null;
   if (principal instanceof UserDetails) {
     username = ((UserDetails) principal).getUsername();
   } else {
     username = principal.toString();
   }
   UserAccountDAO userAccountDao = new UserAccountDAO(dataSource);
   return (UserAccountBean) userAccountDao.findByUserName(username);
 }
  @Override
  protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);

    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
    int noteId = fp.getInt(NOTE_ID, true);

    DiscrepancyNoteBean note = (DiscrepancyNoteBean) dndao.findByPK(noteId);

    String entityType = note.getEntityType();
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());

    ArrayList notes = dndao.findAllEntityByPK(note.getEntityType(), noteId);

    Date lastUpdatedDate = note.getCreatedDate();
    UserAccountBean lastUpdator = (UserAccountBean) udao.findByPK(note.getOwnerId());

    for (int i = 0; i < notes.size(); i++) {
      DiscrepancyNoteBean n = (DiscrepancyNoteBean) notes.get(i);
      int pId = n.getParentDnId();
      if (pId == 0) {
        note = n;
        note.setLastUpdator((UserAccountBean) udao.findByPK(n.getOwnerId()));
        note.setLastDateUpdated(n.getCreatedDate());
        lastUpdatedDate = note.getLastDateUpdated();
        lastUpdator = note.getLastUpdator();
      }
    }

    for (int i = 0; i < notes.size(); i++) {
      DiscrepancyNoteBean n = (DiscrepancyNoteBean) notes.get(i);
      int pId = n.getParentDnId();
      if (pId > 0) {
        note.getChildren().add(n);
        if (!n.getCreatedDate().before(lastUpdatedDate)) {
          lastUpdatedDate = n.getCreatedDate();
          lastUpdator = (UserAccountBean) udao.findByPK(n.getOwnerId());
          note.setLastUpdator(lastUpdator);
          note.setLastDateUpdated(lastUpdatedDate);
          note.setResolutionStatusId(n.getResolutionStatusId());
          note.setResStatus(ResolutionStatus.get(n.getResolutionStatusId()));
        }
      }
    }
    note.setNumChildren(note.getChildren().size());
    note.setDisType(DiscrepancyNoteType.get(note.getDiscrepancyNoteTypeId()));
    logger.info("Just set Note: " + note.getCrfName() + " column " + note.getColumn());
    request.setAttribute(DIS_NOTE, note);
    forwardPage(Page.VIEW_SINGLE_NOTE);
  }
  /*
   * (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);
  }
  @Override
  protected void processRequest() throws Exception {
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());

    FormProcessor fp = new FormProcessor(request);
    int userId = fp.getInt(ARG_USERID);

    UserAccountBean u = (UserAccountBean) udao.findByPK(userId);

    String message;
    if (!u.isActive() || u.getAccountNonLocked()) {
      message = respage.getString("the_specified_user_not_exits");
    } else {
      u.setUpdater(ub);

      SecurityManager sm =
          ((SecurityManager)
              SpringServletAccess.getApplicationContext(context).getBean("securityManager"));
      String password = sm.genPassword();
      String passwordHash = sm.encrytPassword(password, getUserDetails());

      u.setPasswd(passwordHash);
      u.setPasswdTimestamp(null);
      u.setAccountNonLocked(Boolean.TRUE);
      u.setStatus(Status.AVAILABLE);
      u.setLockCounter(0);

      udao.update(u);

      if (udao.isQuerySuccessful()) {
        message = respage.getString("the_user_has_been_unlocked");

        try {
          sendRestoreEmail(u, password);
        } catch (Exception e) {
          message += respage.getString("however_was_error_sending_user_email_regarding");
        }
      } else {
        message = respage.getString("the_user_could_not_be_deleted_due_database_error");
      }
    }

    addPageMessage(message);
    forwardPage(Page.LIST_USER_ACCOUNTS_SERVLET);
  }
  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

    System.out.println("Oh look at you triggering API calls i see !!!!!!");

    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
      StringTokenizer st = new StringTokenizer(authHeader);
      if (st.hasMoreTokens()) {
        String basic = st.nextToken();

        if (basic.equalsIgnoreCase("Basic")) {
          try {
            String credentials =
                new String(Base64.decodeBase64(st.nextToken().getBytes()), "UTF-8");
            int p = credentials.indexOf(":");
            if (p != -1) {
              String _username = credentials.substring(0, p).trim();
              String _password = credentials.substring(p + 1).trim();

              UserAccountDAO userAccountDAO = new UserAccountDAO(dataSource);
              UserAccountBean ub = (UserAccountBean) userAccountDAO.findByApiKey(_username);
              if (ub.getId() != 0) {
                request.getSession().setAttribute("userBean", ub);
              } else {
                unauthorized(response, "Bad credentials");
              }
            } else {
              unauthorized(response, "Invalid authentication token");
            }
          } catch (UnsupportedEncodingException e) {
            throw new Error("Couldn't retrieve authentication", e);
          }
        }
      }
    } else {
      unauthorized(response);
    }

    filterChain.doFilter(request, response);
  }
  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);
      }
    }
  }
  protected void processRequest() throws Exception {
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());

    FormProcessor fp = new FormProcessor(request);
    int userId = fp.getInt(ARG_USERID);
    int action = fp.getInt(ARG_ACTION);

    UserAccountBean u = (UserAccountBean) udao.findByPK(userId);

    String message;
    if (!u.isActive()) {
      message = respage.getString("the_specified_user_not_exits");
    } else if (!EntityAction.contains(action)) {
      message = respage.getString("the_specified_action_on_the_user_is_invalid");
    } else if (!EntityAction.get(action).equals(EntityAction.DELETE)
        && !EntityAction.get(action).equals(EntityAction.RESTORE)) {
      message = respage.getString("the_specified_action_is_not_allowed");
    } else {
      EntityAction desiredAction = EntityAction.get(action);
      u.setUpdater(ub);

      if (desiredAction.equals(EntityAction.DELETE)) {
        udao.delete(u);

        if (udao.isQuerySuccessful()) {
          message = respage.getString("the_user_has_been_deleted");
          // YW 07-31-2007 << for feature that deletion doesn't need email the deleted user.
          /*
          //YW 07-26-2007 << catch exception (eg. timeout) and inform users.
          try {
          	sendDeleteEmail(u);
          } catch (Exception e) {
          	message += "  However, there has been an error sending the user an email regarding this deletion.";
          }
          */
          // YW >>
        } else {
          message = respage.getString("the_user_could_not_be_deleted_due_database_error");
        }
      } else {
        SecurityManager sm = SecurityManager.getInstance();
        String password = sm.genPassword();
        String passwordHash = sm.encrytPassword(password);

        u.setPasswd(passwordHash);
        u.setPasswdTimestamp(null);

        udao.restore(u);

        if (udao.isQuerySuccessful()) {
          message = respage.getString("the_user_has_been_restored");

          try {
            sendRestoreEmail(u, password);
          } catch (Exception e) {
            message += respage.getString("however_was_error_sending_user_email_regarding");
          }
        } else {
          message = respage.getString("the_user_could_not_be_deleted_due_database_error");
        }
      }
    }

    addPageMessage(message);
    forwardPage(Page.LIST_USER_ACCOUNTS_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
  protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    // changes to this servlet, we now look at group name too, tbh 05/2009
    String triggerName = fp.getString("tname");
    String gName = fp.getString("gname");
    String groupName = "";
    if (gName.equals("") || gName.equals("0")) {
      groupName = TRIGGER_GROUP;
    } else { // if (gName.equals("1")) {
      groupName = TRIGGER_IMPORT_GROUP;
    }
    // << tbh 09/03/2009 #4143
    scheduler = getScheduler();
    Trigger trigger = scheduler.getTrigger(triggerName.trim(), groupName);

    // trigger bean is a wrapper for the trigger, to serve as a link btw
    // quartz classes and oc classes
    // is it really necessary? DRY

    if (trigger == null) {
      System.out.println("*** reset trigger group name");
      groupName = TRIGGER_GROUP;
      trigger = scheduler.getTrigger(triggerName.trim(), groupName);
    }
    // << tbh 09/03/2009 #4143
    // above is a hack, if we add more trigger groups this will have
    // to be redone
    System.out.println("found trigger name: " + triggerName);
    System.out.println("found group name: " + groupName);
    // System.out.println("found trigger on the other side, full name: " +
    // trigger.getFullName());
    TriggerBean triggerBean = new TriggerBean();
    JobDataMap dataMap = new JobDataMap();
    AuditEventDAO auditEventDAO = new AuditEventDAO(sm.getDataSource());

    try {
      triggerBean.setFullName(trigger.getName());
      triggerBean.setPreviousDate(trigger.getPreviousFireTime());
      triggerBean.setNextDate(trigger.getNextFireTime());
      // >> set active here, tbh 10/08/2009
      if (scheduler.getTriggerState(triggerName, groupName) == Trigger.STATE_PAUSED) {
        triggerBean.setActive(false);
        System.out.println("setting active to false for trigger: " + trigger.getName());
      } else {
        triggerBean.setActive(true);
        System.out.println("setting active to TRUE for trigger: " + trigger.getName());
      }
      // <<
      if (trigger.getDescription() != null) {
        triggerBean.setDescription(trigger.getDescription());
      }
      if (trigger.getJobDataMap().size() > 0) {
        dataMap = trigger.getJobDataMap();
        String contactEmail = dataMap.getString(ExampleSpringJob.EMAIL);
        System.out.println("found email: " + contactEmail);
        // String datasetId =
        // dataMap.getString(ExampleSpringJob.DATASET_ID);
        // int dsId = new Integer(datasetId).intValue();
        if (gName.equals("") || gName.equals("0")) {
          String tab = dataMap.getString(ExampleSpringJob.TAB);
          String cdisc = dataMap.getString(ExampleSpringJob.CDISC);
          String spss = dataMap.getString(ExampleSpringJob.SPSS);
          String periodToRun = dataMap.getString(ExampleSpringJob.PERIOD);
          // int userId = new Integer(userAcctId).intValue();
          int dsId = dataMap.getInt(ExampleSpringJob.DATASET_ID);
          triggerBean.setCdisc(cdisc);
          triggerBean.setSpss(spss);
          triggerBean.setTab(tab);
          triggerBean.setPeriodToRun(periodToRun);
          DatasetDAO datasetDAO = new DatasetDAO(sm.getDataSource());
          DatasetBean dataset = (DatasetBean) datasetDAO.findByPK(dsId);
          triggerBean.setDataset(dataset);
        }
        int userId = dataMap.getInt(ExampleSpringJob.USER_ID);
        // need to set information, extract bean, user account bean

        UserAccountDAO userAccountDAO = new UserAccountDAO(sm.getDataSource());

        triggerBean.setContactEmail(contactEmail);

        UserAccountBean userAccount = (UserAccountBean) userAccountDAO.findByPK(userId);

        triggerBean.setUserAccount(userAccount);

        ArrayList<AuditEventBean> triggerLogs =
            auditEventDAO.findAllByAuditTable(trigger.getName());

        // set the table for the audit event beans here

        ArrayList allRows = AuditEventRow.generateRowsFromBeans(triggerLogs);

        EntityBeanTable table = fp.getEntityBeanTable();
        String[] columns = {
          resword.getString("date_and_time"),
          resword.getString("action_message"),
          resword.getString("entity_operation"),
          // resword.getString("study_site"),
          // resword.getString("study_subject_ID"),
          resword.getString("changes_and_additions"),
          resword.getString("actions")
        };

        table.setColumns(new ArrayList(Arrays.asList(columns)));
        table.setAscendingSort(false);
        table.hideColumnLink(1);
        table.hideColumnLink(3);
        table.hideColumnLink(4);

        table.setQuery("ViewSingleJob?tname=" + triggerName + "&gname=" + gName, new HashMap());
        table.setRows(allRows);
        table.computeDisplay();

        request.setAttribute("table", table);
      }

    } catch (NullPointerException e) {
      // TODO Auto-generated catch block
      System.out.println(" found NPE " + e.getMessage());
      e.printStackTrace();
    }
    // need to show the extract for which this runs, which files, etc
    // in other words the job data map

    request.setAttribute("triggerBean", triggerBean);

    request.setAttribute("groupName", groupName);

    forwardPage(Page.VIEW_SINGLE_JOB);
  }
  @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();
    }
  }
  @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;
  }
  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 {
    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);
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.akaza.openclinica.control.core.SecureController#processRequest()
   */
  protected void processRequest() throws Exception {
    // find last 5 modifed sites
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    // ArrayList sites = (ArrayList) sdao.findAllByParentAndLimit(currentStudy.getId(),true);
    ArrayList allSites = (ArrayList) sdao.findAllByParent(currentStudy.getId());
    ArrayList sites = new ArrayList();
    for (int i = 0; i < allSites.size(); i++) {
      sites.add(allSites.get(i));
      if (i == 5) {
        break;
      }
    }
    request.setAttribute("sites", sites);
    request.setAttribute("sitesCount", new Integer(sites.size()));
    request.setAttribute("allSitesCount", new Integer(allSites.size()));

    StudyEventDefinitionDAO edao = new StudyEventDefinitionDAO(sm.getDataSource());
    ArrayList seds = (ArrayList) edao.findAllByStudyAndLimit(currentStudy.getId());
    ArrayList allSeds = (ArrayList) edao.findAllByStudy(currentStudy);
    request.setAttribute("seds", seds);
    request.setAttribute("sedsCount", new Integer(seds.size()));
    request.setAttribute("allSedsCount", new Integer(allSeds.size()));

    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    ArrayList users = (ArrayList) udao.findAllUsersByStudyIdAndLimit(currentStudy.getId(), true);
    ArrayList allUsers = (ArrayList) udao.findAllUsersByStudy(currentStudy.getId());
    request.setAttribute("users", users);
    request.setAttribute("usersCount", new Integer(users.size()));
    request.setAttribute("allUsersCount", new Integer(allUsers.size()));

    StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
    // ArrayList subjects = (ArrayList) ssdao.findAllByStudyIdAndLimit(currentStudy.getId(),true);
    ArrayList allSubjects = (ArrayList) ssdao.findAllByStudyId(currentStudy.getId());
    ArrayList subjects = new ArrayList();
    for (int i = 0; i < allSubjects.size(); i++) {
      subjects.add(allSubjects.get(i));
      if (i == 5) {
        break;
      }
    }
    request.setAttribute("subs", subjects);
    request.setAttribute("subsCount", new Integer(subjects.size()));
    request.setAttribute("allSubsCount", new Integer(allSubjects.size()));

    // added tbh, 9-21-2005
    AuditEventDAO aedao = new AuditEventDAO(sm.getDataSource());
    // ArrayList audits = (ArrayList) aedao.findAllByStudyIdAndLimit(currentStudy.getId());
    // request.setAttribute("audits", audits);
    resetPanel();

    if (allSubjects.size() > 0) {
      setToPanel("Subjects", new Integer(allSubjects.size()).toString());
    }
    if (allUsers.size() > 0) {
      setToPanel("Users", new Integer(allUsers.size()).toString());
    }
    if (allSites.size() > 0) {
      setToPanel("Sites", new Integer(allSites.size()).toString());
    }
    if (allSeds.size() > 0) {
      setToPanel("Event Definitions", new Integer(allSeds.size()).toString());
    }

    forwardPage(Page.MANAGE_STUDY);
  }