Search in sources :

Example 1 with TransformerFactoryConfigurationError

use of javax.xml.transform.TransformerFactoryConfigurationError in project camel by apache.

the class XmlConverter method createTransformerFactory.

public TransformerFactory createTransformerFactory() {
    TransformerFactory factory;
    TransformerFactoryConfigurationError cause;
    try {
        factory = TransformerFactory.newInstance();
    } catch (TransformerFactoryConfigurationError e) {
        cause = e;
        // try fallback from the JDK
        try {
            LOG.debug("Cannot create/load TransformerFactory due: {}. Will attempt to use JDK fallback TransformerFactory: {}", e.getMessage(), JDK_FALLBACK_TRANSFORMER_FACTORY);
            factory = TransformerFactory.newInstance(JDK_FALLBACK_TRANSFORMER_FACTORY, null);
        } catch (Throwable t) {
            // okay we cannot load fallback then throw original exception
            throw cause;
        }
    }
    LOG.debug("Created TransformerFactory: {}", factory);
    // Enable the Security feature by default
    try {
        factory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (TransformerConfigurationException e) {
        LOG.warn("TransformerFactory doesn't support the feature {} with value {}, due to {}.", new Object[] { javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, "true", e });
    }
    factory.setErrorListener(new XmlErrorListener());
    configureSaxonTransformerFactory(factory);
    return factory;
}
Also used : TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) TransformerFactory(javax.xml.transform.TransformerFactory) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException)

Example 2 with TransformerFactoryConfigurationError

use of javax.xml.transform.TransformerFactoryConfigurationError in project hudson-2.x by hudson.

the class WebAppMain method contextInitialized.

/**
     * Creates the sole instance of {@link Hudson} and register it to the {@link ServletContext}.
     */
public void contextInitialized(ServletContextEvent event) {
    try {
        final ServletContext context = event.getServletContext();
        // Install the current servlet context, unless its already been set
        final WebAppController controller = WebAppController.get();
        try {
            // Attempt to set the context
            controller.setContext(context);
        } catch (IllegalStateException e) {
        // context already set ignore
        }
        // Setup the default install strategy if not already configured
        try {
            controller.setInstallStrategy(new DefaultInstallStrategy());
        } catch (IllegalStateException e) {
        // strategy already set ignore
        }
        // use the current request to determine the language
        LocaleProvider.setProvider(new LocaleProvider() {

            public Locale get() {
                Locale locale = null;
                StaplerRequest req = Stapler.getCurrentRequest();
                if (req != null)
                    locale = req.getLocale();
                if (locale == null)
                    locale = Locale.getDefault();
                return locale;
            }
        });
        // quick check to see if we (seem to) have enough permissions to run. (see #719)
        JVM jvm;
        try {
            jvm = new JVM();
            new URLClassLoader(new URL[0], getClass().getClassLoader());
        } catch (SecurityException e) {
            controller.install(new InsufficientPermissionDetected(e));
            return;
        }
        try {
            // remove Sun PKCS11 provider if present. See http://wiki.hudson-ci.org/display/HUDSON/Solaris+Issue+6276483
            Security.removeProvider("SunPKCS11-Solaris");
        } catch (SecurityException e) {
        // ignore this error.
        }
        installLogger();
        File dir = getHomeDir(event);
        try {
            dir = dir.getCanonicalFile();
        } catch (IOException e) {
            dir = dir.getAbsoluteFile();
        }
        final File home = dir;
        home.mkdirs();
        LOGGER.info("Home directory: " + home);
        // check that home exists (as mkdirs could have failed silently), otherwise throw a meaningful error
        if (!home.exists()) {
            controller.install(new NoHomeDir(home));
            return;
        }
        // make sure that we are using XStream in the "enhanced" (JVM-specific) mode
        if (jvm.bestReflectionProvider().getClass() == PureJavaReflectionProvider.class) {
            // nope
            controller.install(new IncompatibleVMDetected());
            return;
        }
        // make sure this is servlet 2.4 container or above
        try {
            ServletResponse.class.getMethod("setCharacterEncoding", String.class);
        } catch (NoSuchMethodException e) {
            controller.install(new IncompatibleServletVersionDetected(ServletResponse.class));
            return;
        }
        // make sure that we see Ant 1.7
        try {
            FileSet.class.getMethod("getDirectoryScanner");
        } catch (NoSuchMethodException e) {
            controller.install(new IncompatibleAntVersionDetected(FileSet.class));
            return;
        }
        // make sure AWT is functioning, or else JFreeChart won't even load.
        if (ChartUtil.awtProblemCause != null) {
            controller.install(new AWTProblem(ChartUtil.awtProblemCause));
            return;
        }
        // check that and report an error
        try {
            File f = File.createTempFile("test", "test");
            f.delete();
        } catch (IOException e) {
            controller.install(new NoTempDir(e));
            return;
        }
        // try to correct it
        try {
            TransformerFactory.newInstance();
        // if this works we are all happy
        } catch (TransformerFactoryConfigurationError x) {
            // no it didn't.
            LOGGER.log(Level.WARNING, "XSLT not configured correctly. Hudson will try to fix this. See http://issues.apache.org/bugzilla/show_bug.cgi?id=40895 for more details", x);
            System.setProperty(TransformerFactory.class.getName(), "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
            try {
                TransformerFactory.newInstance();
                LOGGER.info("XSLT is set to the JAXP RI in JRE");
            } catch (TransformerFactoryConfigurationError y) {
                LOGGER.log(Level.SEVERE, "Failed to correct the problem.");
            }
        }
        installExpressionFactory(event);
        controller.install(new HudsonIsLoading());
        new Thread("hudson initialization thread") {

            @Override
            public void run() {
                try {
                    // Creating of the god object performs most of the booting muck
                    Hudson hudson = new Hudson(home, context);
                    // once its done, hook up to stapler and things should be ready to go
                    controller.install(hudson);
                    // trigger the loading of changelogs in the background,
                    // but give the system 10 seconds so that the first page
                    // can be served quickly
                    Trigger.timer.schedule(new SafeTimerTask() {

                        public void doRun() {
                            User.getUnknown().getBuilds();
                        }
                    }, 1000 * 10);
                } catch (Error e) {
                    LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
                    controller.install(new HudsonFailedToLoad(e));
                    throw e;
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
                    controller.install(new HudsonFailedToLoad(e));
                }
            }
        }.start();
    } catch (Error e) {
        LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
        throw e;
    } catch (RuntimeException e) {
        LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
        throw e;
    }
}
Also used : Locale(java.util.Locale) JVM(com.thoughtworks.xstream.core.JVM) IncompatibleAntVersionDetected(hudson.util.IncompatibleAntVersionDetected) StaplerRequest(org.kohsuke.stapler.StaplerRequest) NoHomeDir(hudson.util.NoHomeDir) ServletContext(javax.servlet.ServletContext) HudsonFailedToLoad(hudson.util.HudsonFailedToLoad) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) IncompatibleVMDetected(hudson.util.IncompatibleVMDetected) Hudson(hudson.model.Hudson) InsufficientPermissionDetected(hudson.util.InsufficientPermissionDetected) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) IOException(java.io.IOException) WebAppController(hudson.stapler.WebAppController) HudsonIsLoading(hudson.util.HudsonIsLoading) NoTempDir(hudson.util.NoTempDir) AWTProblem(hudson.util.AWTProblem) NamingException(javax.naming.NamingException) IOException(java.io.IOException) DefaultInstallStrategy(hudson.stapler.WebAppController.DefaultInstallStrategy) LocaleProvider(org.jvnet.localizer.LocaleProvider) URLClassLoader(java.net.URLClassLoader) IncompatibleServletVersionDetected(hudson.util.IncompatibleServletVersionDetected) File(java.io.File) SafeTimerTask(hudson.triggers.SafeTimerTask)

Example 3 with TransformerFactoryConfigurationError

use of javax.xml.transform.TransformerFactoryConfigurationError in project bazel by bazelbuild.

the class XmlOutputFormatter method createPostFactoStreamCallback.

@Override
public OutputFormatterCallback<Target> createPostFactoStreamCallback(final OutputStream out, final QueryOptions options) {
    return new OutputFormatterCallback<Target>() {

        private Document doc;

        private Element queryElem;

        @Override
        public void start() {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                doc = factory.newDocumentBuilder().newDocument();
            } catch (ParserConfigurationException e) {
                // This shouldn't be possible: all the configuration is hard-coded.
                throw new IllegalStateException("XML output failed", e);
            }
            doc.setXmlVersion("1.1");
            queryElem = doc.createElement("query");
            queryElem.setAttribute("version", "2");
            doc.appendChild(queryElem);
        }

        @Override
        public void processOutput(Iterable<Target> partialResult) throws IOException, InterruptedException {
            for (Target target : partialResult) {
                queryElem.appendChild(createTargetElement(doc, target));
            }
        }

        @Override
        public void close(boolean failFast) throws IOException {
            if (!failFast) {
                try {
                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    transformer.transform(new DOMSource(doc), new StreamResult(out));
                } catch (TransformerFactoryConfigurationError | TransformerException e) {
                    // This shouldn't be possible: all the configuration is hard-coded.
                    throw new IllegalStateException("XML output failed", e);
                }
            }
        }
    };
}
Also used : TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Element(org.w3c.dom.Element) SynchronizedDelegatingOutputFormatterCallback(com.google.devtools.build.lib.query2.engine.SynchronizedDelegatingOutputFormatterCallback) ThreadSafeOutputFormatterCallback(com.google.devtools.build.lib.query2.engine.ThreadSafeOutputFormatterCallback) OutputFormatterCallback(com.google.devtools.build.lib.query2.engine.OutputFormatterCallback) Document(org.w3c.dom.Document) FakeSubincludeTarget(com.google.devtools.build.lib.query2.FakeSubincludeTarget) Target(com.google.devtools.build.lib.packages.Target) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 4 with TransformerFactoryConfigurationError

use of javax.xml.transform.TransformerFactoryConfigurationError 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 5 with TransformerFactoryConfigurationError

use of javax.xml.transform.TransformerFactoryConfigurationError in project OpenClinica by OpenClinica.

the class XalanTransformJob method executeInternal.

protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    // need to generate a Locale so that user beans and other things will
    // generate normally
    // TODO make dynamic?
    Locale locale = new Locale("en-US");
    ResourceBundleProvider.updateLocale(locale);
    ResourceBundle pageMessages = ResourceBundleProvider.getPageMessagesBundle();
    JobDataMap dataMap = context.getMergedJobDataMap();
    // get the file information from the job
    String alertEmail = dataMap.getString(EMAIL);
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        // Use the TransformerFactory to instantiate a Transformer that will work with  
        // the stylesheet you specify. This method call also processes the stylesheet
        // into a compiled Templates object.
        java.io.InputStream in = new java.io.FileInputStream(dataMap.getString(XSL_FILE_PATH));
        // tFactory.setAttribute("use-classpath", Boolean.TRUE);
        // tFactory.setErrorListener(new ListingErrorHandler());
        Transformer transformer = tFactory.newTransformer(new StreamSource(in));
        // Use the Transformer to apply the associated Templates object to an XML document
        // (foo.xml) and write the output to a file (foo.out).
        //  System.out.println("--> job starting: ");
        final long start = System.currentTimeMillis();
        transformer.transform(new StreamSource(dataMap.getString(XML_FILE_PATH)), new StreamResult(new FileOutputStream(dataMap.getString(SQL_FILE_PATH))));
        final long done = System.currentTimeMillis() - start;
    // System.out.println("--> job completed in " + done + " ms");
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : Locale(java.util.Locale) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) JobDataMap(org.quartz.JobDataMap) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) StreamSource(javax.xml.transform.stream.StreamSource) FileNotFoundException(java.io.FileNotFoundException) FileOutputStream(java.io.FileOutputStream) ResourceBundle(java.util.ResourceBundle) TransformerException(javax.xml.transform.TransformerException)

Aggregations

TransformerFactoryConfigurationError (javax.xml.transform.TransformerFactoryConfigurationError)15 TransformerException (javax.xml.transform.TransformerException)11 StreamResult (javax.xml.transform.stream.StreamResult)9 Transformer (javax.xml.transform.Transformer)8 IOException (java.io.IOException)7 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)6 DOMSource (javax.xml.transform.dom.DOMSource)6 File (java.io.File)4 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 SAXException (org.xml.sax.SAXException)4 FileOutputStream (java.io.FileOutputStream)3 Locale (java.util.Locale)3 Entry (java.util.Map.Entry)3 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)3 TransformerFactory (javax.xml.transform.TransformerFactory)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 StringWriter (java.io.StringWriter)2 ResourceBundle (java.util.ResourceBundle)2 StreamSource (javax.xml.transform.stream.StreamSource)2