@Override
  public void processRequest() throws Exception {
    resetPanel();
    panel.setStudyInfoShown(false);
    panel.setOrderedData(true);
    panel.setSubmitDataModule(false);
    panel.setExtractData(false);
    panel.setCreateDataset(false);

    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"));

    FormProcessor fp = new FormProcessor(request);

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

    int crfId = fp.getInt(CRF_ID);
    if (crfId == 0) {
      addPageMessage(respage.getString("please_choose_a_CRF_to_view"));
      forwardPage(Page.CRF_LIST);
    } else {
      CRFDAO cdao = new CRFDAO(sm.getDataSource());
      CRFVersionDAO vdao = new CRFVersionDAO(sm.getDataSource());
      CRFBean crf = (CRFBean) cdao.findByPK(crfId);
      ArrayList<CRFVersionBean> versions = (ArrayList<CRFVersionBean>) vdao.findAllByCRF(crfId);
      crf.setVersions(versions);
      // Collection<RuleSetBean> items =
      // getRuleSetService().getRuleSetsByCrf(crf);
      Collection<TableColumnHolder> items = populate(crf, versions);
      TableFacade tableFacade = createTableFacade("rules", request);
      tableFacade.setItems(items); // set the items
      tableFacade.setExportTypes(response, CSV, JEXCEL);
      tableFacade.setStateAttr("restore");

      Limit limit = tableFacade.getLimit();
      if (limit.isExported()) {
        export(tableFacade);
        // return null; // In Spring returning null tells the controller
        // not to do anything.
      }

      String html = html(tableFacade);
      request.setAttribute("rules", html); // Set the Html in the
      // request for the JSP.

      request.setAttribute(CRF, crf);
      forwardPage(Page.VIEW_CRF);
    }
  }
  public void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    int itemId = fp.getInt(ITEM_ID);
    ItemDAO idao = new ItemDAO(sm.getDataSource());
    ItemFormMetadataDAO ifmdao = new ItemFormMetadataDAO(sm.getDataSource());
    CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
    CRFDAO cdao = new CRFDAO(sm.getDataSource());

    if (itemId == 0) {
      addPageMessage("Please choose an item first.");
      forwardPage(Page.ITEM_DETAIL);
      return;
    }
    ItemBean item = (ItemBean) idao.findByPK(itemId);
    ArrayList versions = idao.findAllVersionsByItemId(item.getId());
    ArrayList versionItems = new ArrayList();
    // finds each item metadata for each version
    for (int i = 0; i < versions.size(); i++) {
      Integer versionId = (Integer) versions.get(i);
      CRFVersionBean version = (CRFVersionBean) cvdao.findByPK(versionId.intValue());
      if (versionId != null && versionId.intValue() > 0) {
        ItemFormMetadataBean imfBean =
            ifmdao.findByItemIdAndCRFVersionId(item.getId(), versionId.intValue());
        imfBean.setCrfVersionName(version.getName());
        CRFBean crf = (CRFBean) cdao.findByPK(version.getCrfId());
        imfBean.setCrfName(crf.getName());
        versionItems.add(imfBean);
      }
    }
    request.setAttribute(VERSION_ITEMS, versionItems);
    request.setAttribute(ITEM_BEAN, item);
    forwardPage(Page.ITEM_DETAIL);
  }
 private ArrayList<StudyEventDefinitionBean> initDefinitions(StudyBean site) {
   ArrayList<StudyEventDefinitionBean> seds = new ArrayList<StudyEventDefinitionBean>();
   StudyEventDefinitionDAO sedDao = new StudyEventDefinitionDAO(sm.getDataSource());
   EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
   CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
   CRFDAO cdao = new CRFDAO(sm.getDataSource());
   StudyBean parentStudy =
       (StudyBean) new StudyDAO(sm.getDataSource()).findByPK(site.getParentStudyId());
   seds = sedDao.findAllByStudy(parentStudy);
   int start = 0;
   for (StudyEventDefinitionBean sed : seds) {
     int defId = sed.getId();
     ArrayList<EventDefinitionCRFBean> edcs =
         (ArrayList<EventDefinitionCRFBean>)
             edcdao.findAllByDefinitionAndSiteIdAndParentStudyId(
                 defId, site.getId(), parentStudy.getId());
     ArrayList<EventDefinitionCRFBean> defCrfs = new ArrayList<EventDefinitionCRFBean>();
     // sed.setCrfNum(edcs.size());
     for (EventDefinitionCRFBean edcBean : edcs) {
       int edcStatusId = edcBean.getStatus().getId();
       CRFBean crf = (CRFBean) cdao.findByPK(edcBean.getCrfId());
       int crfStatusId = crf.getStatusId();
       if (edcStatusId == 5 || edcStatusId == 7 || crfStatusId == 5 || crfStatusId == 7) {
       } else {
         ArrayList<CRFVersionBean> versions =
             (ArrayList<CRFVersionBean>) cvdao.findAllActiveByCRF(edcBean.getCrfId());
         edcBean.setVersions(versions);
         edcBean.setCrfName(crf.getName());
         CRFVersionBean defaultVersion =
             (CRFVersionBean) cvdao.findByPK(edcBean.getDefaultVersionId());
         edcBean.setDefaultVersionName(defaultVersion.getName());
         String sversionIds = edcBean.getSelectedVersionIds();
         ArrayList<Integer> idList = new ArrayList<Integer>();
         if (sversionIds.length() > 0) {
           String[] ids = sversionIds.split("\\,");
           for (String id : ids) {
             idList.add(Integer.valueOf(id));
           }
         }
         edcBean.setSelectedVersionIdList(idList);
         defCrfs.add(edcBean);
         ++start;
       }
     }
     logger.debug("definitionCrfs size=" + defCrfs.size() + " total size=" + edcs.size());
     sed.setCrfs(defCrfs);
     sed.setCrfNum(defCrfs.size());
   }
   return seds;
 }
  // testUpdate
  public void testUpdateSuccess() throws Exception {
    CRFBean sb = (CRFBean) cdao.findByPK(1);
    String keepName = sb.getName();
    sb.setName("new name");
    UserAccountBean ub = new UserAccountBean();
    ub.setId(1);
    sb.setUpdater(ub);

    sb.setStatus(Status.AVAILABLE);

    sb = (CRFBean) cdao.update(sb);
    sb.setName(keepName);
    CRFBean sbs = (CRFBean) cdao.update(sb);
    assertNotNull("test update", sbs);
  }
  public void testUpdateFail() throws Exception {
    CRFBean sb = (CRFBean) cdao.findByPK(1000);
    String keepName = sb.getName();
    sb.setName("new name");
    UserAccountBean ub = new UserAccountBean();
    ub.setId(2);
    sb.setUpdater(ub);

    sb.setStatus(Status.AVAILABLE);

    sb = (CRFBean) cdao.update(sb);
    sb.setName(keepName);
    CRFBean sbs = (CRFBean) cdao.update(sb);
    assertNotNull("test update", sbs);
    assertEquals("check primarykey", sb.getId(), 0);
  }
  /*
   * (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);
  }
 public void testStuff() throws Exception {
   ArrayList col = (ArrayList) cdao.findAll();
   for (int i = 0; i < col.size(); i++) {
     CRFBean eb = (CRFBean) col.get(i);
     System.out.println(eb.getName());
   }
   assertNotNull("findAll", col);
 }
  public void testFindByVersionIdFail() throws Exception {
    int crfVersionId = -1;
    int crfId = 1;

    CRFBean cb = cdao.findByVersionId(crfVersionId);

    assertNotNull("bean valid", cb);
    assertTrue("bean inactive", !cb.isActive());
  }
  public void testFindByVersionIdSuccess() throws Exception {
    int crfVersionId = 1;
    int crfId = 1;

    CRFBean cb = cdao.findByVersionId(crfVersionId);

    assertNotNull("bean valid", cb);
    assertTrue("bean id set", cb.isActive());
    assertEquals("correct bean found", cb.getId(), crfId);
  }
  public void testInsertFail() throws Exception {
    CRFBean cb = new CRFBean();
    cb.setName("test CRF -- please delete");
    cb.setStatus(Status.AVAILABLE);
    cb.setDescription("test CRF -- please delete");
    cb.setOwner(new UserAccountBean());
    CRFBean cbc = (CRFBean) cdao.create(cb);
    assertNotNull("test insert", cbc);

    assertEquals("check primarykey", cb.getId(), 0);
  }
 // testInsert
 public void testInsertSuccess() throws Exception {
   CRFBean cb = new CRFBean();
   cb.setName("test CRF -- please delete");
   cb.setStatus(Status.AVAILABLE);
   cb.setDescription("test CRF -- please delete");
   UserAccountBean ub = new UserAccountBean();
   ub.setId(1);
   cb.setOwner(ub);
   CRFBean cbc = (CRFBean) cdao.create(cb);
   assertNotNull("test insert", cbc);
 }
  @Override
  public void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    int studySubId = fp.getInt(STUDY_SUB_ID, true);
    int eventCRFId = fp.getInt(EVENT_CRF_ID);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        request.setAttribute("displayEventCRF", dec);

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

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

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

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

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

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

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

          // Default Values are not addressed

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

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

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

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

        addPageMessage(emailBody);
        // sendEmail(emailBody);
        request.setAttribute("id", new Integer(studySubId).toString());
        forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET);
      }
    }
  }
  @RequestMapping(method = RequestMethod.GET)
  public ModelMap handleMainPage(HttpServletRequest request) {
    ModelMap map = new ModelMap();
    // setUpSidebar(request);
    StudyBean currentStudy = (StudyBean) request.getSession().getAttribute("study");

    eventDefinitionCRFDao = new EventDefinitionCRFDAO(dataSource);
    studyEventDefinitionDao = new StudyEventDefinitionDAO(dataSource);
    crfDao = new CRFDAO(dataSource);
    studyGroupClassDao = new StudyGroupClassDAO(dataSource);
    studyDao = new StudyDAO(dataSource);
    userDao = new UserAccountDAO(dataSource);
    ruleDao = new RuleDAO(dataSource);

    StudyModuleStatus sms = studyModuleStatusDao.findByStudyId(currentStudy.getId());
    if (sms == null) {
      sms = new StudyModuleStatus();
      sms.setStudyId(currentStudy.getId());
    }

    int crfCount = crfDao.findAllByStudy(currentStudy.getId()).size();
    int crfWithEventDefinition = crfDao.findAllActiveByDefinitions(currentStudy.getId()).size();
    int totalCrf = crfCount + crfWithEventDefinition;
    // int eventDefinitionCount = eventDefinitionCRFDao.findAllActiveByStudy(currentStudy).size();
    int eventDefinitionCount = studyEventDefinitionDao.findAllActiveByStudy(currentStudy).size();

    int subjectGroupCount = studyGroupClassDao.findAllActiveByStudy(currentStudy).size();

    List<RuleSetBean> ruleSets = ruleSetService.getRuleSetsByStudy(currentStudy);
    ruleSets = ruleSetService.filterByStatusEqualsAvailableOnlyRuleSetRules(ruleSets);
    int ruleCount = ruleSets != null ? ruleSets.size() : 0;

    int siteCount = studyDao.findOlnySiteIdsByStudy(currentStudy).size();
    int userCount = userDao.findAllUsersByStudy(currentStudy.getId()).size();
    Collection childStudies = studyDao.findAllByParent(currentStudy.getId());
    Map childStudyUserCount = new HashMap();
    for (Object sb : childStudies) {
      StudyBean childStudy = (StudyBean) sb;
      childStudyUserCount.put(
          childStudy.getName(), userDao.findAllUsersByStudy(childStudy.getId()).size());
    }

    if (sms.getCrf() == 0) {
      sms.setCrf(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getCrf() != 3 && totalCrf > 0) {
      sms.setCrf(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getEventDefinition() == 0) {
      sms.setEventDefinition(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getEventDefinition() != 3 && eventDefinitionCount > 0) {
      sms.setEventDefinition(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getSubjectGroup() == 0) {
      sms.setSubjectGroup(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getSubjectGroup() != 3 && subjectGroupCount > 0) {
      sms.setSubjectGroup(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getRule() == 0) {
      sms.setRule(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getRule() != 3 && ruleCount > 0) {
      sms.setRule(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getSite() == 0) {
      sms.setSite(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getSite() != 3 && siteCount > 0) {
      sms.setSite(StudyModuleStatus.IN_PROGRESS);
    }

    if (sms.getUsers() == 0) {
      sms.setUsers(StudyModuleStatus.NOT_STARTED);
    }
    if (sms.getUsers() != 3 && userCount > 0) {
      sms.setUsers(StudyModuleStatus.IN_PROGRESS);
    }

    map.addObject(sms);
    map.addAttribute("crfCount", totalCrf);
    map.addAttribute("eventDefinitionCount", eventDefinitionCount);
    map.addAttribute("subjectGroupCount", subjectGroupCount);
    map.addAttribute("ruleCount", ruleCount);
    map.addAttribute("siteCount", siteCount);
    map.addAttribute("userCount", userCount);
    map.addAttribute("childStudyUserCount", childStudyUserCount);
    map.addAttribute("studyId", currentStudy.getId());
    map.addAttribute("currentStudy", currentStudy);

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

    ArrayList pageMessages = new ArrayList();
    if (request.getSession().getAttribute("pageMessages") != null) {
      pageMessages.addAll((ArrayList) request.getSession().getAttribute("pageMessages"));
      request.setAttribute("pageMessages", pageMessages);
      request.getSession().removeAttribute("pageMessages");
    }
    return map;
  }
 public void testFindByPKFail() throws Exception {
   CRFBean sb = (CRFBean) cdao.findByPK(-1);
   assertNotNull("findbypk", sb);
   assertTrue("inactive object", !sb.isActive());
 }
 // testFindByPK
 public void testFindByPKSuccess() throws Exception {
   CRFBean sb = (CRFBean) cdao.findByPK(1);
   assertNotNull("findbypk", sb);
   assertTrue("active object", sb.isActive());
   assertEquals("correct object", sb.getId(), 1);
 }
  /**
   * @api {get} /rest2/openrosa/:studyOID/formList Get Form List
   * @apiName getFormList
   * @apiPermission admin
   * @apiVersion 1.0.0
   * @apiParam {String} studyOID Study Oid.
   * @apiGroup Form
   * @apiDescription Retrieves a listing of the available OpenClinica forms.
   * @apiParamExample {json} Request-Example: { "studyOid": "S_SAMPLTE", }
   * @apiSuccessExample {xml} Success-Response: HTTP/1.1 200 OK { <xforms
   *     xmlns="http://openrosa.org/xforms/xformsList"> <xform> <formID>F_FIRSTFORM_1</formID>
   *     <name>First Form</name> <majorMinorVersion>1</majorMinorVersion> <version>1</version>
   *     <hash>8678370cd92814d4e3216d58d821403f</hash>
   *     <downloadUrl>http://oc1.openclinica.com/OpenClinica-web/rest2/openrosa/S_SAMPLTE/formXml?
   *     formId=F_FIRSTFORM_1</downloadUrl> </xform> <xform> <formID>F_SECONDFORM_1</formID>
   *     <name>Second Form</name> <majorMinorVersion>1</majorMinorVersion> <version>1</version>
   *     <hash>7ee60d1c6516b730bbe9bdbd7cad942f</hash>
   *     <downloadUrl>http://oc1.openclinica.com/OpenClinica-web/rest2/openrosa/S_SAMPLTE/formXml?
   *     formId=F_SECONDFORM_1</downloadUrl> </xform> </xforms>
   */
  @GET
  @Path("/{studyOID}/formList")
  @Produces(MediaType.TEXT_XML)
  public String getFormList(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response,
      @PathParam("studyOID") String studyOID,
      @QueryParam("formID") String crfOID,
      @RequestHeader("Authorization") String authorization,
      @Context ServletContext context)
      throws Exception {
    if (!mayProceedPreview(studyOID)) return null;

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

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

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

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

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

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

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

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

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

      // Set response headers
      Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
      Date currentDate = new Date();
      cal.setTime(currentDate);
      SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz");
      format.setCalendar(cal);
      response.setHeader("Content-Type", "text/xml; charset=UTF-8");
      response.setHeader("Date", format.format(currentDate));
      response.setHeader("X-OpenRosa-Version", "1.0");
      return writer.toString();
    } catch (Exception e) {
      LOGGER.error(e.getMessage());
      LOGGER.error(ExceptionUtils.getStackTrace(e));
      return "<Error>" + e.getMessage() + "</Error>";
    }
  }