use of org.akaza.openclinica.dao.submit.CRFVersionDAO in project OpenClinica by OpenClinica.
the class OdmExtractDAO method getODMMetadataForForm.
/**
* Metadata to be obtained based on formVersionOID. The studyOID and studyEventOID are irrelevant as these are the global crfs, i.e crfs that do not belong to
* any particular CRF. In order to comply with cdisc ODM, the studyOID, studyeventDefOID etc will be static values which do not exist in the database.
* @param metadata
* @param formVersionOID
*/
// The method underneath tries to reuse the code based on getODMMetadata
public void getODMMetadataForForm(MetaDataVersionBean metadata, String formVersionOID, String odmVersion) {
FormDefBean formDef = new FormDefBean();
String cvIds = new String("");
CRFVersionDAO<String, ArrayList> crfVersionDAO = new CRFVersionDAO<String, ArrayList>(this.ds);
CRFVersionBean crfVersionBean = crfVersionDAO.findByOid(formVersionOID);
cvIds = crfVersionBean.getId() + "";
applyStudyEventDef(metadata, formVersionOID);
fetchItemGroupMetaData(metadata, cvIds, odmVersion);
getOCMetadataForGlobals(crfVersionBean.getId(), metadata, odmVersion);
ArrayList rows = new ArrayList();
ArrayList<ItemGroupDefBean> igs = (ArrayList<ItemGroupDefBean>) metadata.getItemGroupDefs();
HashMap<String, Integer> igPoses = getItemGroupOIDPos(metadata);
ArrayList<ItemDefBean> its = (ArrayList<ItemDefBean>) metadata.getItemDefs();
HashMap<String, Integer> itPoses = getItemOIDPos(metadata);
HashMap<String, Integer> inPoses = new HashMap<String, Integer>();
ItemGroupDefBean ig = new ItemGroupDefBean();
Iterator it;
metadata.setCvIds(cvIds);
HashMap<Integer, Integer> maxLengths = new HashMap<Integer, Integer>();
this.setItemDataMaxLengthTypesExpected();
rows.clear();
logger.debug("Begin to execute GetItemDataMaxLengths");
rows = select(this.getItemDataMaxLengths(cvIds));
it = rows.iterator();
while (it.hasNext()) {
HashMap row = (HashMap) it.next();
maxLengths.put((Integer) row.get("item_id"), (Integer) row.get("max_length"));
}
ItemDefBean itDef = new ItemDefBean();
formDef = fetchFormDetails(crfVersionBean, formDef);
this.setItemGroupAndItemMetaWithUnitTypesExpected();
rows.clear();
String prevCvIg = "";
logger.debug("Begin to execute GetItemGroupAndItemMetaWithUnitSql");
logger.debug("getItemGroupandItemMetaWithUnitsql= " + this.getItemGroupAndItemMetaWithUnitSql(cvIds));
HashMap<Integer, String> sectionLabels = this.getSectionLabels(metadata.getSectionIds());
HashMap<Integer, String> parentItemOIDs = this.getParentItemOIDs(cvIds);
this.setItemGroupAndItemMetaOC1_3TypesExpected();
logger.debug("Begin to execute GetItemGroupAndItemMetaWithUnitSql");
logger.debug("getItemGroupandItemMetaWithUnitsql= " + this.getItemGroupAndItemMetaOC1_3Sql(cvIds));
rows = select(this.getItemGroupAndItemMetaOC1_3Sql(cvIds));
Iterator iter = rows.iterator();
while (iter.hasNext()) {
HashMap row = (HashMap) iter.next();
Integer cvId = (Integer) row.get("crf_version_id");
Integer igId = (Integer) row.get("item_group_id");
String cvOID = (String) row.get("crf_version_oid");
String igOID = (String) row.get("item_group_oid");
String itOID = (String) row.get("item_oid");
Integer igRepeatNum = (Integer) row.get("repeat_number");
Integer igRepeatMax = (Integer) row.get("repeat_max");
Boolean showGroup = (Boolean) row.get("show_group");
String itemGroupHeader = (String) row.get("item_group_header");
String itHeader = (String) row.get("item_header");
String left = (String) row.get("left_item_text");
String right = (String) row.get("right_item_text");
String itSubheader = (String) row.get("subheader");
Integer itSecId = (Integer) row.get("section_id");
Integer itPId = (Integer) row.get("parent_id");
Integer itColNum = (Integer) row.get("column_number");
String itpgNum = (String) row.get("page_number_label");
String layout = (String) row.get("response_layout");
Integer rsTypeId = (Integer) row.get("response_type_id");
String dfValue = (String) row.get("default_value");
Boolean phi = (Boolean) row.get("phi_status");
Boolean showItem = (Boolean) row.get("show_item");
Integer orderInForm = (Integer) row.get("item_order");
if ((cvId + "-" + igId).equals(prevCvIg)) {
} else {
prevCvIg = cvId + "-" + igId;
ig = igs.get(igPoses.get(igOID));
ItemGroupDetailsBean igDetail = ig.getItemGroupDetails();
igDetail.setOid(igOID);
PresentInFormBean inForm = new PresentInFormBean();
inForm.setFormOid(cvOID);
ItemGroupRepeatBean igr = new ItemGroupRepeatBean();
igr.setRepeatMax(igRepeatMax);
igr.setRepeatNumber(igRepeatNum);
inForm.setItemGroupRepeatBean(igr);
inForm.setShowGroup(showGroup == true ? "Yes" : "No");
inForm.setItemGroupHeader(itemGroupHeader);
igDetail.getPresentInForms().add(inForm);
ig.setItemGroupDetails(igDetail);
}
itDef = its.get(itPoses.get(itOID));
ItemDetailsBean itDetail = itDef.getItemDetails();
itDetail.setOid(itOID);
ItemPresentInFormBean itInForm = new ItemPresentInFormBean();
itInForm.setFormOid(cvOID);
itInForm.setColumnNumber(itColNum);
itInForm.setDefaultValue(dfValue);
itInForm.setItemHeader(itHeader);
itInForm.setLeftItemText(left);
itInForm.setRightItemText(right);
itInForm.setItemSubHeader(itSubheader);
itInForm.setPageNumber(itpgNum);
itInForm.setParentItemOid(parentItemOIDs.get(itPId));
itInForm.setSectionLabel(sectionLabels.get(itSecId));
itInForm.setPhi(phi == false ? "No" : "Yes");
itInForm.setOrderInForm(orderInForm);
itInForm.setShowItem(showItem == true ? "Yes" : "No");
ItemResponseBean itemResponse = new ItemResponseBean();
itemResponse.setResponseLayout(layout);
itemResponse.setResponseType(ResponseType.get(rsTypeId).getName());
itInForm.setItemResponse(itemResponse);
itDetail.getItemPresentInForm().add(itInForm);
inPoses.put(itOID + "-" + cvOID, itDetail.getItemPresentInForm().size() - 1);
}
this.getSCDs(cvIds, its, itPoses, inPoses);
metadata.getFormDefs().add(formDef);
}
use of org.akaza.openclinica.dao.submit.CRFVersionDAO in project OpenClinica by OpenClinica.
the class ImportDataRuleRunnerContainer method initRuleSetsAndTargets.
/**
* Populate importDataTrueRuleSets and variableAndValue.
* Precondition: import data file passed validation which means all OIDs are not empty.
* @param ds
* @param studyBean
* @param subjectDataBean
* @param ruleSetService
*/
@Transactional
public void initRuleSetsAndTargets(DataSource ds, StudyBean studyBean, SubjectDataBean subjectDataBean, RuleSetServiceInterface ruleSetService) {
this.shouldRunRules = this.shouldRunRules == null ? Boolean.FALSE : this.shouldRunRules;
this.importDataTrueRuleSets = this.importDataTrueRuleSets == null ? new ArrayList<RuleSetBean>() : this.importDataTrueRuleSets;
this.variableAndValue = this.variableAndValue == null ? new HashMap<String, String>() : this.variableAndValue;
studyOid = studyBean.getOid();
studySubjectOid = subjectDataBean.getSubjectOID();
StudySubjectBean studySubject = new StudySubjectDAO<String, ArrayList>(ds).findByOid(studySubjectOid);
HashMap<String, StudyEventDefinitionBean> seds = new HashMap<String, StudyEventDefinitionBean>();
HashMap<String, CRFVersionBean> cvs = new HashMap<String, CRFVersionBean>();
ArrayList<StudyEventDataBean> studyEventDataBeans = subjectDataBean.getStudyEventData();
for (StudyEventDataBean studyEventDataBean : studyEventDataBeans) {
String sedOid = studyEventDataBean.getStudyEventOID();
StudyEventDefinitionBean sed;
if (seds.containsKey(sedOid))
sed = seds.get(sedOid);
else {
sed = new StudyEventDefinitionDAO<String, ArrayList>(ds).findByOid(sedOid);
seds.put(sedOid, sed);
}
ArrayList<FormDataBean> formDataBeans = studyEventDataBean.getFormData();
for (FormDataBean formDataBean : formDataBeans) {
String cvOid = formDataBean.getFormOID();
CRFVersionBean crfVersion;
if (cvs.containsKey(cvOid))
crfVersion = cvs.get(cvOid);
else {
crfVersion = new CRFVersionDAO<String, ArrayList>(ds).findByOid(cvOid);
cvs.put(cvOid, crfVersion);
}
String sedOrd = studyEventDataBean.getStudyEventRepeatKey();
Integer sedOrdinal = sedOrd != null && !sedOrd.isEmpty() ? Integer.valueOf(sedOrd) : 1;
StudyEventBean studyEvent = (StudyEventBean) new StudyEventDAO(ds).findByStudySubjectIdAndDefinitionIdAndOrdinal(studySubject.getId(), sed.getId(), sedOrdinal);
List<RuleSetBean> ruleSets = ruleSetService.getRuleSetsByCrfStudyAndStudyEventDefinition(studyBean, sed, crfVersion);
// Set<String> targetItemOids = new HashSet<String>();
if (ruleSets != null && !ruleSets.isEmpty()) {
ruleSets = filterByImportDataEntryTrue(ruleSets);
if (ruleSets != null && !ruleSets.isEmpty()) {
ruleSets = ruleSetService.filterByStatusEqualsAvailable(ruleSets);
ruleSets = ruleSetService.filterRuleSetsByStudyEventOrdinal(ruleSets, studyEvent, crfVersion, sed);
// ruleSets = ruleSetService.filterRuleSetsByHiddenItems(ruleSets, eventCrfBean, crfVersion, new ArrayList<ItemBean>());
shouldRunRules = ruleSetService.shouldRunRulesForRuleSets(ruleSets, Phase.IMPORT);
if (shouldRunRules != null && shouldRunRules == Boolean.TRUE) {
// targetItemOids = collectTargetItemOids(ruleSets);
HashMap<String, Integer> grouped = new HashMap<String, Integer>();
ArrayList<ImportItemGroupDataBean> itemGroupDataBeans = formDataBean.getItemGroupData();
for (ImportItemGroupDataBean itemGroupDataBean : itemGroupDataBeans) {
ArrayList<ImportItemDataBean> itemDataBeans = itemGroupDataBean.getItemData();
for (ImportItemDataBean importItemDataBean : itemDataBeans) {
// if(targetItemOids.contains(importItemDataBean.getItemOID())) {
ItemBean item = new ItemDAO<String, ArrayList>(ds).findByOid(importItemDataBean.getItemOID()).get(0);
String igOid = itemGroupDataBean.getItemGroupOID();
String igOrd = itemGroupDataBean.getItemGroupRepeatKey();
Integer igOrdinal = igOrd != null && !igOrd.isEmpty() ? Integer.valueOf(igOrd) : 1;
// logic from DataEntryServlet method: populateRuleSpecificHashMaps()
if (isRepeatIGForSure(ds, crfVersion.getId(), igOid, igOrdinal, item.getId())) {
String key1 = igOid + "[" + igOrdinal + "]." + importItemDataBean.getItemOID();
String key = igOid + "." + importItemDataBean.getItemOID();
variableAndValue.put(key1, importItemDataBean.getValue());
if (grouped.containsKey(key)) {
grouped.put(key, grouped.get(key) + 1);
} else {
grouped.put(key, 1);
}
} else {
variableAndValue.put(importItemDataBean.getItemOID(), importItemDataBean.getValue());
grouped.put(importItemDataBean.getItemOID(), 1);
}
//
// }
}
}
ruleSets = ruleSetService.solidifyGroupOrdinalsUsingFormProperties(ruleSets, grouped);
importDataTrueRuleSets.addAll(ruleSets);
}
}
}
}
}
}
use of org.akaza.openclinica.dao.submit.CRFVersionDAO in project OpenClinica by OpenClinica.
the class ImportDataHelper method createEventCRF.
public EventCRFBean createEventCRF(HashMap<String, String> importedObject) {
EventCRFBean eventCrfBean = null;
int studyEventId = importedObject.get("study_event_id") == null ? -1 : Integer.parseInt(importedObject.get("study_event_id"));
String crfVersionName = importedObject.get("crf_version_name") == null ? "" : importedObject.get("crf_version_name").toString();
String crfName = importedObject.get("crf_name") == null ? "" : importedObject.get("crf_name").toString();
String eventDefinitionCRFName = importedObject.get("event_definition_crf_name") == null ? "" : importedObject.get("event_definition_crf_name").toString();
String subjectName = importedObject.get("subject_name") == null ? "" : importedObject.get("subject_name").toString();
String studyName = importedObject.get("study_name") == null ? "" : importedObject.get("study_name").toString();
logger.info("found the following: study event id " + studyEventId + ", crf version name " + crfVersionName + ", crf name " + crfName + ", event def crf name " + eventDefinitionCRFName + ", subject name " + subjectName + ", study name " + studyName);
// << tbh
int eventCRFId = 0;
EventCRFDAO eventCrfDao = new EventCRFDAO(sm.getDataSource());
StudyDAO studyDao = new StudyDAO(sm.getDataSource());
StudySubjectDAO studySubjectDao = new StudySubjectDAO(sm.getDataSource());
StudyEventDefinitionDAO studyEventDefinistionDao = new StudyEventDefinitionDAO(sm.getDataSource());
CRFVersionDAO crfVersionDao = new CRFVersionDAO(sm.getDataSource());
StudyEventDAO studyEventDao = new StudyEventDAO(sm.getDataSource());
CRFDAO crfdao = new CRFDAO(sm.getDataSource());
SubjectDAO subjectDao = new SubjectDAO(sm.getDataSource());
StudyBean studyBean = (StudyBean) studyDao.findByName(studyName);
// .findByPK(studyId);
// generate the subject bean first, so that we can have the subject id
// below...
SubjectBean subjectBean = // .findByUniqueIdentifierAndStudy(subjectName,
subjectDao.findByUniqueIdentifier(subjectName);
StudySubjectBean studySubjectBean = studySubjectDao.findBySubjectIdAndStudy(subjectBean.getId(), studyBean);
// .findByLabelAndStudy(subjectName, studyBean);
logger.info("::: found study subject id here: " + studySubjectBean.getId() + " with the following: subject ID " + subjectBean.getId() + " study bean name " + studyBean.getName());
StudyEventBean studyEventBean = (StudyEventBean) studyEventDao.findByPK(studyEventId);
// TODO need to replace, can't really replace
logger.info("found study event status: " + studyEventBean.getStatus().getName());
// [study] event should be scheduled, event crf should be not started
CRFVersionBean crfVersion = (CRFVersionBean) crfVersionDao.findByFullName(crfVersionName, crfName);
// .findByPK(crfVersionId);
// replaced by findByName(name, version)
logger.info("found crf version name here: " + crfVersion.getName());
EntityBean crf = crfdao.findByPK(crfVersion.getCrfId());
logger.info("found crf name here: " + crf.getName());
// trying it again up here since down there doesn't seem to work, tbh
StudyEventDefinitionBean studyEventDefinitionBean = (StudyEventDefinitionBean) studyEventDefinistionDao.findByName(eventDefinitionCRFName);
if (studySubjectBean.getId() <= 0 && studyEventBean.getId() <= 0 && crfVersion.getId() <= 0 && studyBean.getId() <= 0 && studyEventDefinitionBean.getId() <= 0) {
logger.info("Throw an Exception, One of the provided ids is not valid");
}
// >> tbh repeating items:
ArrayList eventCrfBeans = eventCrfDao.findByEventSubjectVersion(studyEventBean, studySubjectBean, crfVersion);
// TODO repeating items here? not yet
if (eventCrfBeans.size() > 1) {
logger.info("found more than one");
}
if (!eventCrfBeans.isEmpty() && eventCrfBeans.size() == 1) {
eventCrfBean = (EventCRFBean) eventCrfBeans.get(0);
logger.info("This EventCrfBean was found");
}
if (!eventCrfBeans.isEmpty() && eventCrfBeans.size() > 1) {
logger.info("Throw a System exception , result should either be 0 or 1");
}
if (eventCrfBean == null) {
StudyBean studyWithSED = studyBean;
if (studyBean.getParentStudyId() > 0) {
studyWithSED = new StudyBean();
studyWithSED.setId(studyBean.getParentStudyId());
}
AuditableEntityBean studyEvent = studyEventDao.findByPKAndStudy(studyEventId, studyWithSED);
if (studyEvent.getId() <= 0) {
logger.info("Hello Exception");
}
eventCrfBean = new EventCRFBean();
// eventCrfBean.setCrfVersion(crfVersion);
if (eventCRFId == 0) {
// ???
if (studyBean.getStudyParameterConfig().getInterviewerNameDefault().equals("blank")) {
eventCrfBean.setInterviewerName("");
} else {
// default will be event's owner name
eventCrfBean.setInterviewerName(studyEventBean.getOwner().getName());
}
if (!studyBean.getStudyParameterConfig().getInterviewDateDefault().equals("blank")) {
if (studyEventBean.getDateStarted() != null) {
// default
eventCrfBean.setDateInterviewed(studyEventBean.getDateStarted());
// date
} else {
// logger.info("evnet start date is null, so date
// interviewed is null");
eventCrfBean.setDateInterviewed(null);
}
} else {
eventCrfBean.setDateInterviewed(null);
}
eventCrfBean.setAnnotations("");
eventCrfBean.setCreatedDate(new Date());
eventCrfBean.setCRFVersionId(crfVersion.getId());
// eventCrfBean.setCrfVersion((CRFVersionBean)crfVersion);
eventCrfBean.setOwner(ub);
// eventCrfBean.setCrf((CRFBean)crf);
eventCrfBean.setStatus(Status.AVAILABLE);
eventCrfBean.setCompletionStatusId(1);
// problem with the line below
eventCrfBean.setStudySubjectId(studySubjectBean.getId());
eventCrfBean.setStudyEventId(studyEventId);
eventCrfBean.setValidateString("");
eventCrfBean.setValidatorAnnotations("");
try {
eventCrfBean = (EventCRFBean) eventCrfDao.create(eventCrfBean);
// TODO review
// eventCrfBean.setCrfVersion((CRFVersionBean)crfVersion);
// eventCrfBean.setCrf((CRFBean)crf);
} catch (Exception ee) {
logger.info(ee.getMessage());
logger.info("throws with crf version id " + crfVersion.getId() + " and study event id " + studyEventId + " study subject id " + studySubjectBean.getId());
}
// note that you need to catch an exception if the numbers are
// bogus, ie you can throw an error here
// however, putting the try catch allows you to pass which is
// also bad
// logger.info("CREATED EVENT CRF");
} else {
// there is an event CRF already, only need to update
// is the status not started???
logger.info("*** already-started event CRF with msg: " + eventCrfBean.getStatus().getName());
if (eventCrfBean.getStatus().equals(Status.PENDING)) {
logger.info("Not Started???");
}
eventCrfBean = (EventCRFBean) eventCrfDao.findByPK(eventCRFId);
eventCrfBean.setCRFVersionId(crfVersion.getId());
eventCrfBean.setUpdatedDate(new Date());
eventCrfBean.setUpdater(ub);
eventCrfBean = (EventCRFBean) eventCrfDao.update(eventCrfBean);
// eventCrfBean.setCrfVersion((CRFVersionBean)crfVersion);
// eventCrfBean.setCrf((CRFBean)crf);
}
if (eventCrfBean.getId() <= 0) {
logger.info("error");
} else {
// TODO change status here, tbh
// 2/08 this part seems to work, tbh
studyEventBean.setSubjectEventStatus(SubjectEventStatus.DATA_ENTRY_STARTED);
studyEventBean.setUpdater(ub);
studyEventBean.setUpdatedDate(new Date());
studyEventDao.update(studyEventBean);
}
}
eventCrfBean.setCrfVersion(crfVersion);
eventCrfBean.setCrf((CRFBean) crf);
// repeating?
return eventCrfBean;
}
use of org.akaza.openclinica.dao.submit.CRFVersionDAO in project OpenClinica by OpenClinica.
the class BatchCRFMigrationServlet method processRequest.
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void processRequest() throws Exception {
FormProcessor fp = new FormProcessor(request);
ArrayList<CRFVersionBean> crfVersionList = null;
ArrayList<StudyEventDefinitionBean> eventList = null;
ArrayList<StudyBean> siteList = null;
// 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);
request.setAttribute("crfName", crf.getName());
ArrayList<CRFVersionBean> versions = (ArrayList<CRFVersionBean>) vdao.findAllByCRF(crfId);
crfVersionList = new ArrayList<CRFVersionBean>();
for (CRFVersionBean version : versions) {
if (version.getStatus().isAvailable())
crfVersionList.add(version);
}
crf.setVersions(crfVersionList);
ArrayList<StudyBean> listOfSites = (ArrayList<StudyBean>) sdao().findAllByParent(currentStudy.getId());
siteList = new ArrayList<StudyBean>();
StudyBean studyBean = new StudyBean();
studyBean.setOid(currentStudy.getOid());
studyBean.setName(resterm.getString("Study_Level_Subjects_Only"));
siteList.add(studyBean);
for (StudyBean s : listOfSites) {
if (s.getStatus().isAvailable()) {
siteList.add(s);
}
}
ArrayList<StudyEventDefinitionBean> listOfDefn = seddao().findAllByStudy(currentStudy);
eventList = new ArrayList<StudyEventDefinitionBean>();
for (StudyEventDefinitionBean d : listOfDefn) {
if (d.getStatus().isAvailable()) {
eventList.add(d);
}
}
// if coming from change crf version -> display message
String crfVersionChangeMsg = fp.getString("isFromCRFVersionBatchChange");
if (crfVersionChangeMsg != null && !crfVersionChangeMsg.equals("")) {
addPageMessage(crfVersionChangeMsg);
}
request.setAttribute("study", currentStudy);
request.setAttribute("siteList", siteList);
request.setAttribute("eventList", eventList);
request.setAttribute(CRF, crf);
forwardPage(Page.BATCH_CRF_MIGRATION);
}
}
use of org.akaza.openclinica.dao.submit.CRFVersionDAO in project OpenClinica by OpenClinica.
the class CreateCRFVersionServlet method processRequest.
@SuppressWarnings("unchecked")
@Override
public void processRequest() throws Exception {
resetPanel();
panel.setStudyInfoShown(true);
CRFDAO cdao = new CRFDAO(sm.getDataSource());
CRFVersionDAO vdao = new CRFVersionDAO(sm.getDataSource());
EventDefinitionCRFDAO edao = new EventDefinitionCRFDAO(sm.getDataSource());
FormProcessor fp = new FormProcessor(request);
// checks which module the requests are from
String module = fp.getString(MODULE);
// keep the module in the session
session.setAttribute(MODULE, module);
request.setAttribute("xformEnabled", CoreResources.getField("xform.enabled"));
String action = request.getParameter("action");
CRFVersionBean version = (CRFVersionBean) session.getAttribute("version");
if (StringUtil.isBlank(action)) {
logger.debug("action is blank");
request.setAttribute("version", version);
forwardPage(Page.CREATE_CRF_VERSION);
} else if ("confirm".equalsIgnoreCase(action)) {
String dir = SQLInitServlet.getField("filePath");
if (!new File(dir).exists()) {
logger.debug("The filePath in datainfo.properties is invalid " + dir);
addPageMessage(resword.getString("the_filepath_you_defined"));
forwardPage(Page.CREATE_CRF_VERSION);
// BWP 01/13/2009 >>
return;
// >>
}
// All the uploaded files will be saved in filePath/crf/original/
String theDir = dir + "crf" + File.separator + "original" + File.separator;
if (!new File(theDir).isDirectory()) {
new File(theDir).mkdirs();
logger.debug("Made the directory " + theDir);
}
// MultipartRequest multi = new MultipartRequest(request, theDir, 50 * 1024 * 1024);
String tempFile = "";
try {
tempFile = uploadFile(theDir, version);
} catch (CRFReadingException crfException) {
Validator.addError(errors, "excel_file", crfException.getMessage());
String msg = crfException.getMessage();
request.setAttribute("formMessages", errors);
forwardPage(Page.CREATE_CRF_VERSION);
return;
} catch (Exception e) {
//
logger.warn("*** Found exception during file upload***");
e.printStackTrace();
}
session.setAttribute("tempFileName", tempFile);
// provided and/or not xls format
if (errors.isEmpty()) {
String s = ((NewCRFBean) session.getAttribute("nib")).getVersionName();
if (s.length() > 255) {
Validator.addError(errors, "excel_file", resword.getString("the_version_CRF_version_more_than_255"));
} else if (s.length() <= 0) {
Validator.addError(errors, "excel_file", resword.getString("the_VERSION_column_was_blank"));
}
version.setName(s);
if (version.getCrfId() == 0) {
version.setCrfId(fp.getInt("crfId"));
}
session.setAttribute("version", version);
}
if (!errors.isEmpty()) {
logger.debug("has validation errors ");
request.setAttribute("formMessages", errors);
forwardPage(Page.CREATE_CRF_VERSION);
} else {
CRFBean crf = (CRFBean) cdao.findByPK(version.getCrfId());
ArrayList versions = (ArrayList) vdao.findAllByCRF(crf.getId());
for (int i = 0; i < versions.size(); i++) {
CRFVersionBean version1 = (CRFVersionBean) versions.get(i);
if (version.getName().equals(version1.getName())) {
// version already exists
logger.debug("Version already exists; owner or not:" + ub.getId() + "," + version1.getOwnerId());
if (ub.getId() != version1.getOwnerId()) {
// not owner
addPageMessage(respage.getString("CRF_version_try_upload_exists_database") + version1.getOwner().getName() + respage.getString("please_contact_owner_to_delete"));
forwardPage(Page.CREATE_CRF_VERSION);
return;
} else {
// owner,
ArrayList definitions = edao.findByDefaultVersion(version1.getId());
if (!definitions.isEmpty()) {
// used in
// definition
request.setAttribute("definitions", definitions);
forwardPage(Page.REMOVE_CRF_VERSION_DEF);
return;
} else {
// not used in definition
int previousVersionId = version1.getId();
version.setId(previousVersionId);
session.setAttribute("version", version);
session.setAttribute("previousVersionId", new Integer(previousVersionId));
forwardPage(Page.REMOVE_CRF_VERSION_CONFIRM);
return;
}
}
}
}
// didn't find same version in the DB,let user upload the excel
// file
logger.debug("didn't find same version in the DB,let user upload the excel file.");
// List excelErr =
// ((ArrayList)request.getAttribute("excelErrors"));
List excelErr = (ArrayList) session.getAttribute("excelErrors");
logger.debug("excelErr.isEmpty()=" + excelErr.isEmpty());
if (excelErr != null && excelErr.isEmpty()) {
addPageMessage(resword.getString("congratulations_your_spreadsheet_no_errors"));
forwardPage(Page.VIEW_SECTION_DATA_ENTRY_PREVIEW);
} else {
logger.debug("OpenClinicaException thrown, forwarding to CREATE_CRF_VERSION_CONFIRM.");
forwardPage(Page.CREATE_CRF_VERSION_CONFIRM);
}
return;
}
} else if ("confirmsql".equalsIgnoreCase(action)) {
NewCRFBean nib = (NewCRFBean) session.getAttribute("nib");
if (nib != null && nib.getItemQueries() != null) {
request.setAttribute("openQueries", nib.getItemQueries());
} else {
request.setAttribute("openQueries", new HashMap());
}
boolean canDelete = false;
// check whether need to delete previous version
Boolean deletePreviousVersion = (Boolean) session.getAttribute("deletePreviousVersion");
Integer previousVersionId = (Integer) session.getAttribute("previousVersionId");
if (deletePreviousVersion != null && deletePreviousVersion.equals(Boolean.TRUE) && previousVersionId != null && previousVersionId.intValue() > 0) {
logger.debug("Need to delete previous version");
// whether we can delete
canDelete = canDeleteVersion(previousVersionId.intValue());
if (!canDelete) {
logger.debug("but cannot delete previous version");
if (session.getAttribute("itemsHaveData") == null && session.getAttribute("eventsForVersion") == null) {
addPageMessage(respage.getString("you_are_not_owner_some_items_cannot_delete"));
}
if (session.getAttribute("itemsHaveData") == null) {
session.setAttribute("itemsHaveData", new ArrayList());
}
if (session.getAttribute("eventsForVersion") == null) {
session.setAttribute("eventsForVersion", new ArrayList());
}
forwardPage(Page.CREATE_CRF_VERSION_NODELETE);
return;
}
ArrayList<ItemBean> nonSharedItems = (ArrayList<ItemBean>) vdao.findNotSharedItemsByVersion(previousVersionId.intValue());
// htaycher: here is the trick we need to put in nib1.setItemQueries()
// update statements for shared items and insert for nonShared that were just deleted 5927
HashMap item_table_statements = new HashMap();
ArrayList<String> temp = new ArrayList<String>(nonSharedItems.size());
for (ItemBean item : nonSharedItems) {
temp.add(item.getName());
item_table_statements.put(item.getName(), nib.getBackupItemQueries().get(item.getName()));
}
for (String item_name : (Set<String>) nib.getItemQueries().keySet()) {
// check if item shared
if (!temp.contains(item_name)) {
item_table_statements.put(item_name, nib.getItemQueries().get(item_name));
}
}
// statements to run
if (!nonSharedItems.isEmpty()) {
request.setAttribute("openQueries", item_table_statements);
}
// htaycher: put all statements in
nib.setItemQueries(item_table_statements);
session.setAttribute("nib", nib);
}
// submit
logger.debug("commit sql");
NewCRFBean nib1 = (NewCRFBean) session.getAttribute("nib");
if (nib1 != null) {
try {
if (canDelete) {
nib1.deleteInsertToDB();
} else {
nib1.insertToDB();
}
request.setAttribute("queries", nib1.getQueries());
// YW << for add a link to "View CRF Version Data Entry".
// For this purpose, CRFVersion id is needed.
// So the latest CRFVersion Id of A CRF Id is it.
CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
ArrayList crfvbeans = new ArrayList();
logger.debug("CRF-ID [" + version.getCrfId() + "]");
int crfVersionId = 0;
String versionOID = null;
if (version.getCrfId() != 0) {
crfvbeans = cvdao.findAllByCRFId(version.getCrfId());
CRFVersionBean cvbean = (CRFVersionBean) crfvbeans.get(crfvbeans.size() - 1);
crfVersionId = cvbean.getId();
versionOID = cvbean.getOid();
for (Iterator iter = crfvbeans.iterator(); iter.hasNext(); ) {
cvbean = (CRFVersionBean) iter.next();
if (crfVersionId < cvbean.getId()) {
crfVersionId = cvbean.getId();
}
}
}
// Not needed; crfVersionId will be autoboxed in Java 5
// this was added for the old CVS java compiler
Integer cfvID = new Integer(crfVersionId);
if (cfvID == 0) {
cfvID = cvdao.findCRFVersionId(nib1.getCrfId(), nib1.getVersionName());
}
CRFVersionBean finalVersion = (CRFVersionBean) cvdao.findByPK(cfvID);
version.setCrfId(nib1.getCrfId());
version.setOid(finalVersion.getOid());
CRFBean crfBean = (CRFBean) cdao.findByPK(version.getCrfId());
crfBean.setUpdatedDate(version.getCreatedDate());
crfBean.setUpdater(ub);
cdao.update(crfBean);
// workaround to get a correct file name below, tbh 06/2008
request.setAttribute("crfVersionId", cfvID);
// YW >>
// return those properties to initial values
session.removeAttribute("version");
session.removeAttribute("eventsForVersion");
session.removeAttribute("itemsHaveData");
session.removeAttribute("nib");
session.removeAttribute("deletePreviousVersion");
session.removeAttribute("previousVersionId");
// save new version spreadsheet
String tempFile = (String) session.getAttribute("tempFileName");
if (tempFile != null) {
logger.debug("*** ^^^ *** saving new version spreadsheet" + tempFile);
try {
String dir = SQLInitServlet.getField("filePath");
File f = new File(dir + "crf" + File.separator + "original" + File.separator + tempFile);
// check to see whether crf/new/ folder exists
// inside, if not,
// creates
// the crf/new/ folder
String finalDir = dir + "crf" + File.separator + "new" + File.separator;
if (!new File(finalDir).isDirectory()) {
logger.debug("need to create folder for excel files" + finalDir);
new File(finalDir).mkdirs();
}
// String newFile = version.getCrfId() +
// version.getName() + ".xls";
String newFile = version.getCrfId() + version.getOid() + ".xls";
logger.debug("*** ^^^ *** new file: " + newFile);
File nf = new File(finalDir + newFile);
logger.debug("copying old file " + f.getName() + " to new file " + nf.getName());
copy(f, nf);
// ?
} catch (IOException ie) {
logger.debug("==============");
addPageMessage(respage.getString("CRF_version_spreadsheet_could_not_saved_contact"));
}
}
session.removeAttribute("tempFileName");
session.removeAttribute(MODULE);
session.removeAttribute("excelErrors");
session.removeAttribute("htmlTab");
forwardPage(Page.CREATE_CRF_VERSION_DONE);
} catch (OpenClinicaException pe) {
logger.debug("--------------");
session.setAttribute("excelErrors", nib1.getErrors());
// request.setAttribute("excelErrors", nib1.getErrors());
forwardPage(Page.CREATE_CRF_VERSION_ERROR);
}
} else {
forwardPage(Page.CREATE_CRF_VERSION);
}
} else if ("delete".equalsIgnoreCase(action)) {
logger.debug("user wants to delete previous version");
List excelErr = (ArrayList) session.getAttribute("excelErrors");
logger.debug("for overwrite CRF version, excelErr.isEmpty()=" + excelErr.isEmpty());
if (excelErr != null && excelErr.isEmpty()) {
addPageMessage(resword.getString("congratulations_your_spreadsheet_no_errors"));
// should be moved to excelErr != null block
session.setAttribute("deletePreviousVersion", Boolean.TRUE);
forwardPage(Page.VIEW_SECTION_DATA_ENTRY_PREVIEW);
} else {
// should be moved to excelErr != null
session.setAttribute("deletePreviousVersion", Boolean.FALSE);
// block
logger.debug("OpenClinicaException thrown, forwarding to CREATE_CRF_VERSION_CONFIRM.");
forwardPage(Page.CREATE_CRF_VERSION_CONFIRM);
}
}
}
Aggregations