Search in sources :

Example 1 with ItemDataDAO

use of org.akaza.openclinica.dao.submit.ItemDataDAO in project OpenClinica by OpenClinica.

the class ImportSpringJob method executeInternalInTransaction.

protected void executeInternalInTransaction(JobExecutionContext context) {
    locale = new Locale("en-US");
    ResourceBundleProvider.updateLocale(locale);
    respage = ResourceBundleProvider.getPageMessagesBundle();
    resword = ResourceBundleProvider.getWordsBundle();
    triggerService = new TriggerService();
    JobDataMap dataMap = context.getMergedJobDataMap();
    SimpleTrigger trigger = (SimpleTrigger) context.getTrigger();
    TriggerBean triggerBean = new TriggerBean();
    triggerBean.setFullName(trigger.getName());
    String contactEmail = dataMap.getString(EMAIL);
    logger.debug("=== starting to run trigger " + trigger.getName() + " ===");
    try {
        ApplicationContext appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
        dataSource = (DataSource) appContext.getBean("dataSource");
        mailSender = (OpenClinicaMailSender) appContext.getBean("openClinicaMailSender");
        RuleSetServiceInterface ruleSetService = (RuleSetServiceInterface) appContext.getBean("ruleSetService");
        itemDataDao = new ItemDataDAO(dataSource);
        eventCrfDao = new EventCRFDAO(dataSource);
        auditEventDAO = new AuditEventDAO(dataSource);
        int userId = dataMap.getInt(USER_ID);
        UserAccountDAO userAccountDAO = new UserAccountDAO(dataSource);
        UserAccountBean ub = (UserAccountBean) userAccountDAO.findByPK(userId);
        triggerBean.setUserAccount(ub);
        String directory = dataMap.getString(DIRECTORY);
        String studyName = dataMap.getString(STUDY_NAME);
        String studyOid = dataMap.getString(STUDY_OID);
        String localeStr = dataMap.getString(ExampleSpringJob.LOCALE);
        if (localeStr != null) {
            locale = new Locale(localeStr);
            ResourceBundleProvider.updateLocale(locale);
            respage = ResourceBundleProvider.getPageMessagesBundle();
            resword = ResourceBundleProvider.getWordsBundle();
        }
        StudyDAO studyDAO = new StudyDAO(dataSource);
        StudyBean studyBean;
        if (studyOid != null) {
            studyBean = studyDAO.findByOid(studyOid);
        } else {
            studyBean = (StudyBean) studyDAO.findByName(studyName);
        }
        // might also need study id here for the data service?
        File fileDirectory = new File(SQLInitServlet.getField("filePath") + DIR_PATH + File.separator);
        // File fileDirectory = new File(IMPORT_DIR);
        if ("".equals(directory)) {
        // avoid NPEs
        // do nothing here?
        } else {
            // there is a separator at the end of IMPORT_DIR already...
            // fileDirectory = new File(IMPORT_DIR + directory +
            // File.separator);
            fileDirectory = new File(SQLInitServlet.getField("filePath") + DIR_PATH + File.separator + directory + File.separator);
        }
        if (!fileDirectory.isDirectory()) {
            fileDirectory.mkdirs();
        }
        // this is necessary the first time this is run, tbh
        // File destDirectory = new File(IMPORT_DIR_2);
        File destDirectory = new File(SQLInitServlet.getField("filePath") + DEST_DIR + File.separator);
        if (!destDirectory.isDirectory()) {
            destDirectory.mkdirs();
        }
        // look at directory, if there are new files, move them over and
        // read them
        // File fileDirectory = new File(directory);
        String[] files = fileDirectory.list();
        logger.debug("found " + files.length + " files under directory " + SQLInitServlet.getField("filePath") + DIR_PATH + File.separator + directory);
        File[] target = new File[files.length];
        File[] destination = new File[files.length];
        for (int i = 0; i < files.length; i++) {
            // hmm
            if (!new File(fileDirectory + File.separator + files[i]).isDirectory()) {
                File f = new File(fileDirectory + File.separator + files[i]);
                if (f == null || f.getName() == null) {
                    logger.debug("found a null file");
                } else if (f.getName().indexOf(".xml") < 0 && f.getName().indexOf(".XML") < 0) {
                    logger.debug("does not seem to be an xml file");
                // we need a place holder to avoid 'gaps' in the file
                // list
                } else {
                    logger.debug("adding: " + f.getName());
                    // new File(IMPORT_DIR +
                    target[i] = f;
                    // directory +
                    // File.separator + files[i]);
                    // destination[i] = new File(IMPORT_DIR_2 + files[i]);
                    destination[i] = new File(SQLInitServlet.getField("filePath") + DEST_DIR + File.separator + files[i]);
                }
            }
        }
        if (target.length > 0 && destination.length > 0) {
            cutAndPaste(target, destination);
            // @pgawade 28-June-2012: Fix for issue #13964 - Remove the null
            // elements from destination array of files
            // which might be created because of presense of sub-directories
            // or non-xml files under scheduled_data_import directory
            // which are non-usable files for import.
            destination = removeNullElements(destination);
            // do everything else here with 'destination'
            ArrayList<String> auditMessages = processData(destination, dataSource, respage, resword, ub, studyBean, destDirectory, triggerBean, ruleSetService);
            auditEventDAO.createRowForExtractDataJobSuccess(triggerBean, auditMessages.get(1));
            try {
                if (contactEmail != null && !"".equals(contactEmail)) {
                    mailSender.sendEmail(contactEmail, respage.getString("job_ran_for") + " " + triggerBean.getFullName(), generateMsg(auditMessages.get(0), contactEmail), true);
                    logger.debug("email body: " + auditMessages.get(1));
                }
            } catch (OpenClinicaSystemException e) {
                // Do nothing
                logger.error("=== throw an ocse === " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            logger.debug("no real files found");
            auditEventDAO.createRowForExtractDataJobSuccess(triggerBean, respage.getString("job_ran_but_no_files"));
        // no email here, tbh
        }
    // use the business logic to go through each one and import that
    // data
    // check to see if they were imported before?
    // using the four methods:
    // importCRFDataServce.validateStudyMetadata,
    // service.lookupValidationErrors, service.fetchEventCRFBeans(?),
    // and
    // service.generateSummaryStatsBean(for the email we send out later)
    } catch (Exception e) {
        // more detailed reporting here
        logger.error("found a fail exception: " + e.getMessage());
        e.printStackTrace();
        auditEventDAO.createRowForExtractDataJobFailure(triggerBean, e.getMessage());
        try {
            mailSender.sendEmail(contactEmail, respage.getString("job_failure_for") + " " + triggerBean.getFullName(), e.getMessage(), true);
        } catch (OpenClinicaSystemException ose) {
            // Do nothing
            logger.error("=== throw an ocse: " + ose.getMessage());
        }
    }
}
Also used : Locale(java.util.Locale) JobDataMap(org.quartz.JobDataMap) TriggerBean(org.akaza.openclinica.bean.admin.TriggerBean) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) AuditEventDAO(org.akaza.openclinica.dao.admin.AuditEventDAO) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) JobExecutionException(org.quartz.JobExecutionException) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException) RuleSetServiceInterface(org.akaza.openclinica.service.rule.RuleSetServiceInterface) ApplicationContext(org.springframework.context.ApplicationContext) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) SimpleTrigger(org.quartz.SimpleTrigger) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) File(java.io.File) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO)

Example 2 with ItemDataDAO

use of org.akaza.openclinica.dao.submit.ItemDataDAO in project OpenClinica by OpenClinica.

the class DataImportService method submitData.

public ArrayList<String> submitData(ODMContainer odmContainer, DataSource dataSource, StudyBean studyBean, UserAccountBean userBean, List<DisplayItemBeanWrapper> displayItemBeanWrappers, Map<Integer, String> importedCRFStatuses) throws Exception {
    boolean discNotesGenerated = false;
    ItemDataDAO itemDataDao = new ItemDataDAO(dataSource);
    itemDataDao.setFormatDates(false);
    EventCRFDAO eventCrfDao = new EventCRFDAO(dataSource);
    StringBuffer auditMsg = new StringBuffer();
    int eventCrfBeanId = -1;
    EventCRFBean eventCrfBean = null;
    ArrayList<Integer> eventCrfInts;
    ItemDataBean itemDataBean;
    CrfBusinessLogicHelper crfBusinessLogicHelper = new CrfBusinessLogicHelper(dataSource);
    for (DisplayItemBeanWrapper wrapper : displayItemBeanWrappers) {
        boolean resetSDV = false;
        logger.debug("right before we check to make sure it is savable: " + wrapper.isSavable());
        if (wrapper.isSavable()) {
            eventCrfInts = new ArrayList<Integer>();
            logger.debug("wrapper problems found : " + wrapper.getValidationErrors().toString());
            if (wrapper.getDisplayItemBeans() != null && wrapper.getDisplayItemBeans().size() == 0) {
                return getReturnList("fail", "", "No items to submit. Please check your XML.");
            }
            for (DisplayItemBean displayItemBean : wrapper.getDisplayItemBeans()) {
                eventCrfBeanId = displayItemBean.getData().getEventCRFId();
                eventCrfBean = (EventCRFBean) eventCrfDao.findByPK(eventCrfBeanId);
                logger.debug("found value here: " + displayItemBean.getData().getValue());
                logger.debug("found status here: " + eventCrfBean.getStatus().getName());
                itemDataBean = itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(displayItemBean.getItem().getId(), eventCrfBean.getId(), displayItemBean.getData().getOrdinal());
                if (wrapper.isOverwrite() && itemDataBean.getStatus() != null) {
                    if (!itemDataBean.getValue().equals(displayItemBean.getData().getValue()))
                        resetSDV = true;
                    logger.debug("just tried to find item data bean on item name " + displayItemBean.getItem().getName());
                    itemDataBean.setUpdatedDate(new Date());
                    itemDataBean.setUpdater(userBean);
                    itemDataBean.setValue(displayItemBean.getData().getValue());
                    // set status?
                    itemDataDao.update(itemDataBean);
                    logger.debug("updated: " + itemDataBean.getItemId());
                    // need to set pk here in order to create dn
                    displayItemBean.getData().setId(itemDataBean.getId());
                } else {
                    resetSDV = true;
                    itemDataDao.create(displayItemBean.getData());
                    logger.debug("created: " + displayItemBean.getData().getItemId());
                    itemDataBean = itemDataDao.findByItemIdAndEventCRFIdAndOrdinal(displayItemBean.getItem().getId(), eventCrfBean.getId(), displayItemBean.getData().getOrdinal());
                    // logger.debug("found: id " + itemDataBean2.getId() + " name " + itemDataBean2.getName());
                    displayItemBean.getData().setId(itemDataBean.getId());
                }
                ItemDAO idao = new ItemDAO(dataSource);
                ItemBean ibean = (ItemBean) idao.findByPK(displayItemBean.getData().getItemId());
                // logger.debug("*** checking for validation errors: " + ibean.getName());
                String itemOid = displayItemBean.getItem().getOid() + "_" + wrapper.getStudyEventRepeatKey() + "_" + displayItemBean.getData().getOrdinal() + "_" + wrapper.getStudySubjectOid();
                // wrapper.getValidationErrors().toString());
                if (wrapper.getValidationErrors().containsKey(itemOid)) {
                    ArrayList<String> messageList = (ArrayList<String>) wrapper.getValidationErrors().get(itemOid);
                    for (String message : messageList) {
                        DiscrepancyNoteBean parentDn = createDiscrepancyNote(ibean, message, eventCrfBean, displayItemBean, null, userBean, dataSource, studyBean);
                        createDiscrepancyNote(ibean, message, eventCrfBean, displayItemBean, parentDn.getId(), userBean, dataSource, studyBean);
                        discNotesGenerated = true;
                        logger.debug("*** created disc note with message: " + message);
                        auditMsg.append(wrapper.getStudySubjectOid() + ": " + ibean.getOid() + ": " + message + "---");
                    // split by this ? later, tbh
                    // displayItemBean);
                    }
                }
                if (!eventCrfInts.contains(new Integer(eventCrfBean.getId()))) {
                    String eventCRFStatus = importedCRFStatuses.get(new Integer(eventCrfBean.getId()));
                    if (eventCRFStatus != null && eventCRFStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()) && eventCrfBean.getStatus().isAvailable()) {
                        crfBusinessLogicHelper.markCRFStarted(eventCrfBean, userBean, true);
                    } else {
                        crfBusinessLogicHelper.markCRFComplete(eventCrfBean, userBean, true);
                    }
                    eventCrfInts.add(new Integer(eventCrfBean.getId()));
                }
            }
            // Reset the SDV status if item data has been changed or added
            if (eventCrfBean != null && resetSDV)
                eventCrfDao.setSDVStatus(false, userBean.getId(), eventCrfBean.getId());
        }
    }
    if (!discNotesGenerated) {
        return getReturnList("success", "", auditMsg.toString());
    } else {
        return getReturnList("warn", "", auditMsg.toString());
    }
}
Also used : DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) ItemBean(org.akaza.openclinica.bean.submit.ItemBean) ItemDAO(org.akaza.openclinica.dao.submit.ItemDAO) ArrayList(java.util.ArrayList) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) Date(java.util.Date) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) CrfBusinessLogicHelper(org.akaza.openclinica.web.job.CrfBusinessLogicHelper) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) DisplayItemBeanWrapper(org.akaza.openclinica.bean.submit.DisplayItemBeanWrapper)

Example 3 with ItemDataDAO

use of org.akaza.openclinica.dao.submit.ItemDataDAO in project OpenClinica by OpenClinica.

the class CrfBusinessLogicHelper method markCRFComplete.

/**
 * The following methods are for 'mark CRF complete' Note that we will also wrap Study Event status changes in this
 * code, possibly split out in a later release, tbh 06/2008
 *
 * @return
 */
public boolean markCRFComplete(EventCRFBean ecb, UserAccountBean ub, boolean inTransaction) throws Exception {
    DataEntryStage stage = ecb.getStage();
    EventCRFDAO eventCrfDao = new EventCRFDAO(ds);
    ItemDataDAO itemDataDao = new ItemDataDAO(ds);
    StudyDAO sdao = new StudyDAO(ds);
    StudySubjectDAO ssdao = new StudySubjectDAO(ds);
    StudyBean study = sdao.findByStudySubjectId(ecb.getStudySubjectId());
    EventDefinitionCRFBean edcb = getEventDefinitionCrfByStudyEventAndCrfVersion(ecb, study);
    // StudyEventDAO studyEventDao = new StudyEventDAO(ds);
    // StudyEventBean studyEventBean = (StudyEventBean)
    // studyEventDao.findByPK(ecb.getStudyEventId());
    // Status studyEventStatus = studyEventBean.getStatus();
    StudyEventDefinitionDAO studyEventDefinitionDao = new StudyEventDefinitionDAO(ds);
    StudyEventDefinitionBean sedBean = (StudyEventDefinitionBean) studyEventDefinitionDao.findByPK(edcb.getStudyEventDefinitionId());
    CRFDAO crfDao = new CRFDAO(ds);
    ArrayList crfs = (ArrayList) crfDao.findAllActiveByDefinition(sedBean);
    sedBean.setCrfs(crfs);
    // request.setAttribute(TableOfContentsServlet.INPUT_EVENT_CRF_BEAN,
    // ecb);
    // request.setAttribute(INPUT_EVENT_CRF_ID, new
    // Integer(ecb.getId()));
    logger.debug("inout_event_crf_id:" + ecb.getId());
    logger.debug("inout_study_event_def_id:" + sedBean.getId());
    Status newStatus = ecb.getStatus();
    DataEntryStage newStage = ecb.getStage();
    boolean ide = true;
    newStatus = Status.UNAVAILABLE;
    // ecb.setUpdaterId(ub.getId());
    ecb.setUpdater(ub);
    ecb.setUpdatedDate(new Date());
    ecb.setDateCompleted(new Date());
    ecb.setDateValidateCompleted(new Date());
    /*
         * //for the non-reviewed sections, no item data in DB yet, need to //create them if
         * (!isEachSectionReviewedOnce()) { boolean canSave = saveItemsToMarkComplete(newStatus); if (canSave == false){
         * addPageMessage("You may not mark this Event CRF complete, because there are some required entries which have
         * not been filled out."); return false; } }
         */
    ecb.setStatus(newStatus);
    ecb.setStage(newStage);
    ecb = (EventCRFBean) eventCrfDao.update(ecb);
    logger.debug("just updated event crf id: " + ecb.getId());
    // note the below statement only updates the DATES, not the STATUS
    eventCrfDao.markComplete(ecb, ide);
    // update all the items' status to complete
    itemDataDao.updateStatusByEventCRF(ecb, newStatus);
    // change status for study event
    StudyEventDAO sedao = new StudyEventDAO(ds);
    StudyEventBean seb = (StudyEventBean) sedao.findByPK(ecb.getStudyEventId());
    seb.setUpdatedDate(new Date());
    seb.setUpdater(ub);
    // updates with Pauls observation from bug:2488:
    // 1. If there is only one CRF in the event (whether the CRF was
    // required or not), and data was imported for it, the status of the
    // event should be Completed.
    // 
    logger.debug("sed bean get crfs get size: " + sedBean.getCrfs().size());
    logger.debug("edcb get crf id: " + edcb.getCrfId() + " version size? " + edcb.getVersions().size());
    logger.debug("ecb get crf id: " + ecb.getCrf().getId());
    logger.debug("ecb get crf version id: " + ecb.getCRFVersionId());
    if (sedBean.getCrfs().size() == 1) {
        // && edcb.getCrfId() ==
        // ecb.getCrf().getId()) {
        seb.setSubjectEventStatus(SubjectEventStatus.COMPLETED);
        logger.info("just set subj event status to -- COMPLETED --");
    } else // removing sedBean.getCrfs().size() > 1 &&
    if (areAllRequired(seb, study) && !areAllCompleted(seb, study)) {
        seb.setSubjectEventStatus(SubjectEventStatus.DATA_ENTRY_STARTED);
        logger.info("just set subj event status to -- DATAENTRYSTARTED --");
    } else // removing sedBean.getCrfs().size() > 1 &&
    if (!areAllRequired(seb, study)) {
        if (areAllRequiredCompleted(seb, study)) {
            seb.setSubjectEventStatus(SubjectEventStatus.COMPLETED);
            logger.info("just set subj event status to -- 3completed3 --");
        } else {
            seb.setSubjectEventStatus(SubjectEventStatus.DATA_ENTRY_STARTED);
            logger.info("just set subj event status to -- DATAENTRYSTARTED --");
        }
    } else if (noneAreRequired(seb, study)) {
        seb.setSubjectEventStatus(SubjectEventStatus.COMPLETED);
        logger.info("just set subj event status to -- 5completed5 --");
    }
    logger.debug("just set subj event status, final status is " + seb.getSubjectEventStatus().getName());
    logger.debug("final overall status is " + seb.getStatus().getName());
    seb = (StudyEventBean) sedao.update(seb, inTransaction);
    return true;
}
Also used : Status(org.akaza.openclinica.bean.core.Status) SubjectEventStatus(org.akaza.openclinica.bean.core.SubjectEventStatus) EventDefinitionCRFDAO(org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) CRFDAO(org.akaza.openclinica.dao.admin.CRFDAO) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) Date(java.util.Date) DataEntryStage(org.akaza.openclinica.bean.core.DataEntryStage) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) EventDefinitionCRFBean(org.akaza.openclinica.bean.managestudy.EventDefinitionCRFBean) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO)

Example 4 with ItemDataDAO

use of org.akaza.openclinica.dao.submit.ItemDataDAO in project OpenClinica by OpenClinica.

the class ScoreCalculator method redoCalculations.

/**
 * Re-do calculations if funcs include changed item(s) and funcs are not
 * included in the current section. If calculation can not sucessfully redo,
 * old value will be erased and "<erased>" will be saved in database. <br>
 * The parameter 'itemdata' might be overwritten.
 *
 * @param itemGroupSizes
 * @param items
 * @param itemdata
 * @param oldItemdata
 * @param updatedData
 * @param sectionId
 * @return ArrayList<String> which records left_item_text of items who
 *         failed to be updated into database.
 */
public ArrayList<String> redoCalculations(HashMap<String, ItemBean> items, HashMap<String, String> itemdata, TreeSet<String> changedItems, HashMap<Integer, TreeSet<Integer>> itemOrdinals, int sectionId) {
    ArrayList<String> updateFailedItems = new ArrayList<String>();
    if (itemdata == null) {
        logger.error("In ScoreCalculator redoCalculations(), itemdata is empty!");
        errors.add("In ScoreCalculator redoCalculations(), 'itemdata' map is empty!");
        return updateFailedItems;
    }
    if (changedItems == null) {
        logger.error("In ScoreCalculator redoCalculations(), 'changeItems' set is empty!");
        errors.add("In ScoreCalculator redoCalculations(), 'changeItems' set is empty!");
        return updateFailedItems;
    }
    ItemFormMetadataDAO ifmdao = new ItemFormMetadataDAO(sm.getDataSource());
    ItemDAO idao = new ItemDAO(sm.getDataSource());
    ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource());
    NumberFormat nf = NumberFormat.getInstance();
    Parser parser = new Parser(items, itemdata);
    try {
        // for calculation type
        List<ItemFormMetadataBean> derivedItemList = ifmdao.findAllByCRFVersionIdAndResponseTypeId(ecb.getCRFVersionId(), ResponseType.CALCULATION.getId());
        if (derivedItemList.size() > 0) {
            Collections.sort(derivedItemList);
            for (ItemFormMetadataBean ifmb : derivedItemList) {
                if (ifmb.getSectionId() != sectionId) {
                    ItemBean ib = (ItemBean) idao.findByPK(ifmb.getItemId());
                    ResponseOptionBean rob = (ResponseOptionBean) ifmb.getResponseSet().getOptions().get(0);
                    int groupsize = 1;
                    if (itemOrdinals.containsKey(ib.getId())) {
                        groupsize = itemOrdinals.get(ib.getId()).size();
                    }
                    String value = "";
                    ArrayList<ScoreToken> parsedExp = new ArrayList<ScoreToken>();
                    for (int i = 0; i < groupsize; ++i) {
                        ItemDataBean idb = iddao.findByItemIdAndEventCRFIdAndOrdinal(ifmb.getItemId(), ecb.getId(), i + 1);
                        // is there any changed item
                        Parser p = new Parser(items, itemdata);
                        parsedExp = parser.parseScoreTokens(rob.getValue());
                        if (p.isChanged(changedItems, parsedExp)) {
                            StringBuffer err = new StringBuffer();
                            parsedExp = parser.assignVariables(parsedExp, i + 1);
                            // before, set "<erased>"
                            if (parser.getErrors().length() > 0) {
                                err.append(parser.getErrors());
                                if (idb.isActive()) {
                                    idb.setValue("<erased>");
                                    idb.setStatus(Status.UNAVAILABLE);
                                    idb = (ItemDataBean) iddao.update(idb);
                                    if (!idb.isActive()) {
                                        String key = i + 1 > 1 ? ifmb.getLeftItemText() + "_" + (i + 1) : ifmb.getLeftItemText();
                                        updateFailedItems.add(key);
                                    }
                                }
                                parser.setErrors(new StringBuffer());
                            } else // otherwise do calculation
                            {
                                try {
                                    value = ScoreUtil.eval(parsedExp);
                                } catch (ScoreException se) {
                                    logger.error(se.getMessage());
                                }
                                String exp = rob.getValue();
                                exp = exp.replace("##", ",");
                                if (writeToDB(ib, ifmb, idb, exp, value, err)) {
                                    changedItems.add(ib.getName());
                                    itemdata.put(ib.getId() + "_" + (i + 1), idb.getValue());
                                } else {
                                    String key = i + 1 > 1 ? ifmb.getLeftItemText() + "_" + (i + 1) : ifmb.getLeftItemText();
                                    updateFailedItems.add(key);
                                }
                            }
                            if (err.length() > 0) {
                                String key = i + 1 > 1 ? ifmb.getLeftItemText() + "_" + (i + 1) : ifmb.getLeftItemText();
                                errors.add("Item " + key + " contains calculation errors: " + err.toString());
                            }
                        }
                    }
                }
            }
        }
        List<ItemFormMetadataBean> itemList = ifmdao.findAllByCRFVersionIdAndResponseTypeId(ecb.getCRFVersionId(), ResponseType.GROUP_CALCULATION.getId());
        if (itemList.size() > 0) {
            Collections.sort(itemList);
            for (ItemFormMetadataBean ifmb : itemList) {
                if (ifmb.getSectionId() != sectionId) {
                    ItemBean ib = (ItemBean) idao.findByPK(ifmb.getItemId());
                    ResponseOptionBean rob = (ResponseOptionBean) ifmb.getResponseSet().getOptions().get(0);
                    String value = "";
                    Parser p = new Parser(items, itemdata);
                    ArrayList<ScoreToken> parsedExp = parser.parseScoreTokens(rob.getValue());
                    if (p.isChanged(changedItems, parsedExp)) {
                        StringBuffer err = new StringBuffer();
                        parser.setErrors(err);
                        parsedExp = parser.assignVariables(parsedExp, itemOrdinals);
                        ItemDataBean idb = iddao.findByItemIdAndEventCRFIdAndOrdinal(ifmb.getItemId(), ecb.getId(), 1);
                        if (parser.getErrors().length() > 0) {
                            err.append(parser.getErrors());
                            if (idb.isActive()) {
                                idb.setValue("<erased>");
                                idb.setStatus(Status.UNAVAILABLE);
                                idb = (ItemDataBean) iddao.update(idb);
                                if (!idb.isActive()) {
                                    updateFailedItems.add(ifmb.getLeftItemText());
                                }
                            }
                        } else {
                            try {
                                value = ScoreUtil.eval(parsedExp);
                            } catch (ScoreException se) {
                                logger.error(se.getMessage());
                            }
                            String exp = rob.getValue();
                            exp = exp.replace("##", ",");
                            if (writeToDB(ib, ifmb, idb, exp, value, err)) {
                                changedItems.add(ib.getName());
                                itemdata.put(ib.getId() + "_" + idb.getOrdinal(), idb.getValue());
                            } else {
                                updateFailedItems.add(ifmb.getLeftItemText());
                            }
                        }
                        if (err.length() > 0) {
                            errors.add("Item " + ifmb.getLeftItemText() + " contains calculation errors: " + err.toString());
                        }
                    }
                }
            }
        }
    } catch (OpenClinicaException e) {
        logger.error(e.getMessage());
    }
    return updateFailedItems;
}
Also used : DisplayItemBean(org.akaza.openclinica.bean.submit.DisplayItemBean) ItemBean(org.akaza.openclinica.bean.submit.ItemBean) ItemDAO(org.akaza.openclinica.dao.submit.ItemDAO) ArrayList(java.util.ArrayList) ResponseOptionBean(org.akaza.openclinica.bean.submit.ResponseOptionBean) OpenClinicaException(org.akaza.openclinica.exception.OpenClinicaException) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) ScoreException(org.akaza.openclinica.exception.ScoreException) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) ItemFormMetadataDAO(org.akaza.openclinica.dao.submit.ItemFormMetadataDAO) ItemFormMetadataBean(org.akaza.openclinica.bean.submit.ItemFormMetadataBean) NumberFormat(java.text.NumberFormat)

Example 5 with ItemDataDAO

use of org.akaza.openclinica.dao.submit.ItemDataDAO in project OpenClinica by OpenClinica.

the class DeleteEventCRFServlet method processRequest.

@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);
            // OC-12177 added to fix displaying DDE workflow status
            eventCRF.setValidatorId(0);
            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);
        }
    }
}
Also used : StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) ItemDataDAO(org.akaza.openclinica.dao.submit.ItemDataDAO) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) DisplayEventCRFBean(org.akaza.openclinica.bean.submit.DisplayEventCRFBean) ItemDataBean(org.akaza.openclinica.bean.submit.ItemDataBean) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) ItemFormMetadataDAO(org.akaza.openclinica.dao.submit.ItemFormMetadataDAO) EventDefinitionCRFDAO(org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) CRFDAO(org.akaza.openclinica.dao.admin.CRFDAO) DiscrepancyNoteDAO(org.akaza.openclinica.dao.managestudy.DiscrepancyNoteDAO) CRFVersionDAO(org.akaza.openclinica.dao.submit.CRFVersionDAO) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) EventDefinitionCRFDAO(org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) CRFBean(org.akaza.openclinica.bean.admin.CRFBean) DisplayEventCRFBean(org.akaza.openclinica.bean.submit.DisplayEventCRFBean) EventDefinitionCRFBean(org.akaza.openclinica.bean.managestudy.EventDefinitionCRFBean) DisplayEventCRFBean(org.akaza.openclinica.bean.submit.DisplayEventCRFBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO) DiscrepancyNoteBean(org.akaza.openclinica.bean.managestudy.DiscrepancyNoteBean) CRFVersionBean(org.akaza.openclinica.bean.submit.CRFVersionBean) EventDefinitionCRFBean(org.akaza.openclinica.bean.managestudy.EventDefinitionCRFBean) ItemFormMetadataBean(org.akaza.openclinica.bean.submit.ItemFormMetadataBean)

Aggregations

ItemDataDAO (org.akaza.openclinica.dao.submit.ItemDataDAO)83 EventCRFBean (org.akaza.openclinica.bean.submit.EventCRFBean)64 ArrayList (java.util.ArrayList)61 ItemDataBean (org.akaza.openclinica.bean.submit.ItemDataBean)61 EventCRFDAO (org.akaza.openclinica.dao.submit.EventCRFDAO)52 StudyEventDAO (org.akaza.openclinica.dao.managestudy.StudyEventDAO)40 Date (java.util.Date)38 StudyEventBean (org.akaza.openclinica.bean.managestudy.StudyEventBean)37 CRFVersionDAO (org.akaza.openclinica.dao.submit.CRFVersionDAO)31 EventDefinitionCRFDAO (org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO)30 EventDefinitionCRFBean (org.akaza.openclinica.bean.managestudy.EventDefinitionCRFBean)29 StudySubjectDAO (org.akaza.openclinica.dao.managestudy.StudySubjectDAO)29 FormProcessor (org.akaza.openclinica.control.form.FormProcessor)28 CRFDAO (org.akaza.openclinica.dao.admin.CRFDAO)27 StudySubjectBean (org.akaza.openclinica.bean.managestudy.StudySubjectBean)26 StudyEventDefinitionDAO (org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO)24 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)23 StudyDAO (org.akaza.openclinica.dao.managestudy.StudyDAO)22 CRFVersionBean (org.akaza.openclinica.bean.submit.CRFVersionBean)21 ItemBean (org.akaza.openclinica.bean.submit.ItemBean)21