⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jobinitializationplugin.java

📁 时间调度相关的开源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     * SchedulerPlugin Interface.
     * 
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    /**
     * <p>
     * Called during creation of the <code>Scheduler</code> in order to give
     * the <code>SchedulerPlugin</code> a chance to initialize.
     * </p>
     * 
     * @throws org.quartz.SchedulerConfigException
     *           if there is an error initializing.
     */
    public void initialize(String name, final Scheduler scheduler)
        throws SchedulerException {
        super.initialize(name, scheduler);
        
        classLoadHelper = new CascadingClassLoadHelper();
        classLoadHelper.initialize();
        
        getLog().info("Registering Quartz Job Initialization Plug-in.");
        
        // Create JobFile objects
        StringTokenizer stok = new StringTokenizer(fileNames, FILE_NAME_DELIMITERS);
        while (stok.hasMoreTokens()) {
            JobFile jobFile = new JobFile(stok.nextToken());
            jobFiles.put(jobFile.getFilePath(), jobFile);
        }
    }

    
    public void start(UserTransaction userTransaction) {
        try {
            if (jobFiles.isEmpty() == false) {
                
                if (scanInterval > 0) {
                    getScheduler().getContext().put(JOB_INITIALIZATION_PLUGIN_NAME + '_' + getName(), this);
                }
                
                Iterator iterator = jobFiles.values().iterator();
                while (iterator.hasNext()) {
                    JobFile jobFile = (JobFile)iterator.next();
                
                    if (scanInterval > 0) {
                        String jobTriggerName = buildJobTriggerName(jobFile.getFileBasename());
                        
                        SimpleTrigger trig = new SimpleTrigger(
                                jobTriggerName, 
                                JOB_INITIALIZATION_PLUGIN_NAME, 
                                new Date(), null, 
                                SimpleTrigger.REPEAT_INDEFINITELY, scanInterval);
                        trig.setVolatility(true);
                        
                        JobDetail job = new JobDetail(
                                jobTriggerName, 
                                JOB_INITIALIZATION_PLUGIN_NAME,
                                FileScanJob.class);
                        job.setVolatility(true);
                        job.getJobDataMap().put(FileScanJob.FILE_NAME, jobFile.getFileName());
                        job.getJobDataMap().put(FileScanJob.FILE_SCAN_LISTENER_NAME, JOB_INITIALIZATION_PLUGIN_NAME + '_' + getName());
                        
                        getScheduler().scheduleJob(job, trig);
                    }
                    
                    processFile(jobFile);
                }
            }
        } catch(SchedulerException se) {
            getLog().error("Error starting background-task for watching jobs file.", se);
        } finally {
            started = true;
        }
    }
    
    /**
     * Helper method for generating unique job/trigger name for the  
     * file scanning jobs (one per FileJob).  The unique names are saved
     * in jobTriggerNameSet.
     */
    private String buildJobTriggerName(
            String fileBasename) {
        // Name w/o collisions will be prefix + _ + filename (with '.' of filename replaced with '_')
        // For example: JobInitializationPlugin_jobInitializer_myjobs_xml
        String jobTriggerName = JOB_INITIALIZATION_PLUGIN_NAME + '_' + getName() + '_' + fileBasename.replace('.', '_');
        
        // If name is too long (DB column is 80 chars), then truncate to max length
        if (jobTriggerName.length() > MAX_JOB_TRIGGER_NAME_LEN) {
            jobTriggerName = jobTriggerName.substring(0, MAX_JOB_TRIGGER_NAME_LEN);
        }
        
        // Make sure this name is unique in case the same file name under different
        // directories is being checked, or had a naming collision due to length truncation.
        // If there is a conflict, keep incrementing a _# suffix on the name (being sure
        // not to get too long), until we find a unique name.
        int currentIndex = 1;
        while (jobTriggerNameSet.add(jobTriggerName) == false) {
            // If not our first time through, then strip off old numeric suffix
            if (currentIndex > 1) {
                jobTriggerName = jobTriggerName.substring(0, jobTriggerName.lastIndexOf('_'));
            }

            String numericSuffix = "_" + currentIndex++;

            // If the numeric suffix would make the name too long, then make room for it.
            if (jobTriggerName.length() > (MAX_JOB_TRIGGER_NAME_LEN - numericSuffix.length())) {
                jobTriggerName = jobTriggerName.substring(0, (MAX_JOB_TRIGGER_NAME_LEN - numericSuffix.length()));
            }

            jobTriggerName += numericSuffix;
        }
        
        return jobTriggerName;
    }
    
    /**
     * Overriden to ignore <em>wrapInUserTransaction</em> because shutdown()
     * does not interact with the <code>Scheduler</code>. 
     */
    public void shutdown() {
        // Since we have nothing to do, override base shutdown so don't
        // get extranious UserTransactions.
    }

    private void processFile(JobFile jobFile) {
        if (jobFile == null || !jobFile.getFileFound()) {
            return;
        }

        JobSchedulingDataProcessor processor = 
            new JobSchedulingDataProcessor(this.classLoadHelper, isValidating(), isValidatingSchema());

        try {
            processor.processFileAndScheduleJobs(
                    jobFile.getFileName(), 
                    jobFile.getFileName(), // systemId 
                    getScheduler(), 
                    isOverWriteExistingJobs());
        } catch (Exception e) {
            getLog().error("Error scheduling jobs: " + e.getMessage(), e);
        }
    }
    
    public void processFile(String filePath) {
        processFile((JobFile)jobFiles.get(filePath));
    }

    /** 
     * @see org.quartz.jobs.FileScanListener#fileUpdated(java.lang.String)
     */
    public void fileUpdated(String fileName) {
        if (started) {
            processFile(fileName);
        }
    }
    
    class JobFile {
        private String fileName;

        // These are set by initialize()
        private String filePath;
        private String fileBasename;
        private boolean fileFound;

        protected JobFile(String fileName) throws SchedulerException {
            this.fileName = fileName;
            initialize();
        }
        
        protected String getFileName() {
            return fileName;
        }
        
        protected boolean getFileFound() {
            return fileFound;
        }

        protected String getFilePath() {
            return filePath;
        }
        
        protected String getFileBasename() {
            return fileBasename;
        }
                
        private void initialize() throws SchedulerException {
            InputStream f = null;
            try {
                String furl = null;
                
                File file = new File(getFileName()); // files in filesystem
                if (!file.exists()) {
                    URL url = classLoadHelper.getResource(getFileName());
                    if(url != null) {
    //     we need jdk 1.3 compatibility, so we abandon this code...
    //                    try {
    //                        furl = URLDecoder.decode(url.getPath(), "UTF-8");
    //                    } catch (UnsupportedEncodingException e) {
    //                        furl = url.getPath();
    //                    }
                        furl = URLDecoder.decode(url.getPath()); 
                        file = new File(furl); 
                        try {
                            f = url.openStream();
                        } catch (IOException ignor) {
                            // Swallow the exception
                        }
                    }        
                } else {
                    try {              
                        f = new java.io.FileInputStream(file);
                    }catch (FileNotFoundException e) {
                        // ignore
                    }
                }
                
                if (f == null) {
                    if (isFailOnFileNotFound()) {
                        throw new SchedulerException(
                            "File named '" + getFileName() + "' does not exist.");
                    } else {
                        getLog().warn("File named '" + getFileName() + "' does not exist.");
                    }
                } else {
                    fileFound = true;
                    filePath = (furl != null) ? furl : file.getAbsolutePath();
                    fileBasename = file.getName();
                }
            } finally {
                try {
                    if (f != null) {
                        f.close();
                    }
                } catch (IOException ioe) {
                    getLog().warn("Error closing jobs file " + getFileName(), ioe);
                }
            }
        }
    }
}

// EOF

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -