Search in sources :

Example 1 with AuditEventDAO

use of org.akaza.openclinica.dao.admin.AuditEventDAO in project OpenClinica by OpenClinica.

the class SignStudySubjectServlet method processRequest.

@Override
public void processRequest() throws Exception {
    SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
    StudySubjectDAO subdao = new StudySubjectDAO(sm.getDataSource());
    FormProcessor fp = new FormProcessor(request);
    String action = fp.getString("action");
    // studySubjectId
    int studySubId = fp.getInt("id", true);
    String module = fp.getString(MODULE);
    request.setAttribute(MODULE, module);
    if (studySubId == 0) {
        addPageMessage(respage.getString("please_choose_a_subject_to_view"));
        forwardPage(Page.LIST_STUDY_SUBJECTS);
        return;
    }
    StudySubjectBean studySub = (StudySubjectBean) subdao.findByPK(studySubId);
    if (!permitSign(studySub, sm.getDataSource())) {
        addPageMessage(respage.getString("subject_event_cannot_signed"));
        // forwardPage(Page.SUBMIT_DATA_SERVLET);
        forwardPage(Page.LIST_STUDY_SUBJECTS_SERVLET);
        // >> changed tbh, 06/2009
        return;
    }
    if (action.equalsIgnoreCase("confirm")) {
        String username = request.getParameter("j_user");
        String password = request.getParameter("j_pass");
        SecurityManager securityManager = ((SecurityManager) SpringServletAccess.getApplicationContext(context).getBean("securityManager"));
        // String encodedUserPass =
        // org.akaza.openclinica.core.SecurityManager
        // .getInstance().encrytPassword(password);
        UserAccountBean ub = (UserAccountBean) session.getAttribute("userBean");
        if (securityManager.verifyPassword(password, getUserDetails()) && ub.getName().equals(username)) {
            if (signSubjectEvents(studySub, sm.getDataSource(), ub)) {
                // Making the StudySubject signed as all the events have
                // become signed.
                studySub.setStatus(Status.SIGNED);
                studySub.setUpdater(ub);
                subdao.update(studySub);
                addPageMessage(respage.getString("subject_event_signed"));
                // forwardPage(Page.SUBMIT_DATA_SERVLET);
                forwardPage(Page.LIST_STUDY_SUBJECTS_SERVLET);
                // >> changed tbh, 06/2009
                return;
            } else {
                addPageMessage(respage.getString("errors_in_submission_see_below"));
                forwardPage(Page.LIST_STUDY_SUBJECTS);
                return;
            }
        } else {
            request.setAttribute("id", new Integer(studySubId).toString());
            addPageMessage(restext.getString("password_match"));
            forwardPage(Page.LIST_STUDY_SUBJECTS);
            return;
        }
    }
    request.setAttribute("studySub", studySub);
    int studyId = studySub.getStudyId();
    int subjectId = studySub.getSubjectId();
    SubjectBean subject = (SubjectBean) sdao.findByPK(subjectId);
    if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2")) {
        Date dob = subject.getDateOfBirth();
        if (dob != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(dob);
            int year = cal.get(Calendar.YEAR);
            request.setAttribute("yearOfBirth", new Integer(year));
        } else {
            request.setAttribute("yearOfBirth", "");
        }
    }
    request.setAttribute("subject", subject);
    StudyDAO studydao = new StudyDAO(sm.getDataSource());
    StudyBean study = (StudyBean) studydao.findByPK(studyId);
    StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());
    study.getStudyParameterConfig().setCollectDob(spvdao.findByHandleAndStudy(studyId, "collectDob").getValue());
    if (study.getParentStudyId() > 0) {
        // this is a site,find parent
        StudyBean parentStudy = (StudyBean) studydao.findByPK(study.getParentStudyId());
        request.setAttribute("parentStudy", parentStudy);
    } else {
        request.setAttribute("parentStudy", new StudyBean());
    }
    ArrayList children = (ArrayList) sdao.findAllChildrenByPK(subjectId);
    request.setAttribute("children", children);
    // find study events
    StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource());
    StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource());
    EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource());
    // find all eventcrfs for each event
    EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource());
    ArrayList<DisplayStudyEventBean> displayEvents = getDisplayStudyEventsForStudySubject(study, studySub, sm.getDataSource(), ub, currentRole);
    DiscrepancyNoteUtil discNoteUtil = new DiscrepancyNoteUtil();
    // Don't filter for now; disc note beans are returned with eventCRFId
    // set
    discNoteUtil.injectParentDiscNotesIntoDisplayStudyEvents(displayEvents, new HashSet(), sm.getDataSource(), 0);
    // All the displaystudyevents for one subject
    request.setAttribute("displayStudyEvents", displayEvents);
    // Set up a Map for the JSP view, mapping the eventCRFId to another Map:
    // the
    // inner Map maps the resolution status name to the number of notes for
    // that
    // eventCRF id, as in New --> 2
    Map discNoteByEventCRFid = discNoteUtil.createDiscNoteMapByEventCRF(displayEvents);
    request.setAttribute("discNoteByEventCRFid", discNoteByEventCRFid);
    EntityBeanTable table = fp.getEntityBeanTable();
    // sort by start date,
    table.setSortingIfNotExplicitlySet(1, false);
    // desc
    ArrayList allEventRows = DisplayStudyEventRow.generateRowsFromBeans(displayEvents);
    String[] columns = { resword.getString("event") + " (" + resword.getString("occurrence_number") + ")", resword.getString("start_date1"), resword.getString("location"), resword.getString("status"), resword.getString("actions"), resword.getString("CRFs_atrib") };
    table.setColumns(new ArrayList(Arrays.asList(columns)));
    table.hideColumnLink(4);
    table.hideColumnLink(5);
    if (!"removed".equalsIgnoreCase(studySub.getStatus().getName()) && !"auto-removed".equalsIgnoreCase(studySub.getStatus().getName())) {
        table.addLink(resword.getString("add_new_event"), "CreateNewStudyEvent?" + CreateNewStudyEventServlet.INPUT_STUDY_SUBJECT_ID_FROM_VIEWSUBJECT + "=" + studySub.getId());
    }
    HashMap args = new HashMap();
    args.put("id", new Integer(studySubId).toString());
    table.setQuery("ViewStudySubject", args);
    table.setRows(allEventRows);
    table.computeDisplay();
    request.setAttribute("table", table);
    SubjectGroupMapDAO sgmdao = new SubjectGroupMapDAO(sm.getDataSource());
    ArrayList groupMaps = (ArrayList) sgmdao.findAllByStudySubject(studySubId);
    request.setAttribute("groups", groupMaps);
    AuditEventDAO aedao = new AuditEventDAO(sm.getDataSource());
    ArrayList logs = aedao.findEventStatusLogByStudySubject(studySubId);
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    ArrayList eventLogs = new ArrayList();
    for (int i = 0; i < logs.size(); i++) {
        AuditEventBean avb = (AuditEventBean) logs.get(i);
        StudyEventAuditBean sea = new StudyEventAuditBean();
        sea.setAuditEvent(avb);
        StudyEventBean se = (StudyEventBean) sedao.findByPK(avb.getEntityId());
        StudyEventDefinitionBean sed = (StudyEventDefinitionBean) seddao.findByPK(se.getStudyEventDefinitionId());
        sea.setDefinition(sed);
        String old = avb.getOldValue().trim();
        try {
            if (!StringUtil.isBlank(old)) {
                SubjectEventStatus oldStatus = SubjectEventStatus.get(new Integer(old).intValue());
                sea.setOldSubjectEventStatus(oldStatus);
            }
            String newValue = avb.getNewValue().trim();
            if (!StringUtil.isBlank(newValue)) {
                SubjectEventStatus newStatus = SubjectEventStatus.get(new Integer(newValue).intValue());
                sea.setNewSubjectEventStatus(newStatus);
            }
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        // logger.warning("^^^ caught NFE");
        }
        UserAccountBean updater = (UserAccountBean) udao.findByPK(avb.getUserId());
        sea.setUpdater(updater);
        eventLogs.add(sea);
    }
    // logger.warning("^^^ finished iteration");
    request.setAttribute("eventLogs", eventLogs);
    forwardPage(Page.SIGN_STUDY_SUBJECT);
}
Also used : SecurityManager(org.akaza.openclinica.core.SecurityManager) HashMap(java.util.HashMap) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) SubjectDAO(org.akaza.openclinica.dao.submit.SubjectDAO) EntityBeanTable(org.akaza.openclinica.web.bean.EntityBeanTable) ArrayList(java.util.ArrayList) StudyEventDefinitionBean(org.akaza.openclinica.bean.managestudy.StudyEventDefinitionBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) DisplayStudyEventBean(org.akaza.openclinica.bean.managestudy.DisplayStudyEventBean) SubjectEventStatus(org.akaza.openclinica.bean.core.SubjectEventStatus) StudyEventDAO(org.akaza.openclinica.dao.managestudy.StudyEventDAO) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) DiscrepancyNoteUtil(org.akaza.openclinica.service.DiscrepancyNoteUtil) AuditEventBean(org.akaza.openclinica.bean.admin.AuditEventBean) StudyEventAuditBean(org.akaza.openclinica.bean.admin.StudyEventAuditBean) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) EventCRFDAO(org.akaza.openclinica.dao.submit.EventCRFDAO) HashSet(java.util.HashSet) SubjectGroupMapDAO(org.akaza.openclinica.dao.submit.SubjectGroupMapDAO) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) Calendar(java.util.Calendar) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) AuditEventDAO(org.akaza.openclinica.dao.admin.AuditEventDAO) EventDefinitionCRFDAO(org.akaza.openclinica.dao.managestudy.EventDefinitionCRFDAO) StudySubjectDAO(org.akaza.openclinica.dao.managestudy.StudySubjectDAO) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) Date(java.util.Date) SubjectBean(org.akaza.openclinica.bean.submit.SubjectBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) DisplayStudyEventBean(org.akaza.openclinica.bean.managestudy.DisplayStudyEventBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) StudyEventDefinitionDAO(org.akaza.openclinica.dao.managestudy.StudyEventDefinitionDAO) StudyParameterValueDAO(org.akaza.openclinica.dao.service.StudyParameterValueDAO) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with AuditEventDAO

use of org.akaza.openclinica.dao.admin.AuditEventDAO in project OpenClinica by OpenClinica.

the class XsltTransformJob method initDependencies.

/**
     * Initializes the dependencies of this job with the components from the Spring application context.
     *
     * @param scheduler
     */
private void initDependencies(Scheduler scheduler) {
    try {
        ApplicationContext ctx = (ApplicationContext) scheduler.getContext().get("applicationContext");
        DataSource dataSource = ctx.getBean(DataSource.class);
        mailSender = ctx.getBean(OpenClinicaMailSender.class);
        auditEventDAO = ctx.getBean(AuditEventDAO.class);
        datasetDao = ctx.getBean(DatasetDAO.class);
        userAccountDao = ctx.getBean(UserAccountDAO.class);
        studyDao = new StudyDAO(dataSource);
        archivedDatasetFileDao = ctx.getBean(ArchivedDatasetFileDAO.class);
        generateFileService = ctx.getBean(GenerateExtractFileService.class);
        odmFileCreation = ctx.getBean(OdmFileCreation.class);
    } catch (SchedulerException e) {
        throw new IllegalStateException("Could not load dependencies from scheduler context", e);
    }
}
Also used : ArchivedDatasetFileDAO(org.akaza.openclinica.dao.extract.ArchivedDatasetFileDAO) ApplicationContext(org.springframework.context.ApplicationContext) GenerateExtractFileService(org.akaza.openclinica.service.extract.GenerateExtractFileService) SchedulerException(org.quartz.SchedulerException) OpenClinicaMailSender(org.akaza.openclinica.core.OpenClinicaMailSender) AuditEventDAO(org.akaza.openclinica.dao.admin.AuditEventDAO) OdmFileCreation(org.akaza.openclinica.service.extract.OdmFileCreation) DatasetDAO(org.akaza.openclinica.dao.extract.DatasetDAO) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) DataSource(javax.sql.DataSource)

Example 3 with AuditEventDAO

use of org.akaza.openclinica.dao.admin.AuditEventDAO in project OpenClinica by OpenClinica.

the class ExampleSpringJob method executeInternal.

@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    // need to generate a Locale so that user beans and other things will
    // generate normally
    Locale locale = new Locale("en-US");
    ResourceBundleProvider.updateLocale(locale);
    ResourceBundle pageMessages = ResourceBundleProvider.getPageMessagesBundle();
    // logger.debug("--");
    // logger.debug("-- executing a job " + message + " at " + new
    // java.util.Date().toString());
    JobDataMap dataMap = context.getMergedJobDataMap();
    SimpleTrigger trigger = (SimpleTrigger) context.getTrigger();
    try {
        ApplicationContext appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
        String studySubjectNumber = ((CoreResources) appContext.getBean("coreResources")).getField("extract.number");
        coreResources = (CoreResources) appContext.getBean("coreResources");
        ruleSetRuleDao = (RuleSetRuleDao) appContext.getBean("ruleSetRuleDao");
        dataSource = (DataSource) appContext.getBean("dataSource");
        mailSender = (OpenClinicaMailSender) appContext.getBean("openClinicaMailSender");
        AuditEventDAO auditEventDAO = new AuditEventDAO(dataSource);
        // Scheduler scheduler = context.getScheduler();
        // JobDetail detail = context.getJobDetail();
        // jobDetailBean = (JobDetailBean) detail;
        /*
             * data map here should coincide with the job data map found in
             * CreateJobExportServlet, with the following code: jobDataMap = new
             * JobDataMap(); jobDataMap.put(DATASET_ID, datasetId);
             * jobDataMap.put(PERIOD, period); jobDataMap.put(EMAIL, email);
             * jobDataMap.put(TAB, tab); jobDataMap.put(CDISC, cdisc);
             * jobDataMap.put(SPSS, spss);
             */
        String alertEmail = dataMap.getString(EMAIL);
        String localeStr = dataMap.getString(LOCALE);
        if (localeStr != null) {
            locale = new Locale(localeStr);
            ResourceBundleProvider.updateLocale(locale);
            pageMessages = ResourceBundleProvider.getPageMessagesBundle();
        }
        int dsId = dataMap.getInt(DATASET_ID);
        String tab = dataMap.getString(TAB);
        String cdisc = dataMap.getString(CDISC);
        String cdisc12 = dataMap.getString(CDISC12);
        if (cdisc12 == null) {
            cdisc12 = "0";
        }
        String cdisc13 = dataMap.getString(CDISC13);
        if (cdisc13 == null) {
            cdisc13 = "0";
        }
        String cdisc13oc = dataMap.getString(CDISC13OC);
        if (cdisc13oc == null) {
            cdisc13oc = "0";
        }
        String spss = dataMap.getString(SPSS);
        int userId = dataMap.getInt(USER_ID);
        int studyId = dataMap.getInt(STUDY_ID);
        // String datasetId = dataMap.getString(DATASET_ID);
        // int dsId = new Integer(datasetId).intValue();
        // String userAcctId = dataMap.getString(USER_ID);
        // int userId = new Integer(userAcctId).intValue();
        // why the flip-flop? if one property is set to 'true' we can
        // see jobs in another screen but all properties have to be
        // strings
        logger.debug("-- found the job: " + dsId + " dataset id");
        // for (Iterator it = dataMap.entrySet().iterator(); it.hasNext();)
        // {
        // java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
        // Object key = entry.getKey();
        // Object value = entry.getValue();
        // // logger.debug("-- found datamap property: " + key.toString() +
        // // " : " + value.toString());
        // }
        HashMap fileName = new HashMap<String, Integer>();
        if (dsId > 0) {
            // trying to not throw an error if there's no dataset id
            DatasetDAO dsdao = new DatasetDAO(dataSource);
            DatasetBean datasetBean = (DatasetBean) dsdao.findByPK(dsId);
            StudyDAO studyDao = new StudyDAO(dataSource);
            UserAccountDAO userAccountDAO = new UserAccountDAO(dataSource);
            // hmm, three lines in the if block DRY?
            String generalFileDir = "";
            String generalFileDirCopy = "";
            String exportFilePath = SQLInitServlet.getField("exportFilePath");
            String pattern = "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator + "HHmmssSSS" + File.separator;
            SimpleDateFormat sdfDir = new SimpleDateFormat(pattern);
            generalFileDir = DATASET_DIR + datasetBean.getId() + File.separator + sdfDir.format(new java.util.Date());
            if (!"".equals(exportFilePath)) {
                generalFileDirCopy = SQLInitServlet.getField("filePath") + exportFilePath + File.separator;
            }
            // logger.debug("-- created the following dir: " +
            // generalFileDir);
            long sysTimeBegin = System.currentTimeMillis();
            // set up the user bean here, tbh
            // logger.debug("-- gen tab file 00");
            userBean = (UserAccountBean) userAccountDAO.findByPK(userId);
            // needs to also be captured by the servlet, tbh
            // logger.debug("-- gen tab file 00");
            generateFileService = new GenerateExtractFileService(dataSource, coreResources, ruleSetRuleDao);
            // logger.debug("-- gen tab file 00");
            // tbh #5796 - covers a bug when the user changes studies, 10/2010
            StudyBean activeStudy = (StudyBean) studyDao.findByPK(studyId);
            StudyBean parentStudy = new StudyBean();
            logger.debug("active study: " + studyId + " parent study: " + activeStudy.getParentStudyId());
            if (activeStudy.getParentStudyId() > 0) {
                // StudyDAO sdao = new StudyDAO(sm.getDataSource());
                parentStudy = (StudyBean) studyDao.findByPK(activeStudy.getParentStudyId());
            } else {
                parentStudy = activeStudy;
            // covers a bug in tab file creation, tbh 01/2009
            }
            logger.debug("-- found extract bean ");
            ExtractBean eb = generateFileService.generateExtractBean(datasetBean, activeStudy, parentStudy);
            MessageFormat mf = new MessageFormat("");
            StringBuffer message = new StringBuffer();
            StringBuffer auditMessage = new StringBuffer();
            // use resource bundle page messages to generate the email, tbh
            // 02/2009
            // message.append(pageMessages.getString("html_email_header_1")
            // + " " + alertEmail +
            // pageMessages.getString("html_email_header_2") + "<br/>");
            message.append("<p>" + pageMessages.getString("email_header_1") + " " + EmailEngine.getAdminEmail() + " " + pageMessages.getString("email_header_2") + " Job Execution " + pageMessages.getString("email_header_3") + "</p>");
            message.append("<P>Dataset: " + datasetBean.getName() + "</P>");
            message.append("<P>Study: " + activeStudy.getName() + "</P>");
            message.append("<p>" + pageMessages.getString("html_email_body_1") + datasetBean.getName() + pageMessages.getString("html_email_body_2") + SQLInitServlet.getField("sysURL") + pageMessages.getString("html_email_body_3") + "</p>");
            // logger.debug("-- gen tab file 00");
            if ("1".equals(tab)) {
                logger.debug("-- gen tab file 01");
                fileName = generateFileService.createTabFile(eb, sysTimeBegin, generalFileDir, datasetBean, activeStudy.getId(), parentStudy.getId(), generalFileDirCopy, userBean);
                message.append("<p>" + pageMessages.getString("html_email_body_4") + " " + getFileNameStr(fileName) + pageMessages.getString("html_email_body_4_5") + SQLInitServlet.getField("sysURL.base") + "AccessFile?fileId=" + getFileIdInt(fileName) + pageMessages.getString("html_email_body_3") + "</p>");
                // MessageFormat mf = new MessageFormat("");
                // mf.applyPattern(pageMessages.getString(
                // "you_can_access_tab_delimited"));
                // Object[] arguments = { getFileIdInt(fileName) };
                // auditMessage.append(mf.format(arguments));
                // auditMessage.append(
                // "You can access your tab-delimited file <a href='AccessFile?fileId="
                // + getFileIdInt(fileName) + "'>here</a>.<br/>");
                auditMessage.append(pageMessages.getString("you_can_access_tab_delimited") + getFileIdInt(fileName) + pageMessages.getString("access_end"));
            }
            if ("1".equals(cdisc)) {
                String odmVersion = "oc1.2";
                fileName = generateFileService.createODMFile(odmVersion, sysTimeBegin, generalFileDir, datasetBean, activeStudy, generalFileDirCopy, eb, activeStudy.getId(), parentStudy.getId(), studySubjectNumber, true, true, true, null, userBean);
                logger.debug("-- gen odm file");
                message.append("<p>" + pageMessages.getString("html_email_body_4") + " " + getFileNameStr(fileName) + pageMessages.getString("html_email_body_4_5") + SQLInitServlet.getField("sysURL.base") + "AccessFile?fileId=" + getFileIdInt(fileName) + pageMessages.getString("html_email_body_3") + "</p>");
                // MessageFormat mf = new MessageFormat("");
                // mf.applyPattern(pageMessages.getString(
                // "you_can_access_odm_12"));
                // Object[] arguments = { getFileIdInt(fileName) };
                // auditMessage.append(mf.format(arguments));
                // auditMessage.append(
                // "You can access your ODM 1.2 w/OpenClinica Extension XML file <a href='AccessFile?fileId="
                // + getFileIdInt(fileName)
                // + "'>here</a>.<br/>");
                auditMessage.append(pageMessages.getString("you_can_access_odm_12") + getFileIdInt(fileName) + pageMessages.getString("access_end"));
            }
            if ("1".equals(cdisc12)) {
                String odmVersion = "1.2";
                fileName = generateFileService.createODMFile(odmVersion, sysTimeBegin, generalFileDir, datasetBean, activeStudy, generalFileDirCopy, eb, activeStudy.getId(), parentStudy.getId(), studySubjectNumber, true, true, true, null, userBean);
                logger.debug("-- gen odm file 1.2 default");
                message.append("<p>" + pageMessages.getString("html_email_body_4") + " " + getFileNameStr(fileName) + pageMessages.getString("html_email_body_4_5") + SQLInitServlet.getField("sysURL.base") + "AccessFile?fileId=" + getFileIdInt(fileName) + pageMessages.getString("html_email_body_3") + "</p>");
                // mf.applyPattern(pageMessages.getString(
                // "you_can_access_odm_12_xml"));
                // Object[] arguments = { getFileIdInt(fileName) };
                // auditMessage.append(mf.format(arguments));
                // // auditMessage.append(
                // "You can access your ODM 1.2 XML file <a href='AccessFile?fileId="
                // + getFileIdInt(fileName) + "'>here</a>.<br/>");
                auditMessage.append(pageMessages.getString("you_can_access_odm_12_xml") + getFileIdInt(fileName) + pageMessages.getString("access_end"));
            }
            if ("1".equals(cdisc13)) {
                String odmVersion = "1.3";
                fileName = generateFileService.createODMFile(odmVersion, sysTimeBegin, generalFileDir, datasetBean, activeStudy, generalFileDirCopy, eb, activeStudy.getId(), parentStudy.getId(), studySubjectNumber, true, true, true, null, userBean);
                logger.debug("-- gen odm file 1.3");
                message.append("<p>" + pageMessages.getString("html_email_body_4") + " " + getFileNameStr(fileName) + pageMessages.getString("html_email_body_4_5") + SQLInitServlet.getField("sysURL.base") + "AccessFile?fileId=" + getFileIdInt(fileName) + pageMessages.getString("html_email_body_3") + "</p>");
                // MessageFormat mf = new MessageFormat("");
                // mf.applyPattern(pageMessages.getString(
                // "you_can_access_odm_13"));
                // Object[] arguments = { getFileIdInt(fileName) };
                // auditMessage.append(mf.format(arguments));
                // auditMessage.append(
                // "You can access your ODM 1.3 XML file <a href='AccessFile?fileId="
                // + getFileIdInt(fileName) + "'>here</a>.<br/>");
                auditMessage.append(pageMessages.getString("you_can_access_odm_13") + getFileIdInt(fileName) + pageMessages.getString("access_end"));
            }
            if ("1".equals(cdisc13oc)) {
                String odmVersion = "oc1.3";
                fileName = generateFileService.createODMFile(odmVersion, sysTimeBegin, generalFileDir, datasetBean, activeStudy, generalFileDirCopy, eb, activeStudy.getId(), parentStudy.getId(), studySubjectNumber, true, true, true, null, userBean);
                logger.debug("-- gen odm file 1.3 oc");
                message.append("<p>" + pageMessages.getString("html_email_body_4") + " " + getFileNameStr(fileName) + pageMessages.getString("html_email_body_4_5") + SQLInitServlet.getField("sysURL.base") + "AccessFile?fileId=" + getFileIdInt(fileName) + pageMessages.getString("html_email_body_3") + "</p>");
                // MessageFormat mf = new MessageFormat("");
                // mf.applyPattern(pageMessages.getString(
                // "you_can_access_odm_13_xml"));
                // Object[] arguments = { getFileIdInt(fileName) };
                // auditMessage.append(mf.format(arguments));
                // auditMessage.append(
                // "You can access your ODM 1.3 w/OpenClinica Extension XML file <a href='AccessFile?fileId="
                // + getFileIdInt(fileName)
                // + "'>here</a>.<br/>");
                auditMessage.append(pageMessages.getString("you_can_access_odm_13_xml") + getFileIdInt(fileName) + pageMessages.getString("access_end"));
            }
            if ("1".equals(spss)) {
                SPSSReportBean answer = new SPSSReportBean();
                fileName = generateFileService.createSPSSFile(datasetBean, eb, activeStudy, parentStudy, sysTimeBegin, generalFileDir, answer, generalFileDirCopy, userBean);
                logger.debug("-- gen spss file");
                message.append("<p>" + pageMessages.getString("html_email_body_4") + " " + getFileNameStr(fileName) + pageMessages.getString("html_email_body_4_5") + SQLInitServlet.getField("sysURL.base") + "AccessFile?fileId=" + getFileIdInt(fileName) + pageMessages.getString("html_email_body_3") + "</p>");
                // MessageFormat mf = new MessageFormat("");
                // mf.applyPattern(pageMessages.getString(
                // "you_can_access_spss"));
                // Object[] arguments = { getFileIdInt(fileName) };
                // auditMessage.append(mf.format(arguments));
                // auditMessage.append(
                // "You can access your SPSS files <a href='AccessFile?fileId="
                // + getFileIdInt(fileName) + "'>here</a>.<br/>");
                auditMessage.append(pageMessages.getString("you_can_access_spss") + getFileIdInt(fileName) + pageMessages.getString("access_end"));
            }
            // wrap up the message, and send the email
            message.append("<p>" + pageMessages.getString("html_email_body_5") + "</P><P>" + pageMessages.getString("email_footer"));
            try {
                mailSender.sendEmail(alertEmail.trim(), pageMessages.getString("job_ran_for") + " " + datasetBean.getName(), message.toString(), true);
            } catch (OpenClinicaSystemException ose) {
            // Do Nothing, In the future we might want to have an email
            // status added to system.
            }
            TriggerBean triggerBean = new TriggerBean();
            triggerBean.setDataset(datasetBean);
            triggerBean.setUserAccount(userBean);
            triggerBean.setFullName(trigger.getKey().getName());
            auditEventDAO.createRowForExtractDataJobSuccess(triggerBean, auditMessage.toString());
        } else {
            TriggerBean triggerBean = new TriggerBean();
            // triggerBean.setDataset(datasetBean);
            triggerBean.setUserAccount(userBean);
            triggerBean.setFullName(trigger.getKey().getName());
            auditEventDAO.createRowForExtractDataJobFailure(triggerBean);
        // logger.debug("-- made it here for some reason, ds id: "
        // + dsId);
        }
    // logger.debug("-- generated file: " + fileNameStr);
    // dataSource.
    } catch (Exception e) {
        // TODO Auto-generated catch block -- ideally should generate a fail
        // msg here, tbh 02/2009
        logger.debug("-- found exception: " + e.getMessage());
        e.printStackTrace();
    }
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) CoreResources(org.akaza.openclinica.dao.core.CoreResources) DatasetBean(org.akaza.openclinica.bean.extract.DatasetBean) ApplicationContext(org.springframework.context.ApplicationContext) SimpleTrigger(org.quartz.SimpleTrigger) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) SPSSReportBean(org.akaza.openclinica.bean.extract.SPSSReportBean) JobDataMap(org.quartz.JobDataMap) GenerateExtractFileService(org.akaza.openclinica.service.extract.GenerateExtractFileService) TriggerBean(org.akaza.openclinica.bean.admin.TriggerBean) MessageFormat(java.text.MessageFormat) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) AuditEventDAO(org.akaza.openclinica.dao.admin.AuditEventDAO) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) DatasetDAO(org.akaza.openclinica.dao.extract.DatasetDAO) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) JobExecutionException(org.quartz.JobExecutionException) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) ExtractBean(org.akaza.openclinica.bean.extract.ExtractBean) ResourceBundle(java.util.ResourceBundle) SimpleDateFormat(java.text.SimpleDateFormat)

Example 4 with AuditEventDAO

use of org.akaza.openclinica.dao.admin.AuditEventDAO 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.getKey().getName());
    String contactEmail = dataMap.getString(EMAIL);
    logger.debug("=== starting to run trigger " + trigger.getKey().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 5 with AuditEventDAO

use of org.akaza.openclinica.dao.admin.AuditEventDAO in project OpenClinica by OpenClinica.

the class ViewSingleJobServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    // changes to this servlet, we now look at group name too, tbh 05/2009
    String triggerName = fp.getString("tname");
    String gName = fp.getString("gname");
    String groupName = "";
    if (gName.equals("") || gName.equals("0")) {
        groupName = XsltTriggerService.TRIGGER_GROUP_NAME;
    } else {
        // if (gName.equals("1")) {
        groupName = TRIGGER_IMPORT_GROUP;
    }
    // << tbh 09/03/2009 #4143
    scheduler = getScheduler();
    Trigger trigger = scheduler.getTrigger(new TriggerKey(triggerName, groupName));
    if (trigger == null) {
        groupName = XsltTriggerService.TRIGGER_GROUP_NAME;
        trigger = scheduler.getTrigger(new TriggerKey(triggerName.trim(), groupName));
    }
    // << tbh 09/03/2009 #4143
    // above is a hack, if we add more trigger groups this will have
    // to be redone
    logger.debug("found trigger name: " + triggerName);
    logger.debug("found group name: " + groupName);
    TriggerBean triggerBean = new TriggerBean();
    JobDataMap dataMap = new JobDataMap();
    AuditEventDAO auditEventDAO = new AuditEventDAO(sm.getDataSource());
    try {
        triggerBean.setFullName(trigger.getKey().getName());
        triggerBean.setPreviousDate(trigger.getPreviousFireTime());
        triggerBean.setNextDate(trigger.getNextFireTime());
        // >> set active here, tbh 10/08/2009
        if (scheduler.getTriggerState(new TriggerKey(triggerName, groupName)) == Trigger.TriggerState.PAUSED) {
            triggerBean.setActive(false);
            logger.debug("setting active to false for trigger: " + trigger.getKey().getName());
        } else {
            triggerBean.setActive(true);
            logger.debug("setting active to TRUE for trigger: " + trigger.getKey().getName());
        }
        // <<
        if (trigger.getDescription() != null) {
            triggerBean.setDescription(trigger.getDescription());
        }
        if (trigger.getJobDataMap().size() > 0) {
            dataMap = trigger.getJobDataMap();
            String contactEmail = dataMap.getString(XsltTriggerService.EMAIL);
            logger.debug("found email: " + contactEmail);
            // int dsId = new Integer(datasetId).intValue();
            if (gName.equals("") || gName.equals("0")) {
                String exportFormat = dataMap.getString(XsltTriggerService.EXPORT_FORMAT);
                String periodToRun = dataMap.getString(ExampleSpringJob.PERIOD);
                // int userId = new Integer(userAcctId).intValue();
                int dsId = dataMap.getInt(ExampleSpringJob.DATASET_ID);
                triggerBean.setExportFormat(exportFormat);
                triggerBean.setPeriodToRun(periodToRun);
                DatasetDAO datasetDAO = new DatasetDAO(sm.getDataSource());
                DatasetBean dataset = (DatasetBean) datasetDAO.findByPK(dsId);
                triggerBean.setDataset(dataset);
            }
            int userId = dataMap.getInt(ExampleSpringJob.USER_ID);
            // need to set information, extract bean, user account bean
            UserAccountDAO userAccountDAO = new UserAccountDAO(sm.getDataSource());
            triggerBean.setContactEmail(contactEmail);
            UserAccountBean userAccount = (UserAccountBean) userAccountDAO.findByPK(userId);
            triggerBean.setUserAccount(userAccount);
            ArrayList<AuditEventBean> triggerLogs = auditEventDAO.findAllByAuditTable(trigger.getKey().getName());
            // set the table for the audit event beans here
            ArrayList allRows = AuditEventRow.generateRowsFromBeans(triggerLogs);
            EntityBeanTable table = fp.getEntityBeanTable();
            String[] columns = { resword.getString("date_and_time"), resword.getString("action_message"), resword.getString("entity_operation"), // resword.getString("study_subject_ID"),
            resword.getString("changes_and_additions"), resword.getString("actions") };
            table.setColumns(new ArrayList(Arrays.asList(columns)));
            table.setAscendingSort(false);
            table.hideColumnLink(1);
            table.hideColumnLink(3);
            table.hideColumnLink(4);
            table.setQuery("ViewSingleJob?tname=" + triggerName + "&gname=" + gName, new HashMap());
            table.setRows(allRows);
            table.computeDisplay();
            request.setAttribute("table", table);
        }
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        logger.debug(" found NPE " + e.getMessage());
        e.printStackTrace();
    }
    // need to show the extract for which this runs, which files, etc
    // in other words the job data map
    request.setAttribute("triggerBean", triggerBean);
    request.setAttribute("groupName", groupName);
    forwardPage(Page.VIEW_SINGLE_JOB);
}
Also used : TriggerBean(org.akaza.openclinica.bean.admin.TriggerBean) JobDataMap(org.quartz.JobDataMap) HashMap(java.util.HashMap) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) EntityBeanTable(org.akaza.openclinica.web.bean.EntityBeanTable) DatasetBean(org.akaza.openclinica.bean.extract.DatasetBean) ArrayList(java.util.ArrayList) AuditEventDAO(org.akaza.openclinica.dao.admin.AuditEventDAO) DatasetDAO(org.akaza.openclinica.dao.extract.DatasetDAO) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) TriggerKey(org.quartz.TriggerKey) Trigger(org.quartz.Trigger) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) AuditEventBean(org.akaza.openclinica.bean.admin.AuditEventBean)

Aggregations

AuditEventDAO (org.akaza.openclinica.dao.admin.AuditEventDAO)7 UserAccountDAO (org.akaza.openclinica.dao.login.UserAccountDAO)7 HashMap (java.util.HashMap)5 UserAccountBean (org.akaza.openclinica.bean.login.UserAccountBean)5 StudyDAO (org.akaza.openclinica.dao.managestudy.StudyDAO)5 ArrayList (java.util.ArrayList)4 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)4 FormProcessor (org.akaza.openclinica.control.form.FormProcessor)4 AuditEventBean (org.akaza.openclinica.bean.admin.AuditEventBean)3 TriggerBean (org.akaza.openclinica.bean.admin.TriggerBean)3 DatasetDAO (org.akaza.openclinica.dao.extract.DatasetDAO)3 EntityBeanTable (org.akaza.openclinica.web.bean.EntityBeanTable)3 JobDataMap (org.quartz.JobDataMap)3 ApplicationContext (org.springframework.context.ApplicationContext)3 Calendar (java.util.Calendar)2 Date (java.util.Date)2 Locale (java.util.Locale)2 StudyEventAuditBean (org.akaza.openclinica.bean.admin.StudyEventAuditBean)2 SubjectEventStatus (org.akaza.openclinica.bean.core.SubjectEventStatus)2 DatasetBean (org.akaza.openclinica.bean.extract.DatasetBean)2