Exemplo n.º 1
0
  public HashMap validateImportJobForm(
      FormProcessor fp, HttpServletRequest request, String[] triggerNames, String properName) {
    Validator v = new Validator(request);
    v.addValidation(JOB_NAME, Validator.NO_BLANKS);
    // need to be unique too
    v.addValidation(JOB_DESC, Validator.NO_BLANKS);
    if (!"".equals(fp.getString(EMAIL))) {
      v.addValidation(EMAIL, Validator.IS_A_EMAIL);
    }
    // << tbh we are now allowing email to be optional
    // v.addValidation(PERIOD, Validator.NO_BLANKS);
    // v.addValidation(DIRECTORY, Validator.NO_BLANKS);
    // v.addValidation(DATE_START_JOB + "Date", Validator.IS_A_DATE);

    // TODO job names will have to be unique, tbh

    String hours = fp.getString("hours");
    String minutes = fp.getString("minutes");

    HashMap errors = v.validate();
    if ((hours.equals("0")) && (minutes.equals("0"))) {
      // System.out.println("got in the ERROR LOOP");
      // throw an error here, at least one should be greater than zero
      // errors.put(TAB, "Error Message - Pick one of the below");
      v.addError(errors, "hours", "At least one of the following should be greater than zero.");
    }
    for (String triggerName : triggerNames) {
      if (triggerName.equals(fp.getString(JOB_NAME)) && (!triggerName.equals(properName))) {
        v.addError(
            errors, JOB_NAME, "A job with that name already exists.  Please pick another name.");
      }
    }
    return errors;
  }
  private void confirmStudy6() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    Validator v = new Validator(request);
    v.addValidation(
        "medlineIdentifier",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "url",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "urlDescription",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);

    errors = v.validate();

    StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");
    newStudy.setMedlineIdentifier(fp.getString("medlineIdentifier"));
    newStudy.setResultsReference(fp.getBoolean("resultsReference"));
    newStudy.setUrl(fp.getString("url"));
    newStudy.setUrlDescription(fp.getString("urlDescription"));
    session.setAttribute("newStudy", newStudy);
    // request.setAttribute("interventions",session.getAttribute("interventions"));
    if (errors.isEmpty()) {
      forwardPage(Page.UPDATE_STUDY8);
    } else {
      request.setAttribute("formMessages", errors);
      forwardPage(Page.UPDATE_STUDY7);
    }
  }
  @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);
        }
      }
    }
  }
  @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);
  }
  /**
   * Updates the study bean with inputs from second section
   *
   * @param request
   * @return true if study type is Interventional, otherwise false
   */
  private boolean updateStudy2() {
    FormProcessor fp = new FormProcessor(request);
    StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");
    // this is not fully supported yet, because the system will not handle
    // studies which are pending
    // or private...
    newStudy.setStatus(Status.get(fp.getInt("statusId")));

    newStudy.setProtocolDateVerification(fp.getDate(INPUT_VER_DATE));

    newStudy.setDatePlannedStart(fp.getDate(INPUT_START_DATE));

    if (StringUtil.isBlank(fp.getString(INPUT_END_DATE))) {
      newStudy.setDatePlannedEnd(null);
    } else {
      newStudy.setDatePlannedEnd(fp.getDate(INPUT_END_DATE));
    }

    newStudy.setPhase(fp.getString("phase"));

    if (fp.getInt("genetic") == 1) {
      newStudy.setGenetic(true);
    } else {
      newStudy.setGenetic(false);
    }

    session.setAttribute("newStudy", newStudy);

    String interventional = resadmin.getString("interventional");
    return interventional.equalsIgnoreCase(newStudy.getProtocolType());
  }
  /**
   * Constructs study bean from request-first section
   *
   * @param request
   * @return
   */
  private StudyBean createStudyBean() {
    FormProcessor fp = new FormProcessor(request);
    StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");
    newStudy.setName(fp.getString("name"));
    newStudy.setOfficialTitle(fp.getString("officialTitle"));
    newStudy.setIdentifier(fp.getString("uniqueProId"));
    newStudy.setSecondaryIdentifier(fp.getString("secondProId"));
    newStudy.setPrincipalInvestigator(fp.getString("prinInvestigator"));

    newStudy.setSummary(fp.getString("description"));
    newStudy.setProtocolDescription(fp.getString("protocolDescription"));

    newStudy.setSponsor(fp.getString("sponsor"));
    newStudy.setCollaborators(fp.getString("collaborators"));

    return newStudy;
  }
  /**
   * Confirms the third input block of study info
   *
   * @throws Exception
   */
  private void confirmStudy3(boolean isInterventional) throws Exception {
    Validator v = new Validator(request);
    FormProcessor fp = new FormProcessor(request);

    v.addValidation("purpose", Validator.NO_BLANKS);
    for (int i = 0; i < 10; i++) {
      String type = fp.getString("interType" + i);
      String name = fp.getString("interName" + i);
      if (!StringUtil.isBlank(type) && StringUtil.isBlank(name)) {
        v.addValidation("interName", Validator.NO_BLANKS);
        request.setAttribute(
            "interventionError", respage.getString("name_cannot_be_blank_if_type"));
        break;
      }
      if (!StringUtil.isBlank(name) && StringUtil.isBlank(type)) {
        v.addValidation("interType", Validator.NO_BLANKS);
        request.setAttribute(
            "interventionError", respage.getString("name_cannot_be_blank_if_name"));
        break;
      }
    }

    errors = v.validate();
    updateStudy3(isInterventional);

    if (errors.isEmpty()) {
      logger.info("no errors");
      request.setAttribute("interventions", session.getAttribute("interventions"));
      forwardPage(Page.UPDATE_STUDY5);

    } else {
      logger.info("has validation errors");
      request.setAttribute("formMessages", errors);
      setMaps(isInterventional, (ArrayList) session.getAttribute("interventions"));
      if (isInterventional) {
        forwardPage(Page.UPDATE_STUDY3);
      } else {
        forwardPage(Page.UPDATE_STUDY4);
      }
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * org.akaza.openclinica.control.submit.DataEntryServlet#getServletPage()
  */
 @Override
 protected Page getServletPage(HttpServletRequest request) {
   FormProcessor fp = new FormProcessor(request);
   String tabId = fp.getString("tab", true);
   String sectionId = fp.getString(DataEntryServlet.INPUT_SECTION_ID, true);
   String eventCRFId = fp.getString(INPUT_EVENT_CRF_ID, true);
   if (StringUtil.isBlank(sectionId) || StringUtil.isBlank(tabId)) {
     return Page.DOUBLE_DATA_ENTRY_SERVLET;
   } else {
     Page target = Page.DOUBLE_DATA_ENTRY_SERVLET;
     target.setFileName(
         target.getFileName()
             + "?eventCRFId="
             + eventCRFId
             + "&sectionId="
             + sectionId
             + "&tab="
             + tabId);
     return target;
   }
 }
  /**
   * Validates the forth section of study and save it into study bean
   *
   * @param request
   * @param response
   * @throws Exception
   */
  private void confirmStudy4() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    Validator v = new Validator(request);
    v.addValidation(
        "conditions",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        500);
    v.addValidation(
        "keywords",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "eligibility",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        500);
    errors = v.validate();
    if (fp.getInt("expectedTotalEnrollment") <= 0) {
      Validator.addError(
          errors,
          "expectedTotalEnrollment",
          respage.getString("expected_total_enrollment_must_be_a_positive_number"));
    }

    StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");
    newStudy.setConditions(fp.getString("conditions"));
    newStudy.setKeywords(fp.getString("keywords"));
    newStudy.setEligibility(fp.getString("eligibility"));
    newStudy.setGender(fp.getString("gender"));

    newStudy.setAgeMax(fp.getString("ageMax"));
    newStudy.setAgeMin(fp.getString("ageMin"));
    newStudy.setHealthyVolunteerAccepted(fp.getBoolean("healthyVolunteerAccepted"));
    newStudy.setExpectedTotalEnrollment(fp.getInt("expectedTotalEnrollment"));
    session.setAttribute("newStudy", newStudy);
    request.setAttribute("facRecruitStatusMap", CreateStudyServlet.facRecruitStatusMap);
    if (errors.isEmpty()) {
      forwardPage(Page.UPDATE_STUDY6);
    } else {
      request.setAttribute("formMessages", errors);
      forwardPage(Page.UPDATE_STUDY5);
    }
  }
Exemplo n.º 10
0
  public SimpleTrigger generateImportTrigger(
      FormProcessor fp,
      UserAccountBean userAccount,
      StudyBean study,
      Date startDateTime,
      String locale) {

    String jobName = fp.getString(JOB_NAME);

    String email = fp.getString(EMAIL);
    String jobDesc = fp.getString(JOB_DESC);
    String directory = fp.getString(DIRECTORY);

    // what kinds of periods do we have? hourly, daily, weekly?
    long interval = 0;
    int hours = fp.getInt("hours");
    int minutes = fp.getInt("minutes");
    if (hours > 0) {
      long hoursInt = hours * 3600000;
      interval = interval + hoursInt;
    }
    if (minutes > 0) {
      long minutesInt = minutes * 60000;
      interval = interval + minutesInt;
    }
    SimpleTrigger trigger = new SimpleTrigger(jobName, IMPORT_TRIGGER, 64000, interval);
    trigger.setDescription(jobDesc);
    // set just the start date
    trigger.setStartTime(startDateTime);
    trigger.setName(jobName); // + datasetId);
    trigger.setGroup(IMPORT_TRIGGER); // + datasetId);
    trigger.setMisfireInstruction(
        SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT);
    // set job data map
    JobDataMap jobDataMap = new JobDataMap();

    jobDataMap.put(EMAIL, email);
    jobDataMap.put(USER_ID, userAccount.getId());
    jobDataMap.put(STUDY_NAME, study.getName());
    jobDataMap.put(STUDY_OID, study.getOid());
    jobDataMap.put(DIRECTORY, directory);
    jobDataMap.put(ExampleSpringJob.LOCALE, locale);
    jobDataMap.put("hours", hours);
    jobDataMap.put("minutes", minutes);

    trigger.setJobDataMap(jobDataMap);
    trigger.setVolatility(false);
    return trigger;
  }
Exemplo n.º 11
0
  public HashMap validateForm(
      FormProcessor fp, HttpServletRequest request, String[] triggerNames, String properName) {
    Validator v = new Validator(request);
    v.addValidation(JOB_NAME, Validator.NO_BLANKS);
    // need to be unique too
    v.addValidation(JOB_DESC, Validator.NO_BLANKS);
    v.addValidation(EMAIL, Validator.IS_A_EMAIL);
    v.addValidation(PERIOD, Validator.NO_BLANKS);
    v.addValidation(DATE_START_JOB + "Date", Validator.IS_A_DATE);
    // v.addValidation(DATE_START_JOB + "Date", new Date(), Validator.DATE_IS_AFTER_OR_EQUAL);
    // TODO job names will have to be unique, tbh

    String tab = fp.getString(TAB);
    String cdisc = fp.getString(CDISC);
    String cdisc12 = fp.getString(ExampleSpringJob.CDISC12);
    String cdisc13 = fp.getString(ExampleSpringJob.CDISC13);
    String cdisc13oc = fp.getString(ExampleSpringJob.CDISC13OC);
    String spss = fp.getString(SPSS);
    Date jobDate = fp.getDateTime(DATE_START_JOB);
    HashMap errors = v.validate();
    if ((tab == "")
        && (cdisc == "")
        && (spss == "")
        && (cdisc12 == "")
        && (cdisc13 == "")
        && (cdisc13oc == "")) {
      // throw an error here, at least one should work
      // errors.put(TAB, "Error Message - Pick one of the below");
      v.addError(errors, TAB, "Please pick at least one of the below.");
    }
    for (String triggerName : triggerNames) {
      if (triggerName.equals(fp.getString(JOB_NAME)) && (!triggerName.equals(properName))) {
        v.addError(
            errors, JOB_NAME, "A job with that name already exists.  Please pick another name.");
      }
    }
    if (jobDate.before(new Date())) {
      v.addError(
          errors, DATE_START_JOB + "Date", "This date needs to be later than the present time.");
    }
    return errors;
  }
  @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);
      }
    }
  }
  private void confirmWholeStudy() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    Validator v = new Validator(request);
    errors = v.validate();

    StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");
    newStudy.getStudyParameterConfig().setCollectDob(fp.getString("collectDob"));
    newStudy
        .getStudyParameterConfig()
        .setDiscrepancyManagement(fp.getString("discrepancyManagement"));
    newStudy.getStudyParameterConfig().setGenderRequired(fp.getString("genderRequired"));

    newStudy
        .getStudyParameterConfig()
        .setInterviewerNameRequired(fp.getString("interviewerNameRequired"));
    newStudy
        .getStudyParameterConfig()
        .setInterviewerNameDefault(fp.getString("interviewerNameDefault"));
    newStudy
        .getStudyParameterConfig()
        .setInterviewDateEditable(fp.getString("interviewDateEditable"));
    newStudy
        .getStudyParameterConfig()
        .setInterviewDateRequired(fp.getString("interviewDateRequired"));
    newStudy
        .getStudyParameterConfig()
        .setInterviewerNameEditable(fp.getString("interviewerNameEditable"));
    newStudy
        .getStudyParameterConfig()
        .setInterviewDateDefault(fp.getString("interviewDateDefault"));

    newStudy.getStudyParameterConfig().setSubjectIdGeneration(fp.getString("subjectIdGeneration"));
    newStudy
        .getStudyParameterConfig()
        .setSubjectPersonIdRequired(fp.getString("subjectPersonIdRequired"));
    newStudy
        .getStudyParameterConfig()
        .setSubjectIdPrefixSuffix(fp.getString("subjectIdPrefixSuffix"));

    newStudy.getStudyParameterConfig().setPersonIdShownOnCRF(fp.getString("personIdShownOnCRF"));

    session.setAttribute("newStudy", newStudy);

    if (errors.isEmpty()) {
      forwardPage(Page.STUDY_UPDATE_CONFIRM);

    } else {
      request.setAttribute("formMessages", errors);
      forwardPage(Page.UPDATE_STUDY8);
    }
  }
  /**
   * Validates the forth section of study and save it into study bean
   *
   * @param request
   * @param response
   * @throws Exception
   */
  private void confirmStudy5() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    Validator v = new Validator(request);
    if (!StringUtil.isBlank(fp.getString("facConEmail"))) {
      v.addValidation("facConEmail", Validator.IS_A_EMAIL);
    }
    v.addValidation(
        "facName",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facCity",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facState",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        20);
    v.addValidation(
        "facZip",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        64);
    v.addValidation(
        "facCountry",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        64);
    v.addValidation(
        "facConName",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facConDegree",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facConPhone",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "facConEmail",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    errors = v.validate();

    StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");

    newStudy.setFacilityCity(fp.getString("facCity"));
    newStudy.setFacilityContactDegree(fp.getString("facConDrgree"));
    newStudy.setFacilityName(fp.getString("facName"));
    newStudy.setFacilityContactEmail(fp.getString("facConEmail"));
    newStudy.setFacilityContactPhone(fp.getString("facConPhone"));
    newStudy.setFacilityContactName(fp.getString("facConName"));
    newStudy.setFacilityCountry(fp.getString("facCountry"));
    newStudy.setFacilityContactDegree(fp.getString("facConDegree"));
    // newStudy.setFacilityRecruitmentStatus(fp.getString("facRecStatus"));
    newStudy.setFacilityState(fp.getString("facState"));
    newStudy.setFacilityZip(fp.getString("facZip"));

    session.setAttribute("newStudy", newStudy);
    if (errors.isEmpty()) {
      forwardPage(Page.UPDATE_STUDY7);
    } else {
      request.setAttribute("formMessages", errors);
      request.setAttribute("facRecruitStatusMap", CreateStudyServlet.facRecruitStatusMap);
      forwardPage(Page.UPDATE_STUDY6);
    }
  }
  private void confirmStudy2() throws Exception {
    Validator v = new Validator(request);
    FormProcessor fp = new FormProcessor(request);

    v.addValidation(INPUT_START_DATE, Validator.IS_A_DATE);
    if (!StringUtil.isBlank(fp.getString(INPUT_END_DATE))) {
      v.addValidation(INPUT_END_DATE, Validator.IS_A_DATE);
    }
    v.addValidation(INPUT_VER_DATE, Validator.IS_A_DATE);

    errors = v.validate();
    boolean isInterventional = updateStudy2();

    if (errors.isEmpty()) {
      logger.info("no errors");
      ArrayList interventionArray = new ArrayList();
      if (isInterventional) {
        interventionArray = parseInterventions((StudyBean) session.getAttribute("newStudy"));
        setMaps(isInterventional, interventionArray);
        forwardPage(Page.UPDATE_STUDY3);
      } else {
        setMaps(isInterventional, interventionArray);
        forwardPage(Page.UPDATE_STUDY4);
      }

    } else {
      logger.info("has validation errors");
      try {
        local_df.parse(fp.getString(INPUT_START_DATE));
        fp.addPresetValue(INPUT_START_DATE, local_df.format(fp.getDate(INPUT_START_DATE)));
      } catch (ParseException pe) {
        fp.addPresetValue(INPUT_START_DATE, fp.getString(INPUT_START_DATE));
      }
      try {
        local_df.parse(fp.getString(INPUT_VER_DATE));
        fp.addPresetValue(INPUT_VER_DATE, local_df.format(fp.getDate(INPUT_VER_DATE)));
      } catch (ParseException pe) {
        fp.addPresetValue(INPUT_VER_DATE, fp.getString(INPUT_VER_DATE));
      }
      try {
        local_df.parse(fp.getString(INPUT_END_DATE));
        fp.addPresetValue(INPUT_END_DATE, local_df.format(fp.getDate(INPUT_END_DATE)));
      } catch (ParseException pe) {
        fp.addPresetValue(INPUT_END_DATE, fp.getString(INPUT_END_DATE));
      }
      setPresetValues(fp.getPresetValues());
      request.setAttribute("formMessages", errors);
      request.setAttribute("studyPhaseMap", CreateStudyServlet.studyPhaseMap);
      request.setAttribute("statuses", Status.toActiveArrayList());
      forwardPage(Page.UPDATE_STUDY2);
    }
  }
  /**
   * Validates the first section of study and save it into study bean
   *
   * @param request
   * @param response
   * @throws Exception
   */
  private void confirmStudy1() throws Exception {
    Validator v = new Validator(request);
    FormProcessor fp = new FormProcessor(request);

    v.addValidation("name", Validator.NO_BLANKS);
    v.addValidation("uniqueProId", Validator.NO_BLANKS);
    v.addValidation("description", Validator.NO_BLANKS);
    v.addValidation("prinInvestigator", Validator.NO_BLANKS);
    v.addValidation("sponsor", Validator.NO_BLANKS);

    v.addValidation(
        "secondProId",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        255);
    v.addValidation(
        "collaborators",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        1000);
    v.addValidation(
        "protocolDescription",
        Validator.LENGTH_NUMERIC_COMPARISON,
        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO,
        1000);

    errors = v.validate();
    if (fp.getString("name").trim().length() > 100) {
      Validator.addError(errors, "name", resexception.getString("maximum_lenght_name_100"));
    }
    if (fp.getString("uniqueProId").trim().length() > 30) {
      Validator.addError(
          errors, "uniqueProId", resexception.getString("maximum_lenght_unique_protocol_30"));
    }
    if (fp.getString("description").trim().length() > 255) {
      Validator.addError(
          errors, "description", resexception.getString("maximum_lenght_brief_summary_255"));
    }
    if (fp.getString("prinInvestigator").trim().length() > 255) {
      Validator.addError(
          errors,
          "prinInvestigator",
          resexception.getString("maximum_lenght_principal_investigator_255"));
    }
    if (fp.getString("sponsor").trim().length() > 255) {
      Validator.addError(errors, "sponsor", resexception.getString("maximum_lenght_sponsor_255"));
    }
    if (fp.getString("officialTitle").trim().length() > 255) {
      Validator.addError(
          errors, "officialTitle", resexception.getString("maximum_lenght_official_title_255"));
    }
    session.setAttribute("newStudy", createStudyBean());

    if (errors.isEmpty()) {
      logger.info("no errors in the first section");
      request.setAttribute("studyPhaseMap", CreateStudyServlet.studyPhaseMap);
      request.setAttribute("statuses", Status.toActiveArrayList());
      StudyBean newStudy = (StudyBean) session.getAttribute("newStudy");
      fp.addPresetValue(INPUT_START_DATE, local_df.format(newStudy.getDatePlannedStart()));
      if (newStudy.getDatePlannedEnd() != null) {
        fp.addPresetValue(INPUT_END_DATE, local_df.format(newStudy.getDatePlannedEnd()));
      }
      fp.addPresetValue(INPUT_VER_DATE, local_df.format(newStudy.getProtocolDateVerification()));
      setPresetValues(fp.getPresetValues());
      forwardPage(Page.UPDATE_STUDY2);

    } else {
      logger.info("has validation errors in the first section");
      request.setAttribute("formMessages", errors);

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

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

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

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

    trigger.setJobDataMap(jobDataMap);
    // trigger.setRepeatInterval(interval.longValue());
    // System.out.println("default for volatile: " + trigger.isVolatile());
    trigger.setVolatility(false);
    return trigger;
  }
  @Override
  public void processRequest() throws Exception {

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

    String action = fp.getString("action");
    if (subjectId == 0 || StringUtil.isBlank(action)) {
      addPageMessage(respage.getString("please_choose_a_subject_to_remove"));
      forwardPage(Page.SUBJECT_LIST_SERVLET);
    } else {

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

      // find all study subjects
      StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());
      ArrayList studySubs = ssdao.findAllBySubjectId(subjectId);

      // find study events
      StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
      ArrayList events = sedao.findAllBySubjectId(subjectId);
      if ("confirm".equalsIgnoreCase(action)) {
        request.setAttribute("subjectToRemove", subject);
        request.setAttribute("studySubs", studySubs);
        request.setAttribute("events", events);
        forwardPage(Page.REMOVE_SUBJECT);
      } else {
        logger.info("submit to remove the subject");
        // change all statuses to deleted
        subject.setStatus(Status.DELETED);
        subject.setUpdater(ub);
        subject.setUpdatedDate(new Date());
        sdao.update(subject);

        // remove subject references from study
        for (int i = 0; i < studySubs.size(); i++) {
          StudySubjectBean studySub = (StudySubjectBean) studySubs.get(i);
          if (!studySub.getStatus().equals(Status.DELETED)) {
            studySub.setStatus(Status.AUTO_DELETED);
            studySub.setUpdater(ub);
            studySub.setUpdatedDate(new Date());
            ssdao.update(studySub);
          }
        }

        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")
                + " "
                + respage.getString("has_been_removed_succesfully");

        addPageMessage(emailBody);
        //                sendEmail(emailBody);

        forwardPage(Page.SUBJECT_LIST_SERVLET);
      }
    }
  }
  @Override
  @SuppressWarnings(value = "unchecked")
  public void processRequest() throws Exception {
    ItemDataDAO itemDataDao = new ItemDataDAO(sm.getDataSource());
    EventCRFDAO eventCrfDao = new EventCRFDAO(sm.getDataSource());
    CrfBusinessLogicHelper crfBusinessLogicHelper = new CrfBusinessLogicHelper(sm.getDataSource());
    String action = request.getParameter("action");

    FormProcessor fp = new FormProcessor(request);

    // checks which module the requests are from
    String module = fp.getString(MODULE);
    request.setAttribute(MODULE, module);

    resetPanel();
    panel.setStudyInfoShown(false);
    panel.setOrderedData(true);

    setToPanel(resword.getString("create_CRF"), respage.getString("br_create_new_CRF_entering"));

    setToPanel(
        resword.getString("create_CRF_version"), respage.getString("br_create_new_CRF_uploading"));
    setToPanel(
        resword.getString("revise_CRF_version"), respage.getString("br_if_you_owner_CRF_version"));
    setToPanel(
        resword.getString("CRF_spreadsheet_template"),
        respage.getString("br_download_blank_CRF_spreadsheet_from"));
    setToPanel(
        resword.getString("example_CRF_br_spreadsheets"),
        respage.getString("br_download_example_CRF_instructions_from"));

    if ("confirm".equalsIgnoreCase(action)) {
      List<DisplayItemBeanWrapper> displayItemBeanWrappers =
          (List<DisplayItemBeanWrapper>) session.getAttribute("importedData");
      logger.info("Size of displayItemBeanWrappers : " + displayItemBeanWrappers.size());
      forwardPage(Page.VERIFY_IMPORT_CRF_DATA);
    }

    if ("save".equalsIgnoreCase(action)) {
      List<DisplayItemBeanWrapper> displayItemBeanWrappers =
          (List<DisplayItemBeanWrapper>) session.getAttribute("importedData");
      // System.out.println("Size of displayItemBeanWrappers : " + displayItemBeanWrappers.size());

      for (DisplayItemBeanWrapper wrapper : displayItemBeanWrappers) {

        int eventCrfBeanId = -1;
        EventCRFBean eventCrfBean = new EventCRFBean();

        // TODO : tom , the wrapper object has all the necessary data -
        // as you see we check the
        // is to see if this data is Savable if it is then we go ahead
        // and save it. if not we discard.
        // So the change needs to happen here , instead of discarding we
        // need to file discrepancy notes
        // and save the data. If you look in the
        // Page.VERIFY_IMPORT_CRF_DATA jsp file you can see how I am
        // pulling the errors. and use that in the same way.

        logger.info("right before we check to make sure it is savable: " + wrapper.isSavable());
        if (wrapper.isSavable()) {
          ArrayList<Integer> eventCrfInts = new ArrayList<Integer>();
          // based on the use case: "If any of the data does not meet
          // validations specified in the CRF
          // Template, a discrepancy note is automatically logged.
          // The DN will have a type of Failed Validation Check, and
          // a message of Failed Validation check."
          // System.out.println("wrapper problems found : " +
          // wrapper.getValidationErrors().toString());
          for (DisplayItemBean displayItemBean : wrapper.getDisplayItemBeans()) {
            eventCrfBeanId = displayItemBean.getData().getEventCRFId();
            eventCrfBean = (EventCRFBean) eventCrfDao.findByPK(eventCrfBeanId);
            logger.info("found value here: " + displayItemBean.getData().getValue());
            logger.info("found status here: " + eventCrfBean.getStatus().getName());
            // System.out.println("found event crf bean name here: "
            // +
            // eventCrfBean.getEventName()+" id "+eventCrfBean.getId
            // ());
            // SO, items can be created in a wrapper which is set to
            // overwrite
            // we get around this by checking the bean first, to
            // make sure it's not null
            ItemDataBean itemDataBean = new ItemDataBean();
            itemDataBean =
                itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(
                    displayItemBean.getItem().getId(),
                    eventCrfBean.getId(),
                    displayItemBean.getData().getOrdinal());
            if (wrapper.isOverwrite() && itemDataBean.getStatus() != null) {
              // ItemDataBean itemDataBean = new ItemDataBean();
              // itemDataBean =
              // itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(
              // displayItemBean.getItem().getId(),
              // eventCrfBean.getId(), displayItemBean
              // .getData().getOrdinal());
              // itemDataBean =
              // itemDataDao.findByEventCRFIdAndItemName(
              // eventCrfBean,
              // displayItemBean.getItem().getName());
              logger.info(
                  "just tried to find item data bean on item name "
                      + displayItemBean.getItem().getName());
              itemDataBean.setUpdatedDate(new Date());
              itemDataBean.setUpdater(ub);
              itemDataBean.setValue(displayItemBean.getData().getValue());
              // set status?
              itemDataDao.update(itemDataBean);
              logger.info("updated: " + itemDataBean.getItemId());
              // need to set pk here in order to create dn
              displayItemBean.getData().setId(itemDataBean.getId());
            } else {
              itemDataDao.create(displayItemBean.getData());
              logger.info(
                  "created: "
                      + displayItemBean.getData().getItemId()
                      + "event CRF ID = "
                      + eventCrfBean.getId()
                      + "CRF VERSION ID ="
                      + eventCrfBean.getCRFVersionId());

              // does this dao function work for repeating
              // events/groups?
              // ItemDataBean itemDataBean =
              // itemDataDao.findByEventCRFIdAndItemName(
              // eventCrfBean,
              // displayItemBean.getItem().getName());
              ItemDataBean itemDataBean2 =
                  itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(
                      displayItemBean.getItem().getId(),
                      eventCrfBean.getId(),
                      displayItemBean.getData().getOrdinal());
              logger.info(
                  "found: id " + itemDataBean2.getId() + " name " + itemDataBean2.getName());
              displayItemBean.getData().setId(itemDataBean2.getId());
            }
            // logger.info("created item data bean:
            // "+displayItemBean.getData().getId());
            // logger.info("created:
            // "+displayItemBean.getData().getName());
            // logger.info("continued:
            // "+displayItemBean.getData().getItemId());
            ItemDAO idao = new ItemDAO(sm.getDataSource());
            ItemBean ibean = (ItemBean) idao.findByPK(displayItemBean.getData().getItemId());
            // logger.info("continued2: getName " +
            // ibean.getName());
            // System.out.println("*** checking for validation errors: " + ibean.getName());
            String itemOid =
                displayItemBean.getItem().getOid()
                    + "_"
                    + wrapper.getStudyEventRepeatKey()
                    + "_"
                    + displayItemBean.getData().getOrdinal()
                    + "_"
                    + wrapper.getStudySubjectOid();
            if (wrapper.getValidationErrors().containsKey(itemOid)) {
              ArrayList messageList = (ArrayList) wrapper.getValidationErrors().get(itemOid);
              // if
              // (wrapper.getValidationErrors().containsKey(ibean
              // .getName())) {
              // ArrayList messageList = (ArrayList)
              // wrapper.getValidationErrors
              // ().get(ibean.getName());
              // could be more then one will have to iterate
              // could it be more than one? tbh 08/2008
              for (int iter = 0; iter < messageList.size(); iter++) {
                String message = (String) messageList.get(iter);
                DiscrepancyNoteBean parentDn =
                    ImportSpringJob.createDiscrepancyNote(
                        ibean,
                        message,
                        eventCrfBean,
                        displayItemBean,
                        null,
                        ub,
                        sm.getDataSource(),
                        currentStudy);
                ImportSpringJob.createDiscrepancyNote(
                    ibean,
                    message,
                    eventCrfBean,
                    displayItemBean,
                    parentDn.getId(),
                    ub,
                    sm.getDataSource(),
                    currentStudy);
                // System.out.println("*** created disc note with message: " + message);
                // displayItemBean);
              }
            }
            // logger.info("created:
            // "+displayItemBean.getDbData().getName());
            if (!eventCrfInts.contains(new Integer(eventCrfBean.getId()))) {
              crfBusinessLogicHelper.markCRFComplete(eventCrfBean, ub);
              // System.out.println("*** just updated event crf bean: " + eventCrfBean.getId());
              eventCrfInts.add(new Integer(eventCrfBean.getId()));
            }
          }
          // end of item datas, tbh
          // crfBusinessLogicHelper.markCRFComplete(eventCrfBean, ub);
          // System .out.println("*** just updated event crf bean: "+
          // eventCrfBean.getId());
          // need to update the study event status as well, tbh
          // crfBusinessLogicHelper.updateStudyEvent(eventCrfBean,
          // ub);
          // above should do it for us, tbh 08/2008
        }
      }

      addPageMessage(respage.getString("data_has_been_successfully_import"));
      // forwardPage(Page.SUBMIT_DATA_SERVLET);
      forwardPage(Page.LIST_STUDY_SUBJECTS_SERVLET);
      // replaced tbh, 06/2009
    }
  }
  @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);
  }
  /*
   * (non-Javadoc)
   *
   * @see org.akaza.openclinica.control.core.SecureController#mayProceed()
   */
  @Override
  protected void mayProceed(HttpServletRequest request, HttpServletResponse response)
      throws InsufficientPermissionException {
    checkStudyLocked(
        Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_locked"), request, response);
    checkStudyFrozen(
        Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_frozen"), request, response);
    UserAccountBean ub = (UserAccountBean) request.getSession().getAttribute(USER_BEAN_NAME);
    StudyUserRoleBean currentRole =
        (StudyUserRoleBean) request.getSession().getAttribute("userRole");
    HttpSession session = request.getSession();
    locale = request.getLocale();

    // < respage =
    // ResourceBundle.getBundle("org.akaza.openclinica.i18n.page_messages",
    // locale);
    // < restext =
    // ResourceBundle.getBundle("org.akaza.openclinica.i18n.notes",locale);
    // <
    // resexception=ResourceBundle.getBundle(
    // "org.akaza.openclinica.i18n.exceptions",locale);
    // < resword =
    // ResourceBundle.getBundle("org.akaza.openclinica.i18n.words",locale);

    getInputBeans(request);
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    FormProcessor fp = new FormProcessor(request);
    SectionBean sb = (SectionBean) request.getAttribute(SECTION_BEAN);

    // BWP 12/2/07>> The following COUNT_VALIDATE session attribute is not
    // accessible,
    // for unknown reasons (threading problems?), when
    // double-data entry displays error messages; it's value is always 0; so
    // I have to create my
    // own session variable here to keep track of DDE stages

    // We'll go by the SectionBean's ordinal first
    int tabNumber = 1;
    if (sb != null) {
      tabNumber = sb.getOrdinal();
    }
    // if tabNumber still isn't valid, check the "tab" parameter
    if (tabNumber < 1) {
      if (fp == null) {
        fp = new FormProcessor(request);
      }
      String tab = fp.getString("tab");
      if (tab == null || tab.length() < 1) {
        tabNumber = 1;
      } else {
        tabNumber = fp.getInt("tab");
      }
    }
    SectionDAO sectionDao = new SectionDAO(getDataSource());
    int crfVersionId = ecb.getCRFVersionId();
    int eventCRFId = ecb.getId();
    ArrayList sections = sectionDao.findAllByCRFVersionId(crfVersionId);
    int sectionSize = sections.size();

    HttpSession mySession = request.getSession();
    DoubleDataProgress doubleDataProgress =
        (DoubleDataProgress) mySession.getAttribute(DDE_PROGESS);
    if (doubleDataProgress == null || doubleDataProgress.getEventCRFId() != eventCRFId) {
      doubleDataProgress = new DoubleDataProgress(sectionSize, eventCRFId);
      mySession.setAttribute(DDE_PROGESS, doubleDataProgress);
    }
    boolean hasVisitedSection = doubleDataProgress.getSectionVisited(tabNumber, eventCRFId);

    // setting up one-time validation here
    // admit that it's an odd place to put it, but where else?
    // placing it in dataentryservlet is creating too many counts
    int keyId = ecb.getId();
    Integer count = (Integer) session.getAttribute(COUNT_VALIDATE + keyId);
    if (count != null) {
      count++;
      session.setAttribute(COUNT_VALIDATE + keyId, count);
      logger.info("^^^just set count to session: " + count);
    } else {
      count = 0;
      session.setAttribute(COUNT_VALIDATE + keyId, count);
      logger.info("***count not found, set to session: " + count);
    }

    DataEntryStage stage = ecb.getStage();
    if (stage.equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE) && !hasVisitedSection) {
      // if the user has not entered this section yet in Double Data
      // Entry, then
      // set a flag that default values should be shown in the form
      request.setAttribute(DDE_ENTERED, true);
    }
    // Now update the session attribute
    doubleDataProgress.setSectionVisited(eventCRFId, tabNumber, true);
    mySession.setAttribute("doubleDataProgress", doubleDataProgress);
    // StudyEventStatus status =
    Role r = currentRole.getRole();
    session.setAttribute("mayProcessUploading", "true");

    //        if (!SubmitDataServlet.maySubmitData(ub, currentRole)) {
    //            this.session.setAttribute("mayProcessUploading", "false");
    //            String exceptionName = resexception.getString("no_permission_validation");
    //            String noAccessMessage =
    // resexception.getString("not_perfom_validation_syscontact");
    //
    //            addPageMessage(noAccessMessage);
    //            throw new InsufficientPermissionException(Page.MENU, exceptionName, "1");
    //        }
    //
    //        if (stage.equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE)) {
    //            if (userIsOwnerAndLessThanTwelveHoursHavePassed() && !r.equals(Role.STUDYDIRECTOR)
    // && !r.equals(Role.COORDINATOR)) {
    //                this.session.setAttribute("mayProcessUploading", "false");
    //                addPageMessage(respage.getString("since_perform_data_entry"));
    //                throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET,
    // resexception.getString("owner_attempting_double_data_entry"), "1");
    //            }
    //        } else if (stage.equals(DataEntryStage.DOUBLE_DATA_ENTRY)) {
    //            if (ub.getId() != ecb.getValidatorId() && !r.equals(Role.STUDYDIRECTOR) &&
    // !r.equals(Role.COORDINATOR)) {
    //                this.session.setAttribute("mayProcessUploading", "false");
    //                addPageMessage(respage.getString("validation_has_already_begun"));
    //                throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET,
    // resexception
    //                        .getString("non_validator_attempting_double_data_entry"), "1");
    //            }
    //        } else {
    //            this.session.setAttribute("mayProcessUploading", "false");
    //            addPageMessage(respage.getString("not_perform_validation"));
    //            throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET,
    // resexception.getString("using_double_data_entry_CRF_completed"), "1");
    //        }

    return;
  }
  private void updateStudy3(boolean isInterventional) {
    FormProcessor fp = new FormProcessor(request);
    StudyBean study = (StudyBean) session.getAttribute("newStudy");
    study.setPurpose(fp.getString("purpose"));
    ArrayList interventionArray = new ArrayList();
    if (isInterventional) {
      study.setAllocation(fp.getString("allocation"));
      study.setMasking(fp.getString("masking"));
      study.setControl(fp.getString("control"));
      study.setAssignment(fp.getString("assignment"));
      study.setEndpoint(fp.getString("endpoint"));

      // Handle Interventions-type and name
      // repeat 10 times for each pair on the web page
      StringBuffer interventions = new StringBuffer();

      for (int i = 0; i < 10; i++) {
        String type = fp.getString("interType" + i);
        String name = fp.getString("interName" + i);
        if (!StringUtil.isBlank(type) && !StringUtil.isBlank(name)) {
          InterventionBean ib =
              new InterventionBean(fp.getString("interType" + i), fp.getString("interName" + i));
          interventionArray.add(ib);
          interventions.append(ib.toString()).append(",");
        }
      }
      study.setInterventions(interventions.toString());

    } else { // type = observational
      study.setDuration(fp.getString("duration"));
      study.setSelection(fp.getString("selection"));
      study.setTiming(fp.getString("timing"));
    }
    session.setAttribute("newStudy", study);
    session.setAttribute("interventions", interventionArray);
  }
  /*
   * (non-Javadoc)
   *
   * @see org.akaza.openclinica.control.core.SecureController#processRequest()
   */
  @Override
  protected void processRequest() throws Exception {

    FormProcessor fp = new FormProcessor(request);
    int noteId = fp.getInt(INPUT_NOTE_ID);
    String module = (String) session.getAttribute("module");
    // Integer subjectId = (Integer) session.getAttribute("subjectId");

    StudySubjectDAO studySubjectDAO = new StudySubjectDAO(sm.getDataSource());

    DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource());
    dndao.setFetchMapping(true);

    // check that the note exists
    DiscrepancyNoteBean discrepancyNoteBean = (DiscrepancyNoteBean) dndao.findByPK(noteId);

    if (!discrepancyNoteBean.isActive()) {
      throw new InconsistentStateException(
          Page.MANAGE_STUDY_SERVLET,
          resexception.getString("you_are_trying_resolve_discrepancy_not_exist"));
    }

    // check that the note has not already been closed
    ArrayList children = dndao.findAllByParent(discrepancyNoteBean);
    discrepancyNoteBean.setChildren(children);
    // This logic has been reverted, issue-7459
    //        if (parentNoteIsClosed(discrepancyNoteBean)) {
    //            throw new InconsistentStateException(Page.VIEW_DISCREPANCY_NOTES_IN_STUDY_SERVLET,
    // respage
    //                    .getString("the_discrepancy_choose_has_been_closed_resolved_create_new"));
    //        }

    // all clear, send the user to the resolved screen
    String entityType = discrepancyNoteBean.getEntityType().toLowerCase();
    discrepancyNoteBean.setResStatus(
        ResolutionStatus.get(discrepancyNoteBean.getResolutionStatusId()));
    discrepancyNoteBean.setDisType(
        DiscrepancyNoteType.get(discrepancyNoteBean.getDiscrepancyNoteTypeId()));
    // BWP 03/17/2009 3166: if it's not an ItemData type note, redirect
    // Monitors to View Subject or
    // View Study Events <<
    if (currentRole.getRole().equals(Role.MONITOR)
        && !"itemdata".equalsIgnoreCase(entityType)
        && !"eventcrf".equalsIgnoreCase(entityType)) {
      redirectMonitor(module, discrepancyNoteBean);
      return;
    }
    // >>
    // If Study is Frozen or Locked
    if (currentStudy.getStatus().isFrozen()
        && !"itemdata".equalsIgnoreCase(entityType)
        && !"eventcrf".equalsIgnoreCase(entityType)) {
      redirectMonitor(module, discrepancyNoteBean);
      return;
    }

    boolean toView = false;
    boolean isCompleted = false;
    if ("itemdata".equalsIgnoreCase(entityType)) {
      ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
      ItemDataBean idb = (ItemDataBean) iddao.findByPK(discrepancyNoteBean.getEntityId());

      EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());

      EventCRFBean ecb = (EventCRFBean) ecdao.findByPK(idb.getEventCRFId());
      StudySubjectBean studySubjectBean =
          (StudySubjectBean) studySubjectDAO.findByPK(ecb.getStudySubjectId());

      discrepancyNoteBean.setSubjectId(studySubjectBean.getId());
      discrepancyNoteBean.setItemId(idb.getItemId());

      if (ecb.getStatus().equals(Status.UNAVAILABLE)) {
        isCompleted = true;
      }

      toView = true; // we want to go to view note page if the note is
      // for item data
    }
    // logger.info("set up pop up url: " + createNoteURL);
    // System.out.println("set up pop up url: " + createNoteURL);
    boolean goNext =
        prepareRequestForResolution(
            request, sm.getDataSource(), currentStudy, discrepancyNoteBean, isCompleted);

    Page p = getPageForForwarding(discrepancyNoteBean, isCompleted);

    // logger.info("found page for forwarding: " + p.getFileName());
    if (p == null) {
      throw new InconsistentStateException(
          Page.VIEW_DISCREPANCY_NOTES_IN_STUDY_SERVLET,
          resexception.getString("the_discrepancy_note_triying_resolve_has_invalid_type"));
    } else {
      if (p.getFileName().contains("?")) {
        if (!p.getFileName().contains("fromViewNotes=1")) {
          p.setFileName(p.getFileName() + "&fromViewNotes=1");
        }
      } else {
        p.setFileName(p.getFileName() + "?fromViewNotes=1");
      }
      String createNoteURL =
          CreateDiscrepancyNoteServlet.getAddChildURL(
              discrepancyNoteBean, ResolutionStatus.CLOSED, true);
      setPopUpURL(createNoteURL);
    }

    if (!goNext) {
      setPopUpURL("");
      addPageMessage(
          respage.getString("you_may_not_perform_admin_edit_on_CRF_not_completed_by_user"));
      p = Page.VIEW_DISCREPANCY_NOTES_IN_STUDY_SERVLET;
    }

    forwardPage(p);
  }