Search in sources :

Example 26 with SimpleTrigger

use of org.quartz.SimpleTrigger in project camel by apache.

the class QuartzEndpoint method createTrigger.

private Trigger createTrigger(JobDetail jobDetail) throws Exception {
    Trigger result;
    Date startTime = new Date();
    if (getComponent().getScheduler().isStarted()) {
        startTime = new Date(System.currentTimeMillis() + triggerStartDelay);
    }
    if (cron != null) {
        LOG.debug("Creating CronTrigger: {}", cron);
        String timeZone = (String) triggerParameters.get("timeZone");
        if (timeZone != null) {
            if (ObjectHelper.isNotEmpty(customCalendar)) {
                result = TriggerBuilder.newTrigger().withIdentity(triggerKey).startAt(startTime).withSchedule(cronSchedule(cron).withMisfireHandlingInstructionFireAndProceed().inTimeZone(TimeZone.getTimeZone(timeZone))).modifiedByCalendar(QuartzConstants.QUARTZ_CAMEL_CUSTOM_CALENDAR).build();
            } else {
                result = TriggerBuilder.newTrigger().withIdentity(triggerKey).startAt(startTime).withSchedule(cronSchedule(cron).withMisfireHandlingInstructionFireAndProceed().inTimeZone(TimeZone.getTimeZone(timeZone))).build();
            }
            jobDetail.getJobDataMap().put(QuartzConstants.QUARTZ_TRIGGER_CRON_TIMEZONE, timeZone);
        } else {
            if (ObjectHelper.isNotEmpty(customCalendar)) {
                result = TriggerBuilder.newTrigger().withIdentity(triggerKey).startAt(startTime).withSchedule(cronSchedule(cron).withMisfireHandlingInstructionFireAndProceed()).modifiedByCalendar(QuartzConstants.QUARTZ_CAMEL_CUSTOM_CALENDAR).build();
            } else {
                result = TriggerBuilder.newTrigger().withIdentity(triggerKey).startAt(startTime).withSchedule(cronSchedule(cron).withMisfireHandlingInstructionFireAndProceed()).build();
            }
        }
        // enrich job map with details
        jobDetail.getJobDataMap().put(QuartzConstants.QUARTZ_TRIGGER_TYPE, "cron");
        jobDetail.getJobDataMap().put(QuartzConstants.QUARTZ_TRIGGER_CRON_EXPRESSION, cron);
    } else {
        LOG.debug("Creating SimpleTrigger.");
        int repeat = SimpleTrigger.REPEAT_INDEFINITELY;
        String repeatString = (String) triggerParameters.get("repeatCount");
        if (repeatString != null) {
            repeat = EndpointHelper.resolveParameter(getCamelContext(), repeatString, Integer.class);
            // need to update the parameters
            triggerParameters.put("repeatCount", repeat);
        }
        // default use 1 sec interval
        long interval = 1000;
        String intervalString = (String) triggerParameters.get("repeatInterval");
        if (intervalString != null) {
            interval = EndpointHelper.resolveParameter(getCamelContext(), intervalString, Long.class);
            // need to update the parameters
            triggerParameters.put("repeatInterval", interval);
        }
        TriggerBuilder<SimpleTrigger> triggerBuilder;
        if (ObjectHelper.isNotEmpty(customCalendar)) {
            triggerBuilder = TriggerBuilder.newTrigger().withIdentity(triggerKey).startAt(startTime).withSchedule(simpleSchedule().withMisfireHandlingInstructionFireNow().withRepeatCount(repeat).withIntervalInMilliseconds(interval)).modifiedByCalendar(QuartzConstants.QUARTZ_CAMEL_CUSTOM_CALENDAR);
        } else {
            triggerBuilder = TriggerBuilder.newTrigger().withIdentity(triggerKey).startAt(startTime).withSchedule(simpleSchedule().withMisfireHandlingInstructionFireNow().withRepeatCount(repeat).withIntervalInMilliseconds(interval));
        }
        if (fireNow) {
            triggerBuilder = triggerBuilder.startNow();
        }
        result = triggerBuilder.build();
        // enrich job map with details
        jobDetail.getJobDataMap().put(QuartzConstants.QUARTZ_TRIGGER_TYPE, "simple");
        jobDetail.getJobDataMap().put(QuartzConstants.QUARTZ_TRIGGER_SIMPLE_REPEAT_COUNTER, repeat);
        jobDetail.getJobDataMap().put(QuartzConstants.QUARTZ_TRIGGER_SIMPLE_REPEAT_INTERVAL, interval);
    }
    if (triggerParameters != null && triggerParameters.size() > 0) {
        LOG.debug("Setting user extra triggerParameters {}", triggerParameters);
        setProperties(result, triggerParameters);
    }
    LOG.debug("Created trigger={}", result);
    return result;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Trigger(org.quartz.Trigger) SimpleTrigger(org.quartz.SimpleTrigger) CronTrigger(org.quartz.CronTrigger) SimpleTrigger(org.quartz.SimpleTrigger) Date(java.util.Date) UriEndpoint(org.apache.camel.spi.UriEndpoint) DefaultEndpoint(org.apache.camel.impl.DefaultEndpoint)

Example 27 with SimpleTrigger

use of org.quartz.SimpleTrigger in project camel by apache.

the class SpringQuartzPersistentStoreRestartAppChangeOptionsTest method testRestartAppChangeTriggerOptions.

@Test
public void testRestartAppChangeTriggerOptions() throws Exception {
    // Test creates application context twice with different simple trigger options in configuration xml.
    // Both times it retrieves back the option, accessing it via trigger (so, using value stored in DB).
    // After that it asserts that two options are not equal.
    // load spring app
    AbstractXmlApplicationContext app = new ClassPathXmlApplicationContext("org/apache/camel/component/quartz/SpringQuartzPersistentStoreRestartAppChangeOptionsTest1.xml");
    app.start();
    CamelContext camel = app.getBean("camelContext", CamelContext.class);
    assertNotNull(camel);
    SimpleTrigger trigger = (SimpleTrigger) getTrigger(camel, "quartzRoute");
    long repeatInterval = trigger.getRepeatInterval();
    app.stop();
    log.info("Restarting ...");
    log.info("Restarting ...");
    log.info("Restarting ...");
    // load spring app
    AbstractXmlApplicationContext app2 = new ClassPathXmlApplicationContext("org/apache/camel/component/quartz/SpringQuartzPersistentStoreRestartAppChangeOptionsTest2.xml");
    app2.start();
    CamelContext camel2 = app2.getBean("camelContext", CamelContext.class);
    assertNotNull(camel2);
    SimpleTrigger trigger2 = (SimpleTrigger) getTrigger(camel2, "quartzRoute");
    long repeatInterval2 = trigger2.getRepeatInterval();
    app2.stop();
    // we're done so let's properly close the application contexts, but close
    // the second app before the first one so that the quartz scheduler running
    // inside it can be properly shutdown
    IOHelper.close(app2, app);
    assertNotEquals(repeatInterval, repeatInterval2);
}
Also used : CamelContext(org.apache.camel.CamelContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) AbstractXmlApplicationContext(org.springframework.context.support.AbstractXmlApplicationContext) SimpleTrigger(org.quartz.SimpleTrigger) Test(org.junit.Test)

Example 28 with SimpleTrigger

use of org.quartz.SimpleTrigger in project camel by apache.

the class SpringQuartzPersistentStoreRestartAppChangeOptionsTest method testRestartAppChangeTriggerOptions.

@Test
public void testRestartAppChangeTriggerOptions() throws Exception {
    // Test creates application context twice with different simple trigger options in configuration xml.
    // Both times it retrieves back the option, accessing it via trigger (so, using value stored in DB).
    // After that it asserts that two options are not equal.
    // load spring app
    AbstractXmlApplicationContext app = new ClassPathXmlApplicationContext("org/apache/camel/component/quartz2/SpringQuartzPersistentStoreRestartAppChangeOptionsTest1.xml");
    app.start();
    CamelContext camel = app.getBean("camelContext", CamelContext.class);
    assertNotNull(camel);
    SimpleTrigger trigger = (SimpleTrigger) getTrigger(camel, "quartzRoute");
    long repeatInterval = trigger.getRepeatInterval();
    app.stop();
    log.info("Restarting ...");
    log.info("Restarting ...");
    log.info("Restarting ...");
    // load spring app
    AbstractXmlApplicationContext app2 = new ClassPathXmlApplicationContext("org/apache/camel/component/quartz2/SpringQuartzPersistentStoreRestartAppChangeOptionsTest2.xml");
    app2.start();
    CamelContext camel2 = app2.getBean("camelContext", CamelContext.class);
    assertNotNull(camel2);
    SimpleTrigger trigger2 = (SimpleTrigger) getTrigger(camel2, "quartzRoute");
    long repeatInterval2 = trigger2.getRepeatInterval();
    app2.stop();
    // we're done so let's properly close the application contexts, but close
    // the second app before the first one so that the quartz scheduler running
    // inside it can be properly shutdown
    IOHelper.close(app2, app);
    assertNotEquals(repeatInterval, repeatInterval2);
}
Also used : CamelContext(org.apache.camel.CamelContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) AbstractXmlApplicationContext(org.springframework.context.support.AbstractXmlApplicationContext) SimpleTrigger(org.quartz.SimpleTrigger) Test(org.junit.Test)

Example 29 with SimpleTrigger

use of org.quartz.SimpleTrigger in project camel by apache.

the class QuartzSimpleRouteTest method testQuartzCronRoute.

@Test
public void testQuartzCronRoute() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMinimumMessageCount(3);
    assertMockEndpointsSatisfied();
    Trigger trigger = mock.getReceivedExchanges().get(0).getIn().getHeader("trigger", Trigger.class);
    Assert.assertThat(trigger instanceof SimpleTrigger, CoreMatchers.is(true));
    JobDetail detail = mock.getReceivedExchanges().get(0).getIn().getHeader("jobDetail", JobDetail.class);
    Assert.assertThat(detail.getJobClass().equals(CamelJob.class), CoreMatchers.is(true));
    Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_TYPE).equals("simple"), CoreMatchers.is(true));
    Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_SIMPLE_REPEAT_COUNTER).equals(-1), CoreMatchers.is(true));
    Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_SIMPLE_REPEAT_INTERVAL).equals(2000L), CoreMatchers.is(true));
}
Also used : JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) SimpleTrigger(org.quartz.SimpleTrigger) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) SimpleTrigger(org.quartz.SimpleTrigger) Test(org.junit.Test)

Example 30 with SimpleTrigger

use of org.quartz.SimpleTrigger in project OpenClinica by OpenClinica.

the class CreateJobExportServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    // TODO multi stage servlet which will create export jobs
    // will accept, create, and return the ViewJob servlet
    FormProcessor fp = new FormProcessor(request);
    TriggerService triggerService = new TriggerService();
    scheduler = getScheduler();
    String action = fp.getString("action");
    ExtractUtils extractUtils = new ExtractUtils();
    if (StringUtil.isBlank(action)) {
        // set up list of data sets
        // select by ... active study
        setUpServlet();
        forwardPage(Page.CREATE_JOB_EXPORT);
    } else if ("confirmall".equalsIgnoreCase(action)) {
        // collect form information
        Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals("DEFAULT"));
        String[] triggerNames = triggerKeys.stream().toArray(String[]::new);
        HashMap errors = validateForm(fp, request, triggerNames, "");
        if (!errors.isEmpty()) {
            // set errors to request
            request.setAttribute("formMessages", errors);
            logger.info("has validation errors in the first section");
            logger.info("errors found: " + errors.toString());
            setUpServlet();
            forwardPage(Page.CREATE_JOB_EXPORT);
        } else {
            logger.info("found no validation errors, continuing");
            StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
            DatasetDAO datasetDao = new DatasetDAO(sm.getDataSource());
            UserAccountBean userBean = (UserAccountBean) request.getSession().getAttribute("userBean");
            CoreResources cr = new CoreResources();
            int datasetId = fp.getInt(DATASET_ID);
            String period = fp.getString(PERIOD);
            String email = fp.getString(EMAIL);
            String jobName = fp.getString(JOB_NAME);
            String jobDesc = fp.getString(JOB_DESC);
            Date startDateTime = fp.getDateTime(DATE_START_JOB);
            Integer exportFormatId = fp.getInt(FORMAT_ID);
            ExtractPropertyBean epBean = cr.findExtractPropertyBeanById(exportFormatId, "" + datasetId);
            DatasetBean dsBean = (DatasetBean) datasetDao.findByPK(new Integer(datasetId).intValue());
            // set the job in motion
            String[] files = epBean.getFileName();
            String exportFileName;
            int fileSize = files.length;
            int cnt = 0;
            dsBean.setName(dsBean.getName().replaceAll(" ", "_"));
            String[] exportFiles = epBean.getExportFileName();
            String pattern = "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator + "HHmmssSSS" + File.separator;
            SimpleDateFormat sdfDir = new SimpleDateFormat(pattern);
            int i = 0;
            String[] temp = new String[exportFiles.length];
            //JN: The following logic is for comma separated variables, to avoid the second file be treated as a old file and deleted.
            String datasetFilePath = SQLInitServlet.getField("filePath") + "datasets";
            while (i < exportFiles.length) {
                temp[i] = extractUtils.resolveVars(exportFiles[i], dsBean, sdfDir, datasetFilePath);
                i++;
            }
            epBean.setDoNotDelFiles(temp);
            epBean.setExportFileName(temp);
            XsltTriggerService xsltService = new XsltTriggerService();
            String generalFileDir = SQLInitServlet.getField("filePath");
            generalFileDir = generalFileDir + "datasets" + File.separator + dsBean.getId() + File.separator + sdfDir.format(new java.util.Date());
            exportFileName = epBean.getExportFileName()[cnt];
            // need to set the dataset path here, tbh
            // next, can already run jobs, translations, and then add a message to be notified later
            //JN all the properties need to have the variables...
            String xsltPath = SQLInitServlet.getField("filePath") + "xslt" + File.separator + files[cnt];
            String endFilePath = epBean.getFileLocation();
            endFilePath = extractUtils.getEndFilePath(endFilePath, dsBean, sdfDir, datasetFilePath);
            //  exportFileName = resolveVars(exportFileName,dsBean,sdfDir);
            if (epBean.getPostProcExportName() != null) {
                //String preProcExportPathName = getEndFilePath(epBean.getPostProcExportName(),dsBean,sdfDir);
                String preProcExportPathName = extractUtils.resolveVars(epBean.getPostProcExportName(), dsBean, sdfDir, datasetFilePath);
                epBean.setPostProcExportName(preProcExportPathName);
            }
            if (epBean.getPostProcLocation() != null) {
                String prePocLoc = extractUtils.getEndFilePath(epBean.getPostProcLocation(), dsBean, sdfDir, datasetFilePath);
                epBean.setPostProcLocation(prePocLoc);
            }
            extractUtils.setAllProps(epBean, dsBean, sdfDir, datasetFilePath);
            SimpleTrigger trigger = null;
            trigger = xsltService.generateXsltTrigger(scheduler, xsltPath, // xml_file_path
            generalFileDir, endFilePath + File.separator, exportFileName, dsBean.getId(), epBean, userBean, LocaleResolver.getLocale(request).getLanguage(), cnt, SQLInitServlet.getField("filePath") + "xslt", xsltService.getTriggerGroupNameForExportJobs());
            //Updating the original trigger with user given inputs
            trigger.getTriggerBuilder().withSchedule(simpleSchedule().withRepeatCount(64000).withIntervalInSeconds(new Integer(period).intValue()).withMisfireHandlingInstructionNextWithExistingCount()).startAt(startDateTime).forJob(jobName).withDescription(jobDesc);
            trigger.getJobDataMap().put(XsltTriggerService.EMAIL, email);
            trigger.getJobDataMap().put(XsltTriggerService.PERIOD, period);
            trigger.getJobDataMap().put(XsltTriggerService.EXPORT_FORMAT, epBean.getFiledescription());
            trigger.getJobDataMap().put(XsltTriggerService.EXPORT_FORMAT_ID, exportFormatId);
            trigger.getJobDataMap().put(XsltTriggerService.JOB_NAME, jobName);
            trigger.getJobDataMap().put("job_type", "exportJob");
            JobDetailFactoryBean JobDetailFactoryBean = new JobDetailFactoryBean();
            JobDetailFactoryBean.setGroup(xsltService.getTriggerGroupNameForExportJobs());
            JobDetailFactoryBean.setName(trigger.getKey().getName());
            JobDetailFactoryBean.setJobClass(org.akaza.openclinica.job.XsltStatefulJob.class);
            JobDetailFactoryBean.setJobDataMap(trigger.getJobDataMap());
            // need durability?
            JobDetailFactoryBean.setDurability(true);
            // set to the scheduler
            try {
                Date dateStart = scheduler.scheduleJob(JobDetailFactoryBean.getObject(), trigger);
                logger.info("== found job date: " + dateStart.toString());
            // set a success message here
            } catch (SchedulerException se) {
                se.printStackTrace();
                setUpServlet();
                addPageMessage("Error creating Job.");
                forwardPage(Page.VIEW_JOB_SERVLET);
                return;
            }
            setUpServlet();
            addPageMessage("You have successfully created a new job: " + jobName + " which is now set to run at the time you specified.");
            forwardPage(Page.VIEW_JOB_SERVLET);
        }
    } else {
        forwardPage(Page.ADMIN_SYSTEM);
    // forward to form
    // should we even get to this part?
    }
}
Also used : SchedulerException(org.quartz.SchedulerException) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) CoreResources(org.akaza.openclinica.dao.core.CoreResources) DatasetBean(org.akaza.openclinica.bean.extract.DatasetBean) DatasetDAO(org.akaza.openclinica.dao.extract.DatasetDAO) XsltTriggerService(org.akaza.openclinica.service.extract.XsltTriggerService) TriggerService(org.akaza.openclinica.web.job.TriggerService) ExtractUtils(org.akaza.openclinica.service.extract.ExtractUtils) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) ExtractPropertyBean(org.akaza.openclinica.bean.extract.ExtractPropertyBean) XsltTriggerService(org.akaza.openclinica.service.extract.XsltTriggerService) SimpleTrigger(org.quartz.SimpleTrigger) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) SimpleDateFormat(java.text.SimpleDateFormat) JobDetailFactoryBean(org.springframework.scheduling.quartz.JobDetailFactoryBean)

Aggregations

SimpleTrigger (org.quartz.SimpleTrigger)37 SchedulerException (org.quartz.SchedulerException)18 JobDetail (org.quartz.JobDetail)14 CronTrigger (org.quartz.CronTrigger)11 Scheduler (org.quartz.Scheduler)11 Date (java.util.Date)8 Test (org.junit.Test)8 Trigger (org.quartz.Trigger)6 StudyDAO (org.akaza.openclinica.dao.managestudy.StudyDAO)5 JobDataMap (org.quartz.JobDataMap)5 SimpleDateFormat (java.text.SimpleDateFormat)4 DatasetBean (org.akaza.openclinica.bean.extract.DatasetBean)4 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)4 DatasetDAO (org.akaza.openclinica.dao.extract.DatasetDAO)4 CamelContext (org.apache.camel.CamelContext)4 AbstractXmlApplicationContext (org.springframework.context.support.AbstractXmlApplicationContext)4 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 JobExecutionException (org.quartz.JobExecutionException)3