Search in sources :

Example 86 with ResourceBundle

use of java.util.ResourceBundle in project OpenClinica by OpenClinica.

the class HtmlUtils method getCalendarPopupCode.

/**
     * Generates the necessary Javascript code to create a localized
     * CalendarPopup object. It adjusts: First day of the week Day headers Month
     * names Month abbreviations "Today" text
     *
     * @param varname
     *            Javascript variable name for the CalendarPopup object
     * @param divname
     *            <div> name to use for the calendar
     * @return a String with the Javacript code
     * @author Nacho M. Castejon and Jose Martinez Garcia, BAP Health
     */
public static String getCalendarPopupCode(String varname, String divname) {
    StringBuffer out = new StringBuffer();
    out.append("var " + varname + " = new CalendarPopup(\"" + divname + "\");");
    // Following line have been added for year and month navigation combo
    //out.append(varname+".showNavigationDropdowns();");
    int weekStart = Calendar.getInstance(ResourceBundleProvider.getLocale()).getFirstDayOfWeek();
    if (weekStart == Calendar.SUNDAY)
        out.append(varname + ".setWeekStartDay(0);");
    if (weekStart == Calendar.MONDAY)
        out.append(varname + ".setWeekStartDay(1);");
    DateFormatSymbols dfs = new DateFormatSymbols(ResourceBundleProvider.getLocale());
    String[] weekDays = dfs.getShortWeekdays();
    String[] monthNames = dfs.getMonths();
    String[] monthAbbrev = dfs.getShortMonths();
    out.append(varname + ".setDayHeaders(");
    out.append("\"" + weekDays[1].substring(0, 1).toUpperCase(ResourceBundleProvider.getLocale()) + "\"");
    for (int i = 2; i < weekDays.length; i++) out.append(",\"" + weekDays[i].substring(0, 1).toUpperCase(ResourceBundleProvider.getLocale()) + "\"");
    out.append(");");
    out.append(varname + ".setMonthNames(");
    out.append("\"" + capitalize(monthNames[0]) + "\"");
    for (int i = 1; i < monthNames.length - 1; i++) out.append(",\"" + capitalize(monthNames[i]) + "\"");
    out.append(");");
    out.append(varname + ".setMonthAbbreviations(");
    out.append("\"" + capitalize(monthAbbrev[0]) + "\"");
    for (int i = 1; i < monthAbbrev.length - 1; i++) out.append(",\"" + capitalize(monthAbbrev[i]) + "\"");
    out.append(");");
    ResourceBundle reswords = ResourceBundleProvider.getWordsBundle();
    out.append(varname + ".setTodayText(\"" + reswords.getString("today") + "\");");
    return out.toString();
}
Also used : DateFormatSymbols(java.text.DateFormatSymbols) ResourceBundle(java.util.ResourceBundle)

Example 87 with ResourceBundle

use of java.util.ResourceBundle in project OpenClinica by OpenClinica.

the class XsltTransformJob method executeInternal.

@Override
protected void executeInternal(JobExecutionContext context) {
    logger.info("Job " + context.getJobDetail().getDescription() + " started.");
    initDependencies(context.getScheduler());
    // need to generate a Locale for emailing users with i18n
    // TODO make dynamic?
    Locale locale = new Locale("en-US");
    ResourceBundleProvider.updateLocale(locale);
    ResourceBundle pageMessages = ResourceBundleProvider.getPageMessagesBundle();
    List<File> markForDelete = new LinkedList<File>();
    Boolean zipped = true;
    Boolean deleteOld = true;
    Boolean exceptions = false;
    JobDataMap dataMap = context.getMergedJobDataMap();
    String localeStr = dataMap.getString(LOCALE);
    String[] doNotDeleteUntilExtract = new String[4];
    int cnt = dataMap.getInt("count");
    DatasetBean datasetBean = null;
    if (localeStr != null) {
        locale = new Locale(localeStr);
        ResourceBundleProvider.updateLocale(locale);
        pageMessages = ResourceBundleProvider.getPageMessagesBundle();
    }
    // get the file information from the job
    String alertEmail = dataMap.getString(EMAIL);
    java.io.InputStream in = null;
    FileOutputStream endFileStream = null;
    UserAccountBean userBean = null;
    try {
        // init all fields from the data map
        int userAccountId = dataMap.getInt(USER_ID);
        int studyId = dataMap.getInt(STUDY_ID);
        String outputPath = dataMap.getString(POST_FILE_PATH);
        // get all user info, generate xml
        logger.debug("found output path: " + outputPath);
        String generalFileDir = dataMap.getString(XML_FILE_PATH);
        int dsId = dataMap.getInt(DATASET_ID);
        // JN: Change from earlier versions, cannot get static reference as
        // static references don't work. Reason being for example there could be
        // datasetId as a variable which is different for each dataset and
        // that needs to be loaded dynamically
        ExtractPropertyBean epBean = (ExtractPropertyBean) dataMap.get(EP_BEAN);
        File doNotDelDir = new File(generalFileDir);
        if (doNotDelDir.isDirectory()) {
            doNotDeleteUntilExtract = doNotDelDir.list();
        }
        zipped = epBean.getZipFormat();
        deleteOld = epBean.getDeleteOld();
        long sysTimeBegin = System.currentTimeMillis();
        userBean = (UserAccountBean) userAccountDao.findByPK(userAccountId);
        StudyBean currentStudy = (StudyBean) studyDao.findByPK(studyId);
        StudyBean parentStudy = (StudyBean) studyDao.findByPK(currentStudy.getParentStudyId());
        String successMsg = epBean.getSuccessMessage();
        String failureMsg = epBean.getFailureMessage();
        final long start = System.currentTimeMillis();
        datasetBean = (DatasetBean) datasetDao.findByPK(dsId);
        ExtractBean eb = generateFileService.generateExtractBean(datasetBean, currentStudy, parentStudy);
        // generate file directory for file service
        datasetBean.setName(datasetBean.getName().replaceAll(" ", "_"));
        logger.debug("--> job starting: ");
        HashMap<String, Integer> answerMap = odmFileCreation.createODMFile(epBean.getFormat(), sysTimeBegin, generalFileDir, datasetBean, currentStudy, "", eb, currentStudy.getId(), currentStudy.getParentStudyId(), "99", (Boolean) dataMap.get(ZIPPED), false, (Boolean) dataMap.get(DELETE_OLD), epBean.getOdmType(), userBean);
        // won't save a record of the XML to db
        // won't be a zipped file, so that we can submit it for
        // transformation
        // this will have to be toggled by the export data format? no, the
        // export file will have to be zipped/not zipped
        String ODMXMLFileName = "";
        int fId = 0;
        Iterator<Entry<String, Integer>> it = answerMap.entrySet().iterator();
        while (it.hasNext()) {
            JobTerminationMonitor.check();
            Entry<String, Integer> entry = it.next();
            String key = entry.getKey();
            Integer value = entry.getValue();
            // JN: Since there is a logic to
            ODMXMLFileName = key;
            // delete all the intermittent
            // files, this file could be a zip
            // file.
            Integer fileID = value;
            fId = fileID.intValue();
            logger.debug("found " + fId + " and " + ODMXMLFileName);
        }
        logger.info("Finished ODM generation of job " + context.getJobDetail().getDescription());
        // create dirs
        File output = new File(outputPath);
        if (!output.isDirectory()) {
            output.mkdirs();
        }
        int numXLS = epBean.getFileName().length;
        int fileCntr = 0;
        String xmlFilePath = new File(generalFileDir + ODMXMLFileName).toURI().toURL().toExternalForm();
        String endFile = null;
        File oldFilesPath = new File(generalFileDir);
        while (fileCntr < numXLS) {
            JobTerminationMonitor.check();
            String xsltPath = dataMap.getString(XSLT_PATH) + File.separator + epBean.getFileName()[fileCntr];
            in = new java.io.FileInputStream(xsltPath);
            Transformer transformer = transformerFactory.newTransformer(new StreamSource(in));
            endFile = outputPath + File.separator + epBean.getExportFileName()[fileCntr];
            endFileStream = new FileOutputStream(endFile);
            transformer.transform(new StreamSource(xmlFilePath), new StreamResult(endFileStream));
            // JN...CLOSE THE STREAM...HMMMM
            in.close();
            endFileStream.close();
            fileCntr++;
            JobTerminationMonitor.check();
        }
        if (oldFilesPath.isDirectory()) {
            markForDelete = Arrays.asList(oldFilesPath.listFiles());
        // logic to prevent deleting the file being created.
        }
        final double done = setFormat(new Double(System.currentTimeMillis() - start) / 1000);
        logger.info("--> job completed in " + done + " ms");
        // run post processing
        ProcessingFunction function = epBean.getPostProcessing();
        String subject = "";
        String jobName = dataMap.getString(XsltTriggerService.JOB_NAME);
        StringBuffer emailBuffer = new StringBuffer("");
        emailBuffer.append("<p>" + pageMessages.getString("email_header_1") + " " + EmailEngine.getAdminEmail() + " " + pageMessages.getString("email_header_2") + " Job Execution " + pageMessages.getString("email_header_3") + "</p>");
        emailBuffer.append("<P>Dataset: " + datasetBean.getName() + "</P>");
        emailBuffer.append("<P>Study: " + currentStudy.getName() + "</P>");
        if (function != null && function.getClass().equals(org.akaza.openclinica.bean.service.SqlProcessingFunction.class)) {
            String dbUrl = ((org.akaza.openclinica.bean.service.SqlProcessingFunction) function).getDatabaseUrl();
            int lastIndex = dbUrl.lastIndexOf('/');
            String schemaName = dbUrl.substring(lastIndex);
            int HostIndex = dbUrl.substring(0, lastIndex).indexOf("//");
            String Host = dbUrl.substring(HostIndex, lastIndex);
            emailBuffer.append("<P>Database: " + ((org.akaza.openclinica.bean.service.SqlProcessingFunction) function).getDatabaseType() + "</P>");
            emailBuffer.append("<P>Schema: " + schemaName.replace("/", "") + "</P>");
            emailBuffer.append("<P>Host: " + Host.replace("//", "") + "</P>");
        }
        emailBuffer.append("<p>" + pageMessages.getString("html_email_body_1") + datasetBean.getName() + pageMessages.getString("html_email_body_2_2") + "</p>");
        if (function != null) {
            function.setTransformFileName(outputPath + File.separator + dataMap.getString(POST_FILE_NAME));
            function.setODMXMLFileName(endFile);
            function.setXslFileName(dataMap.getString(XSL_FILE_PATH));
            function.setDeleteOld((Boolean) dataMap.get(POST_PROC_DELETE_OLD));
            function.setZip((Boolean) dataMap.get(POST_PROC_ZIP));
            function.setLocation(dataMap.getString(POST_PROC_LOCATION));
            function.setExportFileName(dataMap.getString(POST_PROC_EXPORT_NAME));
            File[] oldFiles = getOldFiles(outputPath, dataMap.getString(POST_PROC_LOCATION));
            function.setOldFiles(oldFiles);
            File[] intermediateFiles = getInterFiles(dataMap.getString(POST_FILE_PATH));
            ProcessingResultType message = function.run();
            // Delete these files only in case when there is no failure
            if (message.getCode().intValue() != 2) {
                deleteOldFiles(intermediateFiles);
            }
            final long done2 = System.currentTimeMillis() - start;
            logger.info("--> postprocessing completed in " + done2 + " ms, found result type " + message.getCode());
            logger.info("--> postprocessing completed in " + done2 + " ms, found result type " + message.getCode());
            if (!function.getClass().equals(org.akaza.openclinica.bean.service.SqlProcessingFunction.class)) {
                String archivedFile = dataMap.getString(POST_FILE_NAME) + "." + function.getFileType();
                // download the zip file
                if (function.isZip()) {
                    archivedFile = archivedFile + ".zip";
                }
                // post processing as well.
                if (function.getClass().equals(org.akaza.openclinica.bean.service.PdfProcessingFunction.class)) {
                    archivedFile = function.getArchivedFileName();
                }
                ArchivedDatasetFileBean fbFinal = generateFileRecord(archivedFile, outputPath, datasetBean, done, new File(outputPath + File.separator + archivedFile).length(), ExportFormatBean.PDFFILE, userAccountId);
                if (successMsg.contains("$linkURL")) {
                    successMsg = successMsg.replace("$linkURL", "<a href=\"" + CoreResources.getField("sysURL.base") + "AccessFile?fileId=" + fbFinal.getId() + "\">" + CoreResources.getField("sysURL.base") + "AccessFile?fileId=" + fbFinal.getId() + " </a>");
                }
                emailBuffer.append("<p>" + successMsg + "</p>");
                logger.debug("System time begining.." + sysTimeBegin);
                logger.debug("System time end.." + System.currentTimeMillis());
                double sysTimeEnd = setFormat((System.currentTimeMillis() - sysTimeBegin) / 1000);
                logger.debug("difference" + sysTimeEnd);
                if (fbFinal != null) {
                    fbFinal.setFileSize((int) bytesToKilo(new File(archivedFile).length()));
                    fbFinal.setRunTime(sysTimeEnd);
                }
            }
            // otherwise don't do it
            if (message.getCode().intValue() == 1) {
                if (jobName != null) {
                    subject = "Success: " + jobName;
                } else {
                    subject = "Success: " + datasetBean.getName();
                }
            } else if (message.getCode().intValue() == 2) {
                if (jobName != null) {
                    subject = "Failure: " + jobName;
                } else {
                    subject = "Failure: " + datasetBean.getName();
                }
                if (failureMsg != null && !failureMsg.isEmpty()) {
                    emailBuffer.append(failureMsg);
                }
                emailBuffer.append("<P>").append(message.getDescription());
                postErrorMessage(message.getDescription(), context);
            } else if (message.getCode().intValue() == 3) {
                if (jobName != null) {
                    subject = "Update: " + jobName;
                } else {
                    subject = "Update: " + datasetBean.getName();
                }
            }
        } else {
            // extract ran but no post-processing - we send an email with
            // success and url to link to
            // generate archived dataset file bean here, and use the id to
            // build the URL
            String archivedFilename = dataMap.getString(POST_FILE_NAME);
            // the zip file
            if (zipped) {
                archivedFilename = dataMap.getString(POST_FILE_NAME) + ".zip";
            }
            // delete old files now
            List<File> intermediateFiles = generateFileService.getOldFiles();
            String[] dontDelFiles = epBean.getDoNotDelFiles();
            //JN: The following is the code for zipping up the files, in case of more than one xsl being provided.
            if (dontDelFiles.length > 1 && zipped) {
                logger.debug("count =====" + cnt + "dontDelFiles length==---" + dontDelFiles.length);
                logger.debug("Entering this?" + cnt + "dontDelFiles" + dontDelFiles);
                String path = outputPath + File.separator;
                logger.debug("path = " + path);
                logger.debug("zipName?? = " + epBean.getZipName());
                String zipName = epBean.getZipName() == null || epBean.getZipName().isEmpty() ? endFile + ".zip" : path + epBean.getZipName() + ".zip";
                archivedFilename = new File(zipName).getName();
                zipAll(path, epBean.getDoNotDelFiles(), zipName);
                String[] tempArray = { archivedFilename };
                dontDelFiles = tempArray;
                endFile = archivedFilename;
            } else if (zipped) {
                markForDelete = zipxmls(markForDelete, endFile);
                endFile = endFile + ".zip";
                String[] temp = new String[dontDelFiles.length];
                int i = 0;
                while (i < dontDelFiles.length) {
                    temp[i] = dontDelFiles[i] + ".zip";
                    i++;
                }
                dontDelFiles = temp;
                // Actually deleting all the xml files which are produced
                // since its zipped
                FilenameFilter xmlFilter = new XMLFileFilter();
                File tempFile = new File(generalFileDir);
                deleteOldFiles(tempFile.listFiles(xmlFilter));
            }
            ArchivedDatasetFileBean fbFinal = generateFileRecord(archivedFilename, outputPath, datasetBean, done, new File(outputPath + File.separator + archivedFilename).length(), ExportFormatBean.TXTFILE, userAccountId);
            if (jobName != null) {
                subject = "Job Ran: " + jobName;
            } else {
                subject = "Job Ran: " + datasetBean.getName();
            }
            if (successMsg == null || successMsg.isEmpty()) {
                logger.info("email buffer??" + emailBuffer);
            } else {
                if (successMsg.contains("$linkURL")) {
                    successMsg = successMsg.replace("$linkURL", "<a href=\"" + CoreResources.getField("sysURL.base") + "AccessFile?fileId=" + fbFinal.getId() + "\">" + CoreResources.getField("sysURL.base") + "AccessFile?fileId=" + fbFinal.getId() + " </a>");
                }
                emailBuffer.append("<p>" + successMsg + "</p>");
            }
            if (deleteOld) {
                deleteIntermFiles(intermediateFiles, endFile, dontDelFiles);
                deleteIntermFiles(markForDelete, endFile, dontDelFiles);
            }
        }
        // email the message to the user
        emailBuffer.append("<p>" + pageMessages.getString("html_email_body_5") + "</p>");
        try {
            // @pgawade 19-April-2011 Log the event into audit_event table
            if (null != dataMap.get("job_type") && ((String) dataMap.get("job_type")).equalsIgnoreCase("exportJob")) {
                String extractName = (String) dataMap.get(XsltTriggerService.JOB_NAME);
                TriggerBean triggerBean = new TriggerBean();
                triggerBean.setDataset(datasetBean);
                triggerBean.setUserAccount(userBean);
                triggerBean.setFullName(extractName);
                String actionMsg = "You may access the " + (String) dataMap.get(XsltTriggerService.EXPORT_FORMAT) + " file by changing your study/site to " + currentStudy.getName() + " and selecting the Export Data icon for " + datasetBean.getName() + " dataset on the View Datasets page.";
                auditEventDAO.createRowForExtractDataJobSuccess(triggerBean, actionMsg);
            }
            mailSender.sendEmail(alertEmail, EmailEngine.getAdminEmail(), subject, emailBuffer.toString(), true);
        } catch (OpenClinicaSystemException ose) {
            // Do Nothing, In the future we might want to have an email
            // status added to system.
            logger.info("exception sending mail: " + ose.getMessage());
            logger.error("exception sending mail: " + ose.getMessage());
        }
        logger.info("just sent email to " + alertEmail + ", from " + EmailEngine.getAdminEmail());
        if (successMsg == null) {
            successMsg = " ";
        }
        postSuccessMessage(successMsg, context);
    } catch (JobInterruptedException e) {
        logger.info("Job was cancelled by the user");
        exceptions = true;
    } catch (TransformerConfigurationException e) {
        sendErrorEmail(e.getMessage(), context, alertEmail);
        postErrorMessage(e.getMessage(), context);
        logger.error("Error executing extract", e);
        exceptions = true;
    } catch (FileNotFoundException e) {
        sendErrorEmail(e.getMessage(), context, alertEmail);
        postErrorMessage(e.getMessage(), context);
        logger.error("Error executing extract", e);
        exceptions = true;
    } catch (TransformerFactoryConfigurationError e) {
        sendErrorEmail(e.getMessage(), context, alertEmail);
        postErrorMessage(e.getMessage(), context);
        logger.error("Error executing extract", e);
        exceptions = true;
    } catch (TransformerException e) {
        sendErrorEmail(e.getMessage(), context, alertEmail);
        postErrorMessage(e.getMessage(), context);
        logger.error("Error executing extract", e);
        exceptions = true;
    } catch (Exception ee) {
        sendErrorEmail(ee.getMessage(), context, alertEmail);
        postErrorMessage(ee.getMessage(), context);
        logger.error("Error executing extract", ee);
        exceptions = true;
        if (null != dataMap.get("job_type") && ((String) dataMap.get("job_type")).equalsIgnoreCase("exportJob")) {
            TriggerBean triggerBean = new TriggerBean();
            triggerBean.setUserAccount(userBean);
            triggerBean.setFullName((String) dataMap.get(XsltTriggerService.JOB_NAME));
            auditEventDAO.createRowForExtractDataJobFailure(triggerBean);
        }
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
                logger.error("Error executing extract", e);
            }
        if (endFileStream != null)
            try {
                endFileStream.close();
            } catch (IOException e) {
                logger.error("Error executing extract", e);
            }
        if (exceptions) {
            logger.debug("EXCEPTIONS... EVEN TEHN DELETING OFF OLD FILES");
            String generalFileDir = dataMap.getString(XML_FILE_PATH);
            File oldFilesPath = new File(generalFileDir);
            if (oldFilesPath.isDirectory()) {
                markForDelete = Arrays.asList(oldFilesPath.listFiles());
            }
            logger.debug("deleting the old files reference from archive dataset");
            if (deleteOld) {
                deleteIntermFiles(markForDelete, "", doNotDeleteUntilExtract);
            }
        }
        if (datasetBean != null)
            resetArchiveDataset(datasetBean.getId());
        logger.info("Job " + context.getJobDetail().getDescription() + " finished.");
    }
}
Also used : Locale(java.util.Locale) DatasetBean(org.akaza.openclinica.bean.extract.DatasetBean) FileNotFoundException(java.io.FileNotFoundException) ExtractPropertyBean(org.akaza.openclinica.bean.extract.ExtractPropertyBean) JobDataMap(org.quartz.JobDataMap) TriggerBean(org.akaza.openclinica.bean.admin.TriggerBean) StreamResult(javax.xml.transform.stream.StreamResult) ProcessingFunction(org.akaza.openclinica.bean.service.ProcessingFunction) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) XMLFileFilter(org.akaza.openclinica.core.util.XMLFileFilter) LinkedList(java.util.LinkedList) ExtractBean(org.akaza.openclinica.bean.extract.ExtractBean) FileOutputStream(java.io.FileOutputStream) ResourceBundle(java.util.ResourceBundle) File(java.io.File) Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) FilenameFilter(java.io.FilenameFilter) ZipEntry(java.util.zip.ZipEntry) Entry(java.util.Map.Entry) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) TransformerException(javax.xml.transform.TransformerException) ArchivedDatasetFileBean(org.akaza.openclinica.bean.extract.ArchivedDatasetFileBean) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) StreamSource(javax.xml.transform.stream.StreamSource) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) TransformerException(javax.xml.transform.TransformerException) SchedulerException(org.quartz.SchedulerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException) ProcessingResultType(org.akaza.openclinica.bean.service.ProcessingResultType)

Example 88 with ResourceBundle

use of java.util.ResourceBundle in project OpenClinica by OpenClinica.

the class RuleRunner method prepareEmailContents.

HashMap<String, String> prepareEmailContents(RuleSetBean ruleSet, RuleSetRuleBean ruleSetRule, StudyBean currentStudy, RuleActionBean ruleAction) {
    // get the Study Event
    StudyEventBean studyEvent = (StudyEventBean) getStudyEventDao().findByPK(Integer.valueOf(getExpressionService().getStudyEventDefenitionOrdninalCurated(ruleSet.getTarget().getValue())));
    // get the Study Subject
    StudySubjectBean studySubject = (StudySubjectBean) getStudySubjectDao().findByPK(studyEvent.getStudySubjectId());
    // get Study/Site Associated with Subject
    StudyBean theStudy = (StudyBean) getStudyDao().findByPK(studySubject.getStudyId());
    String theStudyName, theSiteName = "";
    if (theStudy.getParentStudyId() > 0) {
        StudyBean theParentStudy = (StudyBean) getStudyDao().findByPK(theStudy.getParentStudyId());
        theStudyName = theParentStudy.getName() + " / " + theParentStudy.getIdentifier();
        theSiteName = theStudy.getName() + " / " + theStudy.getIdentifier();
    } else {
        theStudyName = theStudy.getName() + " / " + theStudy.getIdentifier();
    }
    // get the eventCrf & subsequently the CRF Version
    //EventCRFBean eventCrf = (EventCRFBean) getEventCrfDao().findAllByStudyEvent(studyEvent).get(0);
    EventCRFBean eventCrf = (EventCRFBean) getEventCrfDao().findAllByStudyEventAndCrfOrCrfVersionOid(studyEvent, getExpressionService().getCrfOid(ruleSet.getTarget().getValue())).get(0);
    CRFVersionBean crfVersion = (CRFVersionBean) getCrfVersionDao().findByPK(eventCrf.getCRFVersionId());
    CRFBean crf = (CRFBean) getCrfDao().findByPK(crfVersion.getCrfId());
    String studyEventDefinitionName = getExpressionService().getStudyEventDefinitionFromExpression(ruleSet.getTarget().getValue(), currentStudy).getName();
    studyEventDefinitionName += " [" + studyEvent.getSampleOrdinal() + "]";
    String itemGroupName = getExpressionService().getItemGroupNameAndOrdinal(ruleSet.getTarget().getValue());
    ItemGroupBean itemGroupBean = getExpressionService().getItemGroupExpression(ruleSet.getTarget().getValue());
    ItemBean itemBean = getExpressionService().getItemExpression(ruleSet.getTarget().getValue(), itemGroupBean);
    String itemName = itemBean.getName();
    SectionBean section = (SectionBean) getSectionDAO().findByPK(getItemFormMetadataDAO().findByItemIdAndCRFVersionId(itemBean.getId(), crfVersion.getId()).getSectionId());
    StringBuffer sb = new StringBuffer();
    ResourceBundle respage = ResourceBundleProvider.getPageMessagesBundle();
    sb.append(respage.getString("email_header_1"));
    sb.append(" " + contextPath + " ");
    sb.append(respage.getString("email_header_2"));
    sb.append(" '" + currentStudy.getName() + "' ");
    sb.append(respage.getString("email_header_3"));
    sb.append(" \n\n ");
    sb.append(respage.getString("email_body_1") + " " + theStudyName + " \n ");
    sb.append(respage.getString("email_body_1_a") + " " + theSiteName + " \n ");
    sb.append(respage.getString("email_body_2") + " " + studySubject.getName() + " \n ");
    sb.append(respage.getString("email_body_3") + " " + studyEventDefinitionName + " \n ");
    sb.append(respage.getString("email_body_4") + " " + crf.getName() + " " + crfVersion.getName() + " \n ");
    sb.append(respage.getString("email_body_5") + " " + section.getTitle() + " \n ");
    sb.append(respage.getString("email_body_6") + " " + itemGroupName + " \n ");
    sb.append(respage.getString("email_body_7") + " " + itemName + " \n ");
    sb.append(respage.getString("email_body_8") + " " + ruleAction.getCuratedMessage() + " \n ");
    sb.append(" \n\n ");
    sb.append(respage.getString("email_body_9"));
    sb.append(" " + contextPath + " ");
    sb.append(respage.getString("email_body_10"));
    sb.append(" \n");
    requestURLMinusServletPath = requestURLMinusServletPath == null ? "" : requestURLMinusServletPath;
    sb.append(requestURLMinusServletPath + "/ViewSectionDataEntry?ecId=" + eventCrf.getId() + "&sectionId=" + section.getId() + "&tabId=" + section.getOrdinal());
    // &eventId="+ studyEvent.getId());
    sb.append("\n\n");
    sb.append(respage.getString("email_footer"));
    String subject = contextPath + " - [" + currentStudy.getName() + "] ";
    String ruleSummary = ruleAction.getSummary() != null ? ruleAction.getSummary() : "";
    String message = ruleSummary.length() < 20 ? ruleSummary : ruleSummary.substring(0, 20) + " ... ";
    subject += message;
    HashMap<String, String> emailContents = new HashMap<String, String>();
    emailContents.put("body", sb.toString());
    emailContents.put("subject", subject);
    return emailContents;
}
Also used : ItemBean(org.akaza.openclinica.bean.submit.ItemBean) HashMap(java.util.HashMap) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) StudyEventBean(org.akaza.openclinica.bean.managestudy.StudyEventBean) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) CRFBean(org.akaza.openclinica.bean.admin.CRFBean) SectionBean(org.akaza.openclinica.bean.submit.SectionBean) EventCRFBean(org.akaza.openclinica.bean.submit.EventCRFBean) StudySubjectBean(org.akaza.openclinica.bean.managestudy.StudySubjectBean) CRFVersionBean(org.akaza.openclinica.bean.submit.CRFVersionBean) ResourceBundle(java.util.ResourceBundle) ItemGroupBean(org.akaza.openclinica.bean.submit.ItemGroupBean)

Example 89 with ResourceBundle

use of java.util.ResourceBundle in project OpenClinica by OpenClinica.

the class SetUserRoleServlet method processRequest.

@Override
public void processRequest() throws Exception {
    UserAccountDAO udao = new UserAccountDAO(sm.getDataSource());
    StudyDAO sdao = new StudyDAO(sm.getDataSource());
    FormProcessor fp = new FormProcessor(request);
    int userId = fp.getInt("userId");
    if (userId == 0) {
        addPageMessage(respage.getString("please_choose_a_user_to_set_role_for"));
        forwardPage(Page.LIST_USER_ACCOUNTS_SERVLET);
    } else {
        String action = request.getParameter("action");
        UserAccountBean user = (UserAccountBean) udao.findByPK(userId);
        ArrayList studies = (ArrayList) sdao.findAll();
        ArrayList studiesHaveRole = (ArrayList) sdao.findAllByUser(user.getName());
        studies.removeAll(studiesHaveRole);
        HashSet<StudyBean> studiesNotHaveRole = new HashSet<StudyBean>();
        HashSet<StudyBean> sitesNotHaveRole = new HashSet<StudyBean>();
        for (int i = 0; i < studies.size(); i++) {
            StudyBean study1 = (StudyBean) studies.get(i);
            // TODO: implement equal() according to id
            boolean hasStudy = false;
            for (int j = 0; j < studiesHaveRole.size(); j++) {
                StudyBean study2 = (StudyBean) studiesHaveRole.get(j);
                if (study2.getId() == study1.getId()) {
                    hasStudy = true;
                    break;
                }
            }
            if (!hasStudy) {
                // YW 11-19-2007 <<
                if (study1.getParentStudyId() > 0) {
                    sitesNotHaveRole.add(study1);
                } else {
                    studiesNotHaveRole.add(study1);
                }
            // YW >>
            }
        }
        Map roleMap = new LinkedHashMap();
        for (Iterator it = getRoles().iterator(); it.hasNext(); ) {
            Role role = (Role) it.next();
            // I added the below if statement , to exclude displaying on study level the newly added 'ReseachAssisstant2' role by default.
            if (role.getId() != 7)
                roleMap.put(role.getId(), role.getDescription());
        }
        Boolean changeRoles = request.getParameter("changeRoles") == null ? false : Boolean.parseBoolean(request.getParameter("changeRoles"));
        int studyId = fp.getInt("studyId");
        if (changeRoles) {
            StudyBean study = (StudyBean) sdao.findByPK(studyId);
            roleMap = new LinkedHashMap();
            ResourceBundle resterm = org.akaza.openclinica.i18n.util.ResourceBundleProvider.getTermsBundle();
            if (study.getParentStudyId() > 0) {
                for (Iterator it = getRoles().iterator(); it.hasNext(); ) {
                    Role role = (Role) it.next();
                    switch(role.getId()) {
                        //                            break;
                        case 4:
                            roleMap.put(role.getId(), resterm.getString("site_investigator").trim());
                            break;
                        case 5:
                            roleMap.put(role.getId(), resterm.getString("site_Data_Entry_Person").trim());
                            break;
                        case 6:
                            roleMap.put(role.getId(), resterm.getString("site_monitor").trim());
                            break;
                        case 7:
                            roleMap.put(role.getId(), resterm.getString("site_Data_Entry_Person2").trim());
                            break;
                        default:
                    }
                }
            } else {
                for (Iterator it = getRoles().iterator(); it.hasNext(); ) {
                    Role role = (Role) it.next();
                    switch(role.getId()) {
                        case 2:
                            roleMap.put(role.getId(), resterm.getString("Study_Coordinator").trim());
                            break;
                        case 3:
                            roleMap.put(role.getId(), resterm.getString("Study_Director").trim());
                            break;
                        case 4:
                            roleMap.put(role.getId(), resterm.getString("Investigator").trim());
                            break;
                        case 5:
                            roleMap.put(role.getId(), resterm.getString("Data_Entry_Person").trim());
                            break;
                        case 6:
                            roleMap.put(role.getId(), resterm.getString("Monitor").trim());
                            break;
                        default:
                    }
                }
            }
        } else {
            if (currentStudy.getParentStudyId() > 0) {
                roleMap.remove(Role.COORDINATOR.getId());
                roleMap.remove(Role.STUDYDIRECTOR.getId());
            }
        }
        request.setAttribute("roles", roleMap);
        request.setAttribute("studyId", studyId);
        if ("confirm".equalsIgnoreCase(action) || changeRoles) {
            // YW 11-19-2007 << re-order studiesNotHaveRole so that sites
            // under their studies;
            ArrayList finalStudiesNotHaveRole = new ArrayList();
            Iterator iter_study = studiesNotHaveRole.iterator();
            while (iter_study.hasNext()) {
                StudyBean s = (StudyBean) iter_study.next();
                finalStudiesNotHaveRole.add(s);
                Iterator iter_site = sitesNotHaveRole.iterator();
                while (iter_site.hasNext()) {
                    StudyBean site = (StudyBean) iter_site.next();
                    if (site.getParentStudyId() == s.getId()) {
                        finalStudiesNotHaveRole.add(site);
                    }
                }
            }
            // YW >>
            request.setAttribute("user", user);
            request.setAttribute("studies", finalStudiesNotHaveRole);
            StudyUserRoleBean uRole = new StudyUserRoleBean();
            uRole.setFirstName(user.getFirstName());
            uRole.setLastName(user.getLastName());
            uRole.setUserName(user.getName());
            request.setAttribute("uRole", uRole);
            //                ArrayList roles = Role.toArrayList();
            //                roles.remove(Role.ADMIN); // admin is not a user role, only used for tomcat
            //                if (currentStudy.getParentStudyId() > 0) {
            //                    roles.remove(Role.COORDINATOR);
            //                    roles.remove(Role.STUDYDIRECTOR);
            //                }
            //                request.setAttribute("roles", roles);
            forwardPage(Page.SET_USER_ROLE);
        } else {
            // set role
            String userName = fp.getString("name");
            studyId = fp.getInt("studyId");
            StudyBean userStudy = (StudyBean) sdao.findByPK(studyId);
            int roleId = fp.getInt("roleId");
            // new user role
            StudyUserRoleBean sur = new StudyUserRoleBean();
            sur.setName(userName);
            sur.setRole(Role.get(roleId));
            sur.setStudyId(studyId);
            sur.setStudyName(userStudy.getName());
            sur.setStatus(Status.AVAILABLE);
            sur.setOwner(ub);
            sur.setCreatedDate(new Date());
            if (studyId > 0) {
                udao.createStudyUserRole(user, sur);
                addPageMessage(user.getFirstName() + " " + user.getLastName() + " (" + resword.getString("username") + ": " + user.getName() + ") " + respage.getString("has_been_granted_the_role") + " \"" + sur.getRole().getDescription() + "\" " + respage.getString("in_the_study_site") + " " + userStudy.getName() + ".");
            }
            ArrayList<String> pMessage = (ArrayList<String>) request.getAttribute(SecureController.PAGE_MESSAGE);
            String url = response.encodeRedirectURL("ListUserAccounts" + "?alertmessage=" + URLEncoder.encode(pMessage.get(0), "UTF-8"));
            response.sendRedirect(url);
        //   forwardPage(Page.LIST_USER_ACCOUNTS_SERVLET);
        }
    }
}
Also used : FormProcessor(org.akaza.openclinica.control.form.FormProcessor) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) StudyUserRoleBean(org.akaza.openclinica.bean.login.StudyUserRoleBean) ArrayList(java.util.ArrayList) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap) Role(org.akaza.openclinica.bean.core.Role) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) Iterator(java.util.Iterator) ResourceBundle(java.util.ResourceBundle) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 90 with ResourceBundle

use of java.util.ResourceBundle in project OpenClinica by OpenClinica.

the class DiscrepancyNoteOutputServlet method getDateFormat.

private String getDateFormat() {
    Locale locale = LocaleResolver.getLocale(request);
    ResourceBundle resformat = ResourceBundleProvider.getFormatBundle(locale);
    return resformat.getString("date_format_string");
}
Also used : Locale(java.util.Locale) ResourceBundle(java.util.ResourceBundle)

Aggregations

ResourceBundle (java.util.ResourceBundle)1189 Locale (java.util.Locale)180 MissingResourceException (java.util.MissingResourceException)150 Test (org.junit.Test)100 ArrayList (java.util.ArrayList)71 HashMap (java.util.HashMap)70 IOException (java.io.IOException)67 PropertyResourceBundle (java.util.PropertyResourceBundle)56 URL (java.net.URL)48 File (java.io.File)47 Map (java.util.Map)45 InputStream (java.io.InputStream)43 Enumeration (java.util.Enumeration)34 HashSet (java.util.HashSet)30 Test (org.junit.jupiter.api.Test)30 ActionMessage (org.apache.struts.action.ActionMessage)29 MessageFormat (java.text.MessageFormat)28 ListResourceBundle (java.util.ListResourceBundle)28 Set (java.util.Set)26 Preferences (java.util.prefs.Preferences)21