Java Examples for org.quartz.CronExpression

The following java examples will help you to understand the usage of org.quartz.CronExpression. These source code samples are taken from different open source projects.

Example 1
Project: pluggable-master  File: CronExpressionValidator.java View source code
@Override
public void validate(IValidatable<String> validatable) {
    if (validatable.getValue() != null && !"".equals(validatable.getValue())) {
        if (!CronExpression.isValidExpression(validatable.getValue())) {
            ValidationError error = new ValidationError(this);
            error.setVariable("input", validatable.getValue());
            validatable.error(error);
        }
    }
}
Example 2
Project: cron-expression-master  File: CompareSizeToQuartzTest.java View source code
private void check(String expression) throws Exception {
    CronExpression local = quartzLike.parse(expression);
    org.quartz.CronExpression quartz = new org.quartz.CronExpression(expression);
    long localSize = ObjectSizeCalculator.getObjectSize(local);
    long quartzSize = ObjectSizeCalculator.getObjectSize(quartz);
    assertTrue("We have more bytes", localSize < quartzSize);
    ObjectGraphMeasurer.Footprint localFoot = ObjectGraphMeasurer.measure(local);
    ObjectGraphMeasurer.Footprint quartzFoot = ObjectGraphMeasurer.measure(quartz);
    assertTrue("We have more references", localFoot.getAllReferences() < quartzFoot.getAllReferences());
    assertTrue("We have more non-null references", localFoot.getNonNullReferences() < quartzFoot.getNonNullReferences());
    assertTrue("We have more null references", localFoot.getNullReferences() < quartzFoot.getNullReferences());
    assertTrue("We have more objects", localFoot.getObjects() < quartzFoot.getObjects());
    assertTrue("We have more primitives", localFoot.getPrimitives().size() < quartzFoot.getPrimitives().size());
}
Example 3
Project: cloudbreak-master  File: DateUtils.java View source code
public static boolean isTrigger(String cron, String timeZone, long monitorUpdateRate) {
    try {
        CronExpression cronExpression = getCronExpression(cron);
        Date currentTime = getCurrentDate(timeZone);
        Date nextTime = cronExpression.getNextValidTimeAfter(currentTime);
        DateTime nextDateTime = getDateTime(nextTime, timeZone).minus(monitorUpdateRate);
        long interval = nextDateTime.toDate().getTime() - currentTime.getTime();
        return interval > 0 && interval < monitorUpdateRate;
    } catch (ParseException e) {
        LOGGER.warn("Invalid cron expression, {}", e.getMessage());
        return false;
    }
}
Example 4
Project: Quartz-master  File: CronExpressionTest.java View source code
/**
     * Verify that the target object and the object we just deserialized 
     * match.
     */
@Override
protected void verifyMatch(Object target, Object deserialized) {
    CronExpression targetCronExpression = (CronExpression) target;
    CronExpression deserializedCronExpression = (CronExpression) deserialized;
    assertNotNull(deserializedCronExpression);
    assertEquals(targetCronExpression.getCronExpression(), deserializedCronExpression.getCronExpression());
    assertEquals(targetCronExpression.getTimeZone(), deserializedCronExpression.getTimeZone());
}
Example 5
Project: quartz-scheduler-master  File: CronExpressionTest.java View source code
/**
     * Verify that the target object and the object we just deserialized 
     * match.
     */
@Override
protected void verifyMatch(Object target, Object deserialized) {
    CronExpression targetCronExpression = (CronExpression) target;
    CronExpression deserializedCronExpression = (CronExpression) deserialized;
    assertNotNull(deserializedCronExpression);
    assertEquals(targetCronExpression.getCronExpression(), deserializedCronExpression.getCronExpression());
    assertEquals(targetCronExpression.getTimeZone(), deserializedCronExpression.getTimeZone());
}
Example 6
Project: rhq-master  File: RepoManagerBean.java View source code
private void validateFields(Repo repo) throws RepoException {
    if (repo.getName() == null || repo.getName().trim().equals("")) {
        throw new RepoException("Repo name is required");
    }
    if (repo.getSyncSchedule() != null) {
        try {
            CronExpression ce = new CronExpression(repo.getSyncSchedule());
        } catch (ParseException e) {
            throw new RepoException("Repo sync schedule is not a vaild format.");
        }
    }
}
Example 7
Project: serengeti-ws-master  File: InitializingCronTriggerFactoryBean.java View source code
private void initCronExpression() {
    String cronExpression = getCronExpressionFromConfiguration();
    if (!CommonUtil.isBlank(cronExpression) && CronExpression.isValidExpression(cronExpression)) {
        setCronExpression(cronExpression);
    } else {
        CollectionDriver driver = collectionDriverManager.getDriver();
        if (driver != null) {
            setCronExpression(driver.getDefaultCronExpression());
        } else {
            logger.warn("com.vmware.bdd.manager.collection.CollectionDriver is not configured.");
        }
    }
}
Example 8
Project: constellio-master  File: ConstellioJob.java View source code
Set<Trigger> buildCronTriggers() {
    final Set<Trigger> triggers = new HashSet<>();
    Set<String> cronExpressions = cronExpressions();
    if (CollectionUtils.isNotEmpty(cronExpressions)) {
        cronExpressions = new TreeSet<>(cronExpressions);
        for (final String cronExpression : cronExpressions) {
            try {
                final TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger().withIdentity(name() + "-Trigger-" + cronExpression, Scheduler.DEFAULT_GROUP).withSchedule(CronScheduleBuilder.cronSchedule(cronExpression));
                ;
                if (startTime() == null) {
                    triggerBuilder.startAt(new CronExpression(cronExpression).getNextValidTimeAfter(new Date()));
                } else {
                    triggerBuilder.startAt(startTime());
                }
                triggers.add(triggerBuilder.build());
            } catch (final ParseException e) {
                LOGGER.error("invalid cron expression " + cronExpression, e);
            }
        }
    }
    return triggers;
}
Example 9
Project: Fenzo-master  File: TriggerUtils.java View source code
public static void validateCronExpression(String cronExpression) {
    try {
        if (cronExpression == null || cronExpression.equals("")) {
            throw new IllegalArgumentException(String.format("Cron expression cannot be null or empty : %s", cronExpression));
        }
        StringTokenizer tokenizer = new StringTokenizer(cronExpression, " \t", false);
        int tokens = tokenizer.countTokens();
        String beginningToken = tokenizer.nextToken().trim();
        if ("*".equals(beginningToken)) {
            // For all practical purposes and for ALL clients of this library, this is true!
            throw new IllegalArgumentException(String.format("Cron expression cannot have '*' in the SECONDS (first) position : %s", cronExpression));
        }
        if (tokens > 7) {
            throw new IllegalArgumentException(String.format("Cron expression cannot have more than 7 fields : %s", cronExpression));
        }
        CronExpression.validateExpression(cronExpression);
    } catch (ParseException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
Example 10
Project: mangooio-master  File: Bootstrap.java View source code
public void startQuartzScheduler() {
    if (!bootstrapError()) {
        List<Class<?>> jobs = new ArrayList<>();
        new FastClasspathScanner(this.config.getSchedulerPackage()).matchClassesWithAnnotation(Schedule.class, jobs::add).scan();
        if (!jobs.isEmpty() && this.config.isSchedulerAutostart()) {
            final Scheduler mangooScheduler = this.injector.getInstance(Scheduler.class);
            mangooScheduler.initialize();
            for (Class<?> clazz : jobs) {
                final Schedule schedule = clazz.getDeclaredAnnotation(Schedule.class);
                if (CronExpression.isValidExpression(schedule.cron())) {
                    final JobDetail jobDetail = SchedulerUtils.createJobDetail(clazz.getName(), Default.SCHEDULER_JOB_GROUP.toString(), clazz.asSubclass(Job.class));
                    final Trigger trigger = SchedulerUtils.createTrigger(clazz.getName() + "-trigger", Default.SCHEDULER_TRIGGER_GROUP.toString(), schedule.description(), schedule.cron());
                    try {
                        mangooScheduler.schedule(jobDetail, trigger);
                    } catch (MangooSchedulerException e) {
                        LOG.error("Failed to add a job to the scheduler", e);
                    }
                    LOG.info("Successfully scheduled job " + clazz.getName() + " with cron " + schedule.cron());
                } else {
                    LOG.error("Invalid or missing cron expression for job: " + clazz.getName());
                    this.error = true;
                }
            }
            if (!bootstrapError()) {
                try {
                    mangooScheduler.start();
                } catch (MangooSchedulerException e) {
                    LOG.error("Failed to start the scheduler", e);
                }
            }
        }
    }
}
Example 11
Project: opencast-master  File: AbstractBufferScanner.java View source code
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
    String cronExpression;
    boolean enabled;
    unschedule();
    if (properties != null) {
        logger.debug("Updating configuration...");
        enabled = BooleanUtils.toBoolean((String) properties.get(PARAM_KEY_ENABLED));
        setEnabled(enabled);
        logger.debug("enabled = " + enabled);
        cronExpression = (String) properties.get(PARAM_KEY_CRON_EXPR);
        if (StringUtils.isBlank(cronExpression) || !CronExpression.isValidExpression(cronExpression))
            throw new ConfigurationException(PARAM_KEY_CRON_EXPR, "Cron expression must be valid");
        setCronExpression(cronExpression);
        logger.debug("cronExpression = '" + cronExpression + "'");
        try {
            buffer = Long.valueOf((String) properties.get(PARAM_KEY_BUFFER));
            if (buffer < 0) {
                throw new ConfigurationException(PARAM_KEY_BUFFER, "Buffer must be 0 or greater");
            }
        } catch (NumberFormatException e) {
            throw new ConfigurationException(PARAM_KEY_BUFFER, "Buffer must be a valid integer", e);
        }
        logger.debug("buffer = " + buffer);
    }
    schedule();
}
Example 12
Project: openmrs-module-reporting-master  File: RunReportFormController.java View source code
@Override
public void validate(Object commandObject, Errors errors) {
    CommandObject command = (CommandObject) commandObject;
    ValidationUtils.rejectIfEmpty(errors, "reportDefinition", "reporting.Report.run.error.missingReportID");
    if (command.getReportDefinition() != null) {
        ReportDefinition reportDefinition = command.getReportDefinition();
        Set<String> requiredParams = new HashSet<String>();
        if (reportDefinition.getParameters() != null) {
            for (Parameter parameter : reportDefinition.getParameters()) {
                if (parameter.isRequired()) {
                    requiredParams.add(parameter.getName());
                }
            }
        }
        for (Map.Entry<String, Object> e : command.getUserEnteredParams().entrySet()) {
            if (e.getValue() instanceof Iterable || e.getValue() instanceof Object[]) {
                Object iterable = e.getValue();
                if (e.getValue() instanceof Object[]) {
                    iterable = Arrays.asList((Object[]) e.getValue());
                }
                boolean hasNull = true;
                for (Object value : (Iterable<Object>) iterable) {
                    hasNull = !ObjectUtil.notNull(value);
                }
                if (!hasNull) {
                    requiredParams.remove(e.getKey());
                }
            } else if (ObjectUtil.notNull(e.getValue())) {
                requiredParams.remove(e.getKey());
            }
        }
        if (requiredParams.size() > 0) {
            for (Iterator<String> iterator = requiredParams.iterator(); iterator.hasNext(); ) {
                String parameterName = (String) iterator.next();
                if (StringUtils.hasText(command.getExpressions().get(parameterName))) {
                    String expression = command.getExpressions().get(parameterName);
                    if (!EvaluationUtil.isExpression(expression)) {
                        errors.rejectValue("expressions[" + parameterName + "]", "reporting.Report.run.error.invalidParamExpression");
                    }
                } else {
                    errors.rejectValue("userEnteredParams[" + parameterName + "]", "error.required", new Object[] { "This parameter" }, "{0} is required");
                }
            }
        }
        if (reportDefinition.getDataSetDefinitions() == null || reportDefinition.getDataSetDefinitions().size() == 0) {
            errors.reject("reporting.Report.run.error.definitionNotDeclared");
        }
        if (ObjectUtil.notNull(command.getSchedule())) {
            if (!CronExpression.isValidExpression(command.getSchedule())) {
                errors.rejectValue("schedule", "reporting.Report.run.error.invalidCronExpression");
            }
        }
    }
    ValidationUtils.rejectIfEmpty(errors, "selectedRenderer", "reporting.Report.run.error.noRendererSelected");
}
Example 13
Project: syncope-master  File: SchedTaskValidator.java View source code
@Override
public boolean isValid(final SchedTask task, final ConstraintValidatorContext context) {
    boolean isValid = true;
    if (!(task instanceof ProvisioningTask)) {
        Class<?> jobDelegateClass = null;
        try {
            jobDelegateClass = ClassUtils.getClass(task.getJobDelegateClassName());
            isValid = SchedTaskJobDelegate.class.isAssignableFrom(jobDelegateClass);
        } catch (Exception e) {
            LOG.error("Invalid JobDelegate class specified", e);
            isValid = false;
        }
        if (jobDelegateClass == null || !isValid) {
            isValid = false;
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(getTemplate(EntityViolationType.InvalidSchedTask, "Invalid job delegate class name")).addPropertyNode("jobDelegateClassName").addConstraintViolation();
        }
    }
    if (isValid && task.getCronExpression() != null) {
        try {
            new CronExpression(task.getCronExpression());
        } catch (ParseException e) {
            LOG.error("Invalid cron expression '" + task.getCronExpression() + "'", e);
            isValid = false;
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(getTemplate(EntityViolationType.InvalidSchedTask, "Invalid cron expression")).addPropertyNode("cronExpression").addConstraintViolation();
        }
    }
    return isValid;
}
Example 14
Project: aurora-master  File: Quartz.java View source code
/**
   * Convert an Aurora CrontabEntry to a Quartz CronExpression.
   */
static CronExpression cronExpression(CrontabEntry entry, TimeZone timeZone) {
    String dayOfMonth;
    if (entry.hasWildcardDayOfMonth()) {
        // special quartz token meaning "don't care"
        dayOfMonth = "?";
    } else {
        dayOfMonth = entry.getDayOfMonthAsString();
    }
    String dayOfWeek;
    if (entry.hasWildcardDayOfWeek() && !entry.hasWildcardDayOfMonth()) {
        dayOfWeek = "?";
    } else {
        List<Integer> daysOfWeek = Lists.newArrayList();
        for (Range<Integer> range : entry.getDayOfWeek().asRanges()) {
            for (int i : ContiguousSet.create(range, DiscreteDomain.integers())) {
                // Quartz has an off-by-one with what the "standard" defines.
                daysOfWeek.add(i + 1);
            }
        }
        dayOfWeek = Joiner.on(",").join(daysOfWeek);
    }
    String rawCronExpresion = String.join(" ", "0", entry.getMinuteAsString(), entry.getHourAsString(), dayOfMonth, entry.getMonthAsString(), dayOfWeek);
    CronExpression cronExpression;
    try {
        cronExpression = new CronExpression(rawCronExpresion);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
    cronExpression.setTimeZone(timeZone);
    return cronExpression;
}
Example 15
Project: dataworks-zeus-master  File: CronExpParser.java View source code
/**
	 * 解�corn表达�,生�指定日期的时间�列
	 * 
	 * @param cronExpression
	 *            cron表达�
	 * @param cronDate
	 *            cron解�日期
	 * @param result
	 *            crom解�时间�列
	 * @return 解��功失败
	 * */
public static boolean Parser(String cronExpression, String cronDate, List<String> result) {
    if (cronExpression == null || cronExpression.length() < 1 || cronDate == null || cronDate.length() < 1) {
        return false;
    } else {
        CronExpression exp = null;
        try {
            // �始化cron表达�解�器
            exp = new CronExpression(cronExpression);
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
        // 定义生�时间范围
        // 定义开始时间,�一天的23点59分59秒
        Calendar c = Calendar.getInstance();
        String sStart = cronDate + " 00:00:00";
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dStart = null;
        try {
            dStart = sdf.parse(sStart);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(dStart);
        c.add(Calendar.SECOND, -1);
        dStart = c.getTime();
        // 定义结�时间,当天的23点59分59秒
        c.add(Calendar.DATE, 1);
        Date dEnd = c.getTime();
        // 生�时间�列
        java.util.Date dd = dStart;
        dd = exp.getNextValidTimeAfter(dd);
        while ((dd.getTime() >= dStart.getTime()) && (dd.getTime() <= dEnd.getTime())) {
            result.add(sdf.format(dd));
            dd = exp.getNextValidTimeAfter(dd);
        }
        exp = null;
    }
    return true;
}
Example 16
Project: openolat-master  File: ReminderModuleTest.java View source code
@Test
public void testCronJob_everyTwoHours() throws ParseException {
    reminderModule.setScheduler("2", "9:30");
    String cron = reminderModule.getCronExpression();
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 5);
    CronExpression cronExpression = new CronExpression(cron);
    Date d1 = cronExpression.getNextValidTimeAfter(cal.getTime());
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(d1);
    Assert.assertEquals(1, cal1.get(Calendar.HOUR_OF_DAY));
    Assert.assertEquals(30, cal1.get(Calendar.MINUTE));
}
Example 17
Project: ReActions-master  File: Timer.java View source code
public void parseTime() {
    if (this.timerType) {
        this.timesIngame = new HashSet<>();
        this.timesIngame.addAll(Arrays.asList(params.getParam("time", "").split(",\\S*")));
    } else {
        String time = params.getParam("time", "").replace("_", " ");
        try {
            this.timeServer = new CronExpression(time);
        } catch (ParseException e) {
            M.logOnce(time, "Failed to parse cron format: " + time);
            this.timeServer = null;
            e.printStackTrace();
        }
    }
}
Example 18
Project: Repository-master  File: QuartzScheduleFactory.java View source code
/**
   * Cron schedule support using {@link CronExpression} validation.
   */
@Override
public Cron cron(final Date startAt, final String cronExpression) {
    checkNotNull(startAt);
    checkArgument(!Strings2.isBlank(cronExpression), "Empty Cron expression");
    // checking with regular-expression
    checkArgument(CRON_PATTERN.matcher(cronExpression).matches(), "Invalid Cron expression: %s", cronExpression);
    // and implementation for better coverage, as the following misses some invalid syntax
    try {
        CronExpression.validateExpression(cronExpression);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Invalid Cron expression: '" + cronExpression + "': " + e.getMessage(), e);
    }
    return new Cron(startAt, cronExpression);
}
Example 19
Project: eMonocot-master  File: HarvestDataJob.java View source code
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    try {
        SchedulerContext schedulerContext = jobExecutionContext.getScheduler().getContext();
        ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get("applicationContext");
        ResourceService resourceService = (ResourceService) applicationContext.getBean(resourceServiceName);
        JobLauncher jobLauncher = (JobLauncher) applicationContext.getBean(jobLauncherName);
        logger.info("HarvestDataJob");
        for (String cronExpression : cronExpressions) {
            CronExpression expression = new CronExpression(cronExpression);
            DateTime now = new DateTime();
            if (expression.isSatisfiedBy(now.toDate()) && !resourceService.isHarvesting()) {
                DateTime nextInvalidDate = new DateTime(expression.getNextInvalidTimeAfter(now.toDate()));
                logger.info(cronExpression + " is satified and resourceService is not harvesting, looking for jobs to harvest . . .");
                List<Resource> resourcesToHarvest = resourceService.listResourcesToHarvest(10, now, "job-with-source");
                Resource resource = null;
                for (Resource r : resourcesToHarvest) {
                    DateTime probableFinishingTime = now.plus(r.getDuration());
                    if (probableFinishingTime.isBefore(nextInvalidDate) && (r.getLastAttempt() == null || r.getLastAttempt().plusHours(MINIMAL_INTERVAL).isBefore(now))) {
                        resource = r;
                        break;
                    }
                }
                if (resource != null) {
                    logger.info("Found that we can harvest " + resource.getTitle());
                    Map<String, String> jobParametersMap = new HashMap<String, String>();
                    jobParametersMap.put("authority.name", resource.getOrganisation().getIdentifier());
                    jobParametersMap.put("authority.uri", resource.getUri());
                    jobParametersMap.put("resource.identifier", resource.getIdentifier());
                    // Prevent jobs failing if a job has been executed with the same parameters
                    jobParametersMap.put("attempt", UUID.randomUUID().toString());
                    jobParametersMap.put("authority.last.harvested", Long.toString((resource.getStartTime().getMillis())));
                    jobParametersMap.putAll(resource.getParameters());
                    JobLaunchRequest jobLaunchRequest = new JobLaunchRequest();
                    jobLaunchRequest.setJob(resource.getResourceType().getJobName());
                    jobLaunchRequest.setParameters(jobParametersMap);
                    try {
                        jobLauncher.launch(jobLaunchRequest);
                        resource.setLastAttempt(now);
                        resource.setStartTime(null);
                        resource.setDuration(null);
                        resource.setExitCode(null);
                        resource.setExitDescription(null);
                        resource.setJobId(null);
                        resource.setStatus(BatchStatus.UNKNOWN);
                        resource.setRecordsRead(0);
                        resource.setReadSkip(0);
                        resource.setProcessSkip(0);
                        resource.setWriteSkip(0);
                        resource.setWritten(0);
                        resourceService.saveOrUpdate(resource);
                    } catch (org.emonocot.api.job.JobExecutionException jee) {
                        throw new JobExecutionException(jee);
                    }
                } else {
                    logger.info("Could not find a resource we can safely harvest in the time available");
                }
            } else {
                logger.info(now + " is not within " + cronExpression + "or resourceService is harvesting, skipping!");
            }
        }
    } catch (ParseException pe) {
        throw new JobExecutionException(pe);
    } catch (SchedulerException se) {
        throw new JobExecutionException(se);
    }
}
Example 20
Project: kylo-master  File: FeedOnTimeArrivalMetricAssessorTest.java View source code
@Before
public void setUp() throws Exception {
    initMocks(this);
    when(this.builder.message(any(String.class))).thenReturn(this.builder);
    when(this.builder.metric(any(Metric.class))).thenReturn(this.builder);
    when(this.builder.result(any(AssessmentResult.class))).thenReturn(this.builder);
    this.assessor.setMetadataAccess(this.metadataAccess);
    // Noon every day
    CronExpression cron = new CronExpression("0 0 12 1/1 * ? *");
    this.lateTime = new DateTime(CronExpressionUtil.getPreviousFireTime(cron)).plusHours(4);
    this.metric = new FeedOnTimeArrivalMetric("feed", cron, Period.hours(lateTimeGracePeriod));
}
Example 21
Project: TadpoleForDBTools-master  File: AddScheduleDialog.java View source code
/**
	 * show cron expression
	 */
private void showExp() {
    StringBuffer sbStr = new StringBuffer();
    try {
        CronExpression exp = new CronExpression(textCronExp.getText());
        java.util.Date showDate = new java.util.Date();
        for (int i = 0; i <= 5; i++) {
            showDate = exp.getNextValidTimeAfter(showDate);
            sbStr.append(convPretty(showDate) + PublicTadpoleDefine.LINE_SEPARATOR);
            showDate = new java.util.Date(showDate.getTime() + 1000);
        }
        textViewSchedule.setText(sbStr.toString());
    } catch (ParseException e) {
        MessageDialog.openError(null, CommonMessages.get().Confirm, Messages.get().AddScheduleDialog_12);
        textCronExp.setFocus();
    }
}
Example 22
Project: azkaban-master  File: Schedule.java View source code
@Override
public String toString() {
    String underlying = projectName + "." + flowName + " (" + projectId + ")" + " to be run at (starting) " + new DateTime(firstSchedTime).toDateTimeISO();
    if (period == null && cronExpression == null) {
        return underlying + " non-recurring";
    } else if (cronExpression != null) {
        return underlying + " with CronExpression {" + cronExpression + "}";
    } else {
        return underlying + " with precurring period of " + createPeriodString(period);
    }
}
Example 23
Project: 5.2.0.RC-master  File: Scheduler.java View source code
// ============================  Trigger start  ===================================
/**
	 * 根�corn获�Trigger
	 */
public static Trigger cornTrigger(String corn) {
    try {
        CronExpression ce = new CronExpression(corn);
        return TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(ce)).build();
    } catch (ParseException e) {
        log.error(" Parse corn=[" + corn + "] exception. ", e);
        throw new RuntimeException(e);
    }
}
Example 24
Project: DisJob-master  File: ScheduleUtils.java View source code
private static void checkJobInfo(final JobInfo scheduleJob) throws SchedulerException {
    if (scheduleJob == null)
        throw new SchedulerException("请输入�数");
    if (//无效
    scheduleJob.getJobName() == null || scheduleJob.getJobName().length() < 1)
        throw new SchedulerException("任务å??称无效");
    if (//无效
    scheduleJob.getCronExpression() == null || !CronExpression.isValidExpression(scheduleJob.getCronExpression()))
        throw new SchedulerException("groupName:" + scheduleJob.getGroupName() + " jobName:" + scheduleJob.getJobName() + "无效的cron时间表达�: " + scheduleJob.getCronExpression());
    if (//为null或�是Job的�类
    scheduleJob.getJobClass() == null || !Job.class.isAssignableFrom(scheduleJob.getJobClass()))
        throw new SchedulerException("无效的JobClass");
}
Example 25
Project: drools-core-master  File: CronExpressionTest.java View source code
/**
     * Verify that the target object and the object we just deserialized 
     * match.
     */
protected void verifyMatch(Object target, Object deserialized) {
    CronExpression targetCronExpression = (CronExpression) target;
    CronExpression deserializedCronExpression = (CronExpression) deserialized;
    assertNotNull(deserializedCronExpression);
    assertEquals(targetCronExpression.getCronExpression(), deserializedCronExpression.getCronExpression());
    assertEquals(targetCronExpression.getTimeZone(), deserializedCronExpression.getTimeZone());
}
Example 26
Project: drools-master  File: CronExpressionTest.java View source code
/**
     * Verify that the target object and the object we just deserialized 
     * match.
     */
protected void verifyMatch(Object target, Object deserialized) {
    CronExpression targetCronExpression = (CronExpression) target;
    CronExpression deserializedCronExpression = (CronExpression) deserialized;
    assertNotNull(deserializedCronExpression);
    assertEquals(targetCronExpression.getCronExpression(), deserializedCronExpression.getCronExpression());
    assertEquals(targetCronExpression.getTimeZone(), deserializedCronExpression.getTimeZone());
}
Example 27
Project: droolsjbpm-master  File: CronExpressionTest.java View source code
/**
     * Verify that the target object and the object we just deserialized 
     * match.
     */
protected void verifyMatch(Object target, Object deserialized) {
    CronExpression targetCronExpression = (CronExpression) target;
    CronExpression deserializedCronExpression = (CronExpression) deserialized;
    assertNotNull(deserializedCronExpression);
    assertEquals(targetCronExpression.getCronExpression(), deserializedCronExpression.getCronExpression());
    assertEquals(targetCronExpression.getTimeZone(), deserializedCronExpression.getTimeZone());
}
Example 28
Project: elasticsearch-river-jira-master  File: CronExpressionTest.java View source code
/*
	 * Test method for 'org.quartz.CronExpression.isSatisfiedBy(Date)'.
	 */
@Test
public void testIsSatisfiedBy() throws Exception {
    CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005");
    Calendar cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 15, 0);
    assertTrue(cronExpression.isSatisfiedBy(cal.getTime()));
    cal.set(Calendar.YEAR, 2006);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
    cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 16, 0);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
    cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 14, 0);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
}
Example 29
Project: elasticsearch-river-remote-master  File: CronExpressionTest.java View source code
/*
	 * Test method for 'org.quartz.CronExpression.isSatisfiedBy(Date)'.
	 */
@Test
public void testIsSatisfiedBy() throws Exception {
    CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005");
    Calendar cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 15, 0);
    assertTrue(cronExpression.isSatisfiedBy(cal.getTime()));
    cal.set(Calendar.YEAR, 2006);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
    cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 16, 0);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
    cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 14, 0);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
}
Example 30
Project: gennai-master  File: SnapshotOperator.java View source code
@Override
protected void prepare() {
    for (Field field : fields) {
        if (field instanceof Function<?>) {
            ((Function<?>) field).prepare(getConfig(), getContext());
        }
    }
    if (interval.getType() == IntervalType.COUNT) {
        counter = 0;
    } else {
        if (snapshotJob == null) {
            snapshotJob = new SnapshotJob();
            try {
                if (interval.getType() == IntervalType.CRON) {
                    getContext().getComponent().getShapshotTimer().cronSchedule(interval.getSchedulingPattern(), snapshotJob);
                } else {
                    getContext().getComponent().getShapshotTimer().periodSchedule(interval.getPeriod(), snapshotJob);
                }
            } catch (SchedulerException e) {
                LOG.error("Failed to add schedule", e);
            }
        }
        snapshotJob.addTask(new CommitTask());
        if (expire != null) {
            if (interval.getType() == IntervalType.CRON) {
                CronExpression cronExpr;
                try {
                    cronExpr = new CronExpression(expire.getSchedulingPattern());
                    expireTime = cronExpr.getNextValidTimeAfter(new Date(GungnirUtils.currentTimeMillis())).getTime();
                } catch (ParseException e) {
                    LOG.error("Failed to parse pattern", e);
                }
            } else {
                expireTime = GungnirUtils.currentTimeMillis() + expire.getPeriod().getTimeUnit().toMillis(expire.getPeriod().getTime());
            }
        }
    }
}
Example 31
Project: iMatrix6.0.0Dev-master  File: Scheduler.java View source code
// ============================  Trigger start  ===================================
/**
	 * 根�corn获�Trigger
	 */
public static Trigger cornTrigger(String corn) {
    try {
        CronExpression ce = new CronExpression(corn);
        return TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(ce)).build();
    } catch (ParseException e) {
        log.error(" Parse corn=[" + corn + "] exception. ", e);
        throw new RuntimeException(e);
    }
}
Example 32
Project: libreplan-master  File: JobSchedulerController.java View source code
/**
     * Sets the <code>cronExpressionTextBox</code> value from the <code>cronExpressionInputPopup</code>.
     */
public void updateCronExpression() {
    String cronExpression = getCronExpressionString();
    try {
        // Check cron expression format
        new CronExpression(cronExpression);
    } catch (ParseException e) {
        LOG.info("Unable to parse cron expression", e);
        throw new WrongValueException(cronExpressionInputPopup, _("Unable to parse cron expression") + ":\n" + e.getMessage());
    }
    cronExpressionTextBox.setValue(cronExpression);
    cronExpressionInputPopup.close();
    Util.saveBindings(cronExpressionTextBox);
}
Example 33
Project: nifi-master  File: StandardProcessorNode.java View source code
@Override
public synchronized void setScheduldingPeriod(final String schedulingPeriod) {
    if (isRunning()) {
        throw new IllegalStateException("Cannot modify Processor configuration while the Processor is running");
    }
    switch(schedulingStrategy) {
        case CRON_DRIVEN:
            {
                try {
                    new CronExpression(schedulingPeriod);
                } catch (final Exception e) {
                    throw new IllegalArgumentException("Scheduling Period is not a valid cron expression: " + schedulingPeriod);
                }
            }
            break;
        case PRIMARY_NODE_ONLY:
        case TIMER_DRIVEN:
            {
                final long schedulingNanos = FormatUtils.getTimeDuration(requireNonNull(schedulingPeriod), TimeUnit.NANOSECONDS);
                if (schedulingNanos < 0) {
                    throw new IllegalArgumentException("Scheduling Period must be positive");
                }
                this.schedulingNanos.set(Math.max(MINIMUM_SCHEDULING_NANOS, schedulingNanos));
            }
            break;
        case EVENT_DRIVEN:
        default:
            return;
    }
    this.schedulingPeriod.set(schedulingPeriod);
}
Example 34
Project: quartz-1.8.3-optivo-master  File: CronExpressionTest.java View source code
/**
     * Verify that the target object and the object we just deserialized 
     * match.
     */
protected void verifyMatch(Object target, Object deserialized) {
    CronExpression targetCronExpression = (CronExpression) target;
    CronExpression deserializedCronExpression = (CronExpression) deserialized;
    assertNotNull(deserializedCronExpression);
    assertEquals(targetCronExpression.getCronExpression(), deserializedCronExpression.getCronExpression());
    assertEquals(targetCronExpression.getTimeZone(), deserializedCronExpression.getTimeZone());
}
Example 35
Project: rx-cron-scheduler-master  File: CronExpressionTest.java View source code
/*
     * Test method for 'org.quartz.CronExpression.isSatisfiedBy(Date)'.
     */
public void testIsSatisfiedBy() throws Exception {
    CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005");
    Calendar cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 15, 0);
    assertTrue(cronExpression.isSatisfiedBy(cal.getTime()));
    cal.set(Calendar.YEAR, 2006);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
    cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 16, 0);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
    cal = Calendar.getInstance();
    cal.set(2005, Calendar.JUNE, 1, 10, 14, 0);
    assertFalse(cronExpression.isSatisfiedBy(cal.getTime()));
}
Example 36
Project: seam-scheduling-master  File: QuartzShedulerManager.java View source code
@Override
public void schedule(Job job, Map<String, Object> parameters) throws SchedulerException {
    String key = JobWrapper.getJobNameKey(job.getName(), job.getGroup().getName());
    //verify if job exists
    if (jobs.containsKey(key)) {
        throw new SchedulerException("Job " + job.toString() + " alread exists");
    }
    //validate job
    job.validate();
    //create job detail
    JobDetail jobDetail = new JobDetail(job.getName(), job.getGroup().getName(), QuartzJob.class);
    jobDetail.getJobDataMap().put(TASK_PARAM, parameters);
    jobDetail.getJobDataMap().put(TASK, job.getTask());
    //criate expression to validate it
    CronExpression cronExpression = null;
    try {
        cronExpression = new CronExpression(job.getCronExpression());
    } catch (ParseException ex) {
        log.error(ex.getMessage());
        throw new SchedulerException("Invalid cron expression for job " + job.toString());
    }
    try {
        this.scheduler.addJob(jobDetail, true);
    } catch (org.quartz.SchedulerException ex) {
        log.error(ex.getMessage());
        throw new SchedulerException("Problem adding job " + job.toString());
    }
    //verify if job will start automatically
    if (job.isAutoStart()) {
        startJob(job);
    }
    //add job into job list
    jobs.put(key, job);
    log.info("Scheduler for {} initialised", job.toString());
}
Example 37
Project: Singularity-master  File: SingularityScheduler.java View source code
private Optional<Long> getNextRunAt(SingularityRequest request, RequestState state, SingularityDeployStatistics deployStatistics, PendingType pendingType, Optional<SingularityPendingDeploy> maybePendingDeploy) {
    final long now = System.currentTimeMillis();
    long nextRunAt = now;
    if (request.isScheduled()) {
        if (pendingType == PendingType.IMMEDIATE || pendingType == PendingType.RETRY) {
            LOG.info("Scheduling requested immediate run of {}", request.getId());
        } else {
            try {
                Date nextRunAtDate = null;
                Date scheduleFrom = null;
                if (request.getScheduleTypeSafe() == ScheduleType.RFC5545) {
                    final RFC5545Schedule rfc5545Schedule = new RFC5545Schedule(request.getSchedule().get());
                    nextRunAtDate = rfc5545Schedule.getNextValidTime();
                    scheduleFrom = new Date(rfc5545Schedule.getStartDateTime().getMillis());
                } else {
                    scheduleFrom = new Date(now);
                    final CronExpression cronExpression = new CronExpression(request.getQuartzScheduleSafe());
                    if (request.getScheduleTimeZone().isPresent()) {
                        cronExpression.setTimeZone(TimeZone.getTimeZone(request.getScheduleTimeZone().get()));
                    }
                    nextRunAtDate = cronExpression.getNextValidTimeAfter(scheduleFrom);
                }
                if (nextRunAtDate == null) {
                    return Optional.absent();
                }
                LOG.trace("Calculating nextRunAtDate for {} (schedule: {}): {} (from: {})", request.getId(), request.getSchedule(), nextRunAtDate, scheduleFrom);
                // don't create a schedule that is overdue as this is used to indicate that singularity is not fulfilling requests.
                nextRunAt = Math.max(nextRunAtDate.getTime(), now);
                LOG.trace("Scheduling next run of {} (schedule: {}) at {} (from: {})", request.getId(), request.getSchedule(), nextRunAtDate, scheduleFrom);
            } catch (ParseExceptionInvalidRecurrenceRuleException |  pe) {
                throw Throwables.propagate(pe);
            }
        }
    }
    if (pendingType == PendingType.TASK_DONE && request.getWaitAtLeastMillisAfterTaskFinishesForReschedule().or(0L) > 0) {
        nextRunAt = Math.max(nextRunAt, now + request.getWaitAtLeastMillisAfterTaskFinishesForReschedule().get());
        LOG.trace("Adjusted next run of {} to {} (by {}) due to waitAtLeastMillisAfterTaskFinishesForReschedule", request.getId(), nextRunAt, JavaUtils.durationFromMillis(request.getWaitAtLeastMillisAfterTaskFinishesForReschedule().get()));
    }
    if (state == RequestState.SYSTEM_COOLDOWN && pendingType != PendingType.NEW_DEPLOY) {
        final long prevNextRunAt = nextRunAt;
        nextRunAt = Math.max(nextRunAt, now + TimeUnit.SECONDS.toMillis(configuration.getCooldownMinScheduleSeconds()));
        LOG.trace("Adjusted next run of {} to {} (from: {}) due to cooldown", request.getId(), nextRunAt, prevNextRunAt);
    }
    return Optional.of(nextRunAt);
}
Example 38
Project: av-sched-master  File: JobSchedulingServiceImpl.java View source code
private void validate(JobScheduling scheduling) throws AppException {
    Validate.notNull(scheduling);
    if (scheduling.getType() == null) {
        throw new AppException("missing.scheduling.type");
    }
    if (scheduling.getType() == JobSchedulingType.CRON) {
        if (StringUtils.isEmpty(scheduling.getValue()))
            throw new AppException("missing.schedule.value");
        try {
            CronExpression.validateExpression(scheduling.getValue());
        } catch (ParseException e) {
            throw new AppException("invalid.schedule.value", Arrays.asList(scheduling.getValue()));
        }
    }
    if (scheduling.getType() == JobSchedulingType.WAKEUP) {
        if (StringUtils.isEmpty(scheduling.getValue()))
            throw new AppException("missing.schedule.value");
        if (!NumberUtils.isDigits(scheduling.getValue()))
            throw new AppException("invalid.schedule.value");
    }
}
Example 39
Project: che-master  File: CronExpressionTest.java View source code
/**
     * Verify that the target object and the object we just deserialized
     * match.
     */
protected void verifyMatch(Object target, Object deserialized) {
    CronExpression targetCronExpression = (CronExpression) target;
    CronExpression deserializedCronExpression = (CronExpression) deserialized;
    assertNotNull(deserializedCronExpression);
    assertEquals(targetCronExpression.getCronExpression(), deserializedCronExpression.getCronExpression());
    assertEquals(targetCronExpression.getTimeZone(), deserializedCronExpression.getTimeZone());
}
Example 40
Project: DevTools-master  File: CronExpressionTest.java View source code
/**
     * Verify that the target object and the object we just deserialized
     * match.
     */
protected void verifyMatch(Object target, Object deserialized) {
    CronExpression targetCronExpression = (CronExpression) target;
    CronExpression deserializedCronExpression = (CronExpression) deserialized;
    assertNotNull(deserializedCronExpression);
    assertEquals(targetCronExpression.getCronExpression(), deserializedCronExpression.getCronExpression());
    assertEquals(targetCronExpression.getTimeZone(), deserializedCronExpression.getTimeZone());
}
Example 41
Project: hwi-master  File: RCrontab.java View source code
@POST
@Path("create")
@Produces("text/html;charset=ISO-8859-1")
public Viewable create(@FormParam(value = "name") String name, @FormParam(value = "query") String query, @FormParam(value = "callback") String callback, @FormParam(value = "hour") String hour, @FormParam(value = "day") String day, @FormParam(value = "month") String month, @FormParam(value = "week") String week) {
    Viewable v = new Viewable("/crontab/create.vm");
    request.setAttribute("name", name);
    request.setAttribute("query", query);
    request.setAttribute("callback", callback);
    request.setAttribute("hour", hour);
    request.setAttribute("day", day);
    request.setAttribute("month", month);
    request.setAttribute("week", week);
    if (name == null || name.equals("")) {
        request.setAttribute("msg", "name can't be empty");
        return v;
    }
    if (query == null || query.equals("")) {
        request.setAttribute("msg", "query can't be empty");
        return v;
    }
    if (hour == null || hour.equals("")) {
        request.setAttribute("msg", "hour can't be empty");
        return v;
    }
    if (day == null || day.equals("")) {
        request.setAttribute("msg", "day can't be empty");
        return v;
    }
    if (month == null || month.equals("")) {
        request.setAttribute("msg", "month can't be empty");
        return v;
    }
    if (week == null || week.equals("")) {
        request.setAttribute("msg", "week can't be empty");
        return v;
    }
    String crontab = "0 0 " + hour + " " + day + " " + month + " " + week + " *";
    try {
        CronExpression.validateExpression(crontab);
    } catch (Exception e) {
        request.setAttribute("msg", "crontab: " + e.getMessage());
        return v;
    }
    QueryStore qs = QueryStore.getInstance();
    MCrontab mcrontab = new MCrontab(name, query, callback, crontab, "hadoop", "hadoop");
    qs.insertCrontab(mcrontab);
    QueryManager.getInstance().schedule(mcrontab);
    throw new WebApplicationException(Response.seeOther(URI.create("crontabs/" + mcrontab.getId())).build());
}
Example 42
Project: yajsw-master  File: TimerImpl.java View source code
/**
	 * Gets the cron trigger.
	 * 
	 * @param key
	 *            the key
	 * 
	 * @return the cron trigger
	 */
private MyCronTrigger getCronTrigger(String key) {
    JobDetail jobDetail = new JobDetail();
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("process", _wp);
    jobDetail.setJobDataMap(jobDataMap);
    jobDetail.setName(key);
    Class jobClass = getJobClass(key);
    if (jobClass == null)
        return null;
    jobDetail.setJobClass(jobClass);
    MyCronTrigger trigger = new MyCronTrigger(jobDetail);
    CronExpression cronExpression = getCronExpression(key);
    if (cronExpression != null) {
        trigger.setCronExpression(cronExpression);
        if (jobClass.equals(StartJob.class))
            _startImmediate = false;
        _hasTrigger = true;
    } else {
        return null;
    }
    trigger.setName(key);
    trigger.setMisfireInstruction(trigger.MISFIRE_INSTRUCTION_FIRE_ONCE_NOW);
    return trigger;
}
Example 43
Project: yajsw-maven-master  File: TimerImpl.java View source code
/**
	 * Gets the cron trigger.
	 * 
	 * @param key
	 *            the key
	 * 
	 * @return the cron trigger
	 */
private MyCronTrigger getCronTrigger(String key) {
    JobDetail jobDetail = new JobDetail();
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("process", _wp);
    jobDetail.setJobDataMap(jobDataMap);
    jobDetail.setName(key);
    Class jobClass = getJobClass(key);
    if (jobClass == null)
        return null;
    jobDetail.setJobClass(jobClass);
    MyCronTrigger trigger = new MyCronTrigger(jobDetail);
    CronExpression cronExpression = getCronExpression(key);
    if (cronExpression != null) {
        trigger.setCronExpression(cronExpression);
        if (jobClass.equals(StartJob.class))
            _startImmediate = false;
        _hasTrigger = true;
    } else {
        return null;
    }
    trigger.setName(key);
    trigger.setMisfireInstruction(trigger.MISFIRE_INSTRUCTION_FIRE_ONCE_NOW);
    return trigger;
}
Example 44
Project: yajsw-maven-mk2-master  File: TimerImpl.java View source code
/**
	 * Gets the cron trigger.
	 * 
	 * @param key
	 *            the key
	 * 
	 * @return the cron trigger
	 */
private MyCronTrigger getCronTrigger(String key) {
    JobDetail jobDetail = new JobDetail();
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("process", _wp);
    jobDetail.setJobDataMap(jobDataMap);
    jobDetail.setName(key);
    Class jobClass = getJobClass(key);
    if (jobClass == null)
        return null;
    jobDetail.setJobClass(jobClass);
    MyCronTrigger trigger = new MyCronTrigger(jobDetail);
    CronExpression cronExpression = getCronExpression(key);
    if (cronExpression != null) {
        trigger.setCronExpression(cronExpression);
        if (jobClass.equals(StartJob.class))
            _startImmediate = false;
        _hasTrigger = true;
    } else {
        return null;
    }
    trigger.setName(key);
    trigger.setMisfireInstruction(trigger.MISFIRE_INSTRUCTION_FIRE_ONCE_NOW);
    return trigger;
}
Example 45
Project: carbon-business-process-master  File: HumanTaskServerConfiguration.java View source code
private void iniTaskCleanupConfig(TTaskCleanupConfig taskCleanupConfig) {
    if (taskCleanupConfig != null) {
        if (StringUtils.isNotEmpty(taskCleanupConfig.getCronExpression())) {
            if (CronExpression.isValidExpression(taskCleanupConfig.getCronExpression().trim())) {
                this.taskCleanupCronExpression = taskCleanupConfig.getCronExpression();
            } else {
                String warnMsg = String.format("The task clean up cron expression[%s] is invalid." + " Ignoring task clean up configurations! ", taskCleanupConfig.getCronExpression());
                log.warn(warnMsg);
                return;
            }
        }
        if (StringUtils.isNotEmpty(taskCleanupConfig.getStatuses())) {
            String[] removableStatusesArray = taskCleanupConfig.getStatuses().split(",");
            List<TaskStatus> removableTaskStatusList = new ArrayList<TaskStatus>();
            for (String removableStatus : removableStatusesArray) {
                for (TaskStatus taskStatusEnum : TaskStatus.values()) {
                    if (taskStatusEnum.toString().equals(removableStatus.trim())) {
                        removableTaskStatusList.add(taskStatusEnum);
                        break;
                    }
                }
            }
            this.removableTaskStatuses = removableTaskStatusList;
        }
    }
}
Example 46
Project: Glue-master  File: XxlJobServiceImpl.java View source code
@Override
public ReturnT<String> add(XxlJobInfo jobInfo) {
    // valid
    XxlJobGroup group = xxlJobGroupDao.load(jobInfo.getJobGroup());
    if (group == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请选择“执行器�");
    }
    if (!CronExpression.isValidExpression(jobInfo.getJobCron())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入格�正确的“Cron�");
    }
    if (StringUtils.isBlank(jobInfo.getJobDesc())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入“任务æ??è¿°â€?");
    }
    if (StringUtils.isBlank(jobInfo.getAuthor())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入“负责人�");
    }
    if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "路由策略�法");
    }
    if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "阻塞处�策略�法");
    }
    if (ExecutorFailStrategyEnum.match(jobInfo.getExecutorFailStrategy(), null) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "失败处�策略�法");
    }
    if (GlueTypeEnum.match(jobInfo.getGlueType()) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "�行模��法�法");
    }
    if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType()) && StringUtils.isBlank(jobInfo.getExecutorHandler())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入“JobHandler�");
    }
    // fix "\r" in shell
    if (GlueTypeEnum.GLUE_SHELL == GlueTypeEnum.match(jobInfo.getGlueType()) && jobInfo.getGlueSource() != null) {
        jobInfo.setGlueSource(jobInfo.getGlueSource().replaceAll("\r", ""));
    }
    // childJobKey valid
    if (StringUtils.isNotBlank(jobInfo.getChildJobKey())) {
        String[] childJobKeys = jobInfo.getChildJobKey().split(",");
        for (String childJobKeyItem : childJobKeys) {
            String[] childJobKeyArr = childJobKeyItem.split("_");
            if (childJobKeyArr.length != 2) {
                return new ReturnT<String>(ReturnT.FAIL_CODE, MessageFormat.format("�任务Key({0})格�错误", childJobKeyItem));
            }
            XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.valueOf(childJobKeyArr[1]));
            if (childJobInfo == null) {
                return new ReturnT<String>(ReturnT.FAIL_CODE, MessageFormat.format("�任务Key({0})无效", childJobKeyItem));
            }
        }
    }
    // add in db
    xxlJobInfoDao.save(jobInfo);
    if (jobInfo.getId() < 1) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "新增任务失败");
    }
    // add in quartz
    String qz_group = String.valueOf(jobInfo.getJobGroup());
    String qz_name = String.valueOf(jobInfo.getId());
    try {
        XxlJobDynamicScheduler.addJob(qz_name, qz_group, jobInfo.getJobCron());
        //XxlJobDynamicScheduler.pauseJob(qz_name, qz_group);
        return ReturnT.SUCCESS;
    } catch (SchedulerException e) {
        logger.error("", e);
        try {
            xxlJobInfoDao.delete(jobInfo.getId());
            XxlJobDynamicScheduler.removeJob(qz_name, qz_group);
        } catch (SchedulerException e1) {
            logger.error("", e1);
        }
        return new ReturnT<String>(ReturnT.FAIL_CODE, "新增任务失败:" + e.getMessage());
    }
}
Example 47
Project: jmxtrans-master  File: JmxTransformer.java View source code
private Trigger createTrigger(Server server) throws ParseException {
    int runPeriod = configuration.getRunPeriod();
    Trigger trigger;
    if (server.getCronExpression() != null && CronExpression.isValidExpression(server.getCronExpression())) {
        CronTrigger cTrigger = new CronTrigger();
        cTrigger.setCronExpression(server.getCronExpression());
        trigger = cTrigger;
    } else {
        if (server.getRunPeriodSeconds() != null) {
            runPeriod = server.getRunPeriodSeconds();
        }
        trigger = TriggerUtils.makeSecondlyTrigger(runPeriod);
    // TODO replace Quartz with a ScheduledExecutorService
    }
    trigger.setName(server.getHost() + ":" + server.getPort() + "-" + Long.toString(System.nanoTime()));
    trigger.setStartTime(computeSpreadStartDate(runPeriod));
    return trigger;
}
Example 48
Project: riot-master  File: CacheAnnotationHandlerAdapter.java View source code
private void applyContextSettings() throws ParseException {
    if (annotation != null) {
        if (annotation.serveStaleOnError()) {
            CacheContext.serveStaleOnError();
        }
        if (annotation.serveStaleUntilExpired()) {
            CacheContext.serveStaleUntilExpired();
        }
        if (annotation.serveStaleWhileRevalidate()) {
            CacheContext.serveStaleWhileRevalidate();
        }
        Long expireIn = null;
        if (StringUtils.hasText(annotation.ttl())) {
            expireIn = FormatUtils.parseMillis(annotation.ttl());
        }
        if (StringUtils.hasText(annotation.cron())) {
            CronExpression cron = new CronExpression(annotation.cron());
            long delta = cron.getNextValidTimeAfter(new Date()).getTime() - System.currentTimeMillis();
            if (expireIn == null || delta < expireIn) {
                expireIn = delta;
            }
        }
        if (expireIn != null) {
            CacheContext.expireIn(expireIn);
        } else if (lastModifiedMethod != null) {
            CacheContext.expireIn(0);
        }
    }
}
Example 49
Project: Saturn-master  File: ConfigurationService.java View source code
/**
     * 更新作业的cron表达�
     * @param jobName 作业å??
     * @param cron cron表达�
     * @param customContext 自定义上下文
     * @throws SaturnJobException å?¯èƒ½æŠ›çš„异常有:type为0,表示cron表达å¼?无效;type为1,表示作业å??在这个namespace下ä¸?存在;type为3,表示customContext内容超出1M。
     */
public void updateJobCron(String jobName, String cron, Map<String, String> customContext) throws SaturnJobException {
    String cron0 = cron;
    if (cron0 != null && !cron0.trim().isEmpty()) {
        try {
            cron0 = cron0.trim();
            CronExpression.validateExpression(cron0);
        } catch (ParseException e) {
            throw new SaturnJobException(SaturnJobException.CRON_VALID, "The cron expression is valid: " + cron);
        }
    } else {
        cron0 = "";
    }
    if (getJobNodeStorage().isJobExisted(jobName)) {
        String oldCustomContextStr = getJobNodeStorage().getJobNodeDataDirectly(jobName, ConfigurationNode.CUSTOME_CONTEXT);
        Map<String, String> oldCustomContextMap = toCustomContext(oldCustomContextStr);
        if (customContext != null && !customContext.isEmpty()) {
            oldCustomContextMap.putAll(customContext);
            String newCustomContextStr = toCustomContext(oldCustomContextMap);
            if (newCustomContextStr.getBytes().length > 1024 * 1024) {
                throw new SaturnJobException(SaturnJobException.OUT_OF_ZK_LIMIT_MEMORY, "The all customContext is out of zk limit memory(1M)");
            }
            getJobNodeStorage().replaceJobNode(jobName, ConfigurationNode.CUSTOME_CONTEXT, newCustomContextStr);
        }
        String oldCron = getJobNodeStorage().getJobNodeDataDirectly(jobName, ConfigurationNode.CRON);
        if (cron0 != null && oldCron != null && !cron0.equals(oldCron.trim())) {
            getJobNodeStorage().updateJobNode(jobName, ConfigurationNode.CRON, cron0);
        }
    } else {
        throw new SaturnJobException(SaturnJobException.JOB_NOT_FOUND, "The job is not found: " + jobName);
    }
}
Example 50
Project: sling-master  File: QuartzScheduler.java View source code
/**
     * @see org.apache.sling.commons.scheduler.Scheduler#EXPR(java.lang.String)
     */
public ScheduleOptions EXPR(final String expression) {
    if (expression == null) {
        return new InternalScheduleOptions(new IllegalArgumentException("Expression can't be null"));
    }
    if (!CronExpression.isValidExpression(expression)) {
        return new InternalScheduleOptions(new IllegalArgumentException("Expressionis invalid : " + expression));
    }
    return new InternalScheduleOptions(TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(expression)));
}
Example 51
Project: xxl-job-master  File: XxlJobServiceImpl.java View source code
@Override
public ReturnT<String> add(XxlJobInfo jobInfo) {
    // valid
    XxlJobGroup group = xxlJobGroupDao.load(jobInfo.getJobGroup());
    if (group == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请选择“执行器�");
    }
    if (!CronExpression.isValidExpression(jobInfo.getJobCron())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入格�正确的“Cron�");
    }
    if (StringUtils.isBlank(jobInfo.getJobDesc())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入“任务æ??è¿°â€?");
    }
    if (StringUtils.isBlank(jobInfo.getAuthor())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入“负责人�");
    }
    if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "路由策略�法");
    }
    if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "阻塞处�策略�法");
    }
    if (ExecutorFailStrategyEnum.match(jobInfo.getExecutorFailStrategy(), null) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "失败处�策略�法");
    }
    if (GlueTypeEnum.match(jobInfo.getGlueType()) == null) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "�行模��法�法");
    }
    if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType()) && StringUtils.isBlank(jobInfo.getExecutorHandler())) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入“JobHandler�");
    }
    // fix "\r" in shell
    if (GlueTypeEnum.GLUE_SHELL == GlueTypeEnum.match(jobInfo.getGlueType()) && jobInfo.getGlueSource() != null) {
        jobInfo.setGlueSource(jobInfo.getGlueSource().replaceAll("\r", ""));
    }
    // childJobKey valid
    if (StringUtils.isNotBlank(jobInfo.getChildJobKey())) {
        String[] childJobKeys = jobInfo.getChildJobKey().split(",");
        for (String childJobKeyItem : childJobKeys) {
            String[] childJobKeyArr = childJobKeyItem.split("_");
            if (childJobKeyArr.length != 2) {
                return new ReturnT<String>(ReturnT.FAIL_CODE, MessageFormat.format("�任务Key({0})格�错误", childJobKeyItem));
            }
            XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.valueOf(childJobKeyArr[1]));
            if (childJobInfo == null) {
                return new ReturnT<String>(ReturnT.FAIL_CODE, MessageFormat.format("�任务Key({0})无效", childJobKeyItem));
            }
        }
    }
    // add in db
    xxlJobInfoDao.save(jobInfo);
    if (jobInfo.getId() < 1) {
        return new ReturnT<String>(ReturnT.FAIL_CODE, "新增任务失败");
    }
    // add in quartz
    String qz_group = String.valueOf(jobInfo.getJobGroup());
    String qz_name = String.valueOf(jobInfo.getId());
    try {
        XxlJobDynamicScheduler.addJob(qz_name, qz_group, jobInfo.getJobCron());
        //XxlJobDynamicScheduler.pauseJob(qz_name, qz_group);
        return ReturnT.SUCCESS;
    } catch (SchedulerException e) {
        logger.error("", e);
        try {
            xxlJobInfoDao.delete(jobInfo.getId());
            XxlJobDynamicScheduler.removeJob(qz_name, qz_group);
        } catch (SchedulerException e1) {
            logger.error("", e1);
        }
        return new ReturnT<String>(ReturnT.FAIL_CODE, "新增任务失败:" + e.getMessage());
    }
}
Example 52
Project: BETaaS_Platform-Tools-master  File: MonitorableAgreement.java View source code
private Trigger createCronTrigger(String name) throws Exception {
    //
    // create the cron trigger for job monitoring
    //
    CronTrigger trigger = new CronTrigger();
    try {
        if (CronExpression.isValidExpression(cronExpression)) {
            trigger.setCronExpression(cronExpression);
        } else {
            LOG.error(LogMessage.getMessage("Invalid cron expression ({0}). Using default monitoring schedule ({1}).", cronExpression, DEFAULT_SCHEDULE));
            trigger.setCronExpression(DEFAULT_SCHEDULE);
        }
    } catch (ParseException e) {
        String msgText = "Invalid default schedule <{0}>. Monitoring not scheduled.";
        String message = LogMessage.format(msgText, DEFAULT_SCHEDULE);
        throw new Exception(message, e);
    }
    trigger.setGroup(JOB_GROUP);
    trigger.setName(name);
    return trigger;
}
Example 53
Project: dog-master  File: SpChainsOSGi.java View source code
@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
    if (properties != null) {
        // get the configuration parameters
        String mappingFileName = (String) properties.get(SpChainsOSGi.MAPPING_FILE);
        String processorFileName = (String) properties.get(SpChainsOSGi.PROCESSOR_FILE);
        String refreshTimeMillisAsString = (String) properties.get(PROCESSOR_REFRESH);
        String startAt = (String) properties.get(PROCESSOR_START_AT);
        // debug
        this.logger.log(LogService.LOG_DEBUG, SpChainsOSGi.logId + "Mapping file: " + mappingFileName + " Processor file: " + processorFileName + " Refresh time (ms): " + refreshTimeMillisAsString);
        // check files
        this.sourceMappingFile = new File(System.getProperty("configFolder") + "/" + mappingFileName);
        this.processorXMLFile = new File(System.getProperty("configFolder") + "/" + processorFileName);
        if ((this.sourceMappingFile != null) && (this.processorXMLFile != null) && (this.sourceMappingFile.exists()) && (this.processorXMLFile.exists())) {
            // file exist, can configure the processor...
            if ((refreshTimeMillisAsString != null) && (!refreshTimeMillisAsString.isEmpty())) {
                // check the refresh time
                try {
                    this.refreshTimeMillis = Integer.valueOf(refreshTimeMillisAsString);
                } catch (NumberFormatException e) {
                    this.logger.log(LogService.LOG_WARNING, SpChainsOSGi.logId + "Refresh time cannot be parsed, setting the default refresh time at 30s");
                } finally {
                    this.refreshTimeMillis = SpChainsOSGi.defaultRefreshTimeMillis;
                }
                // everything ready,
                // initialize the stream processor
                this.initProcessor(this.processorXMLFile, this.refreshTimeMillis);
                // initialize the sources
                this.initSources(this.sourceMappingFile);
                // initialize the drains
                this.initDrains();
                // initialize the queues
                this.inQueue = new IncomingEventQueue(this.logger, this.sp);
                this.outQueue = new OutgoingEventQueue(this.logger, this.eventAdmin);
                if (startAt != null) {
                    try {
                        // create a cron expression fro the given parameter
                        CronExpression cronExp = new CronExpression(startAt);
                        // get the next valid date
                        Date startTime = cronExp.getNextValidTimeAfter(new Date());
                        // log the start time
                        this.logger.log(LogService.LOG_INFO, SpChainsOSGi.logId + "Scheduled start at: " + startTime);
                        // create a new scheduler
                        SchedulerFactory sFactory = new StdSchedulerFactory();
                        Scheduler scheduler = sFactory.getScheduler();
                        // create a simple trigger
                        SimpleTrigger trigger = new SimpleTrigger();
                        // set the trigger name
                        trigger.setName("startTrigger");
                        // set the trigger to start at the next valid date
                        trigger.setStartTime(startTime);
                        // set fire count at 1 (just one call to start())
                        trigger.setRepeatCount(0);
                        trigger.setRepeatInterval(10);
                        // define a job to start (StartJob, basically calls
                        // the
                        // spManager.start()) method)
                        JobDetail jobDetail = new JobDetail("start", "1", StartJob.class);
                        jobDetail.getJobDataMap().put("managerToStart", this);
                        scheduler.scheduleJob(jobDetail, trigger);
                        // start the scheduler
                        scheduler.start();
                    } catch (Exception e) {
                        this.logger.log(LogService.LOG_WARNING, SpChainsOSGi.logId + "Unable to start at scheduled time, starting immediately...");
                        this.start();
                    }
                } else {
                    // direct start
                    this.start();
                }
                this.ready = true;
            }
        } else {
            // error
            this.logger.log(LogService.LOG_ERROR, SpChainsOSGi.logId + "Configuration files are missing or empty, the stream processor service will not be running");
        }
    }
}
Example 54
Project: incubator-zeppelin-master  File: NotebookRestApi.java View source code
/**
   * Register cron job REST API
   * @param message - JSON with cron expressions.
   * @return JSON with status.OK
   * @throws IOException, IllegalArgumentException
   */
@POST
@Path("cron/{notebookId}")
public Response registerCronJob(@PathParam("notebookId") String notebookId, String message) throws IOException, IllegalArgumentException {
    LOG.info("Register cron job note={} request cron msg={}", notebookId, message);
    CronRequest request = gson.fromJson(message, CronRequest.class);
    Note note = notebook.getNote(notebookId);
    if (note == null) {
        return new JsonResponse<>(Status.NOT_FOUND, "note not found.").build();
    }
    if (!CronExpression.isValidExpression(request.getCronString())) {
        return new JsonResponse<>(Status.BAD_REQUEST, "wrong cron expressions.").build();
    }
    Map<String, Object> config = note.getConfig();
    config.put("cron", request.getCronString());
    note.setConfig(config);
    notebook.refreshCron(note.id());
    return new JsonResponse<>(Status.OK).build();
}
Example 55
Project: pinot-master  File: AnomalyResource.java View source code
// Add anomaly function
@POST
@Path("/anomaly-function/create")
public Response createAnomalyFunction(@NotNull @QueryParam("dataset") String dataset, @NotNull @QueryParam("functionName") String functionName, @NotNull @QueryParam("metric") String metric, @NotNull @QueryParam("metricFunction") String metric_function, @QueryParam("type") String type, @NotNull @QueryParam("windowSize") String windowSize, @NotNull @QueryParam("windowUnit") String windowUnit, @QueryParam("windowDelay") String windowDelay, @QueryParam("cron") String cron, @QueryParam("windowDelayUnit") String windowDelayUnit, @QueryParam("exploreDimension") String exploreDimensions, @QueryParam("filters") String filters, @NotNull @QueryParam("properties") String properties, @QueryParam("isActive") boolean isActive) throws Exception {
    if (StringUtils.isEmpty(dataset) || StringUtils.isEmpty(functionName) || StringUtils.isEmpty(metric) || StringUtils.isEmpty(windowSize) || StringUtils.isEmpty(windowUnit) || StringUtils.isEmpty(properties)) {
        throw new UnsupportedOperationException("Received null for one of the mandatory params: " + "dataset " + dataset + ", functionName " + functionName + ", metric " + metric + ", windowSize " + windowSize + ", windowUnit " + windowUnit + ", properties" + properties);
    }
    DatasetConfigDTO datasetConfig = DAO_REGISTRY.getDatasetConfigDAO().findByDataset(dataset);
    TimeSpec timespec = ThirdEyeUtils.getTimeSpecFromDatasetConfig(datasetConfig);
    TimeGranularity dataGranularity = timespec.getDataGranularity();
    AnomalyFunctionDTO anomalyFunctionSpec = new AnomalyFunctionDTO();
    anomalyFunctionSpec.setActive(isActive);
    anomalyFunctionSpec.setMetricFunction(MetricAggFunction.valueOf(metric_function));
    anomalyFunctionSpec.setCollection(dataset);
    anomalyFunctionSpec.setFunctionName(functionName);
    anomalyFunctionSpec.setTopicMetric(metric);
    anomalyFunctionSpec.setMetrics(Arrays.asList(metric));
    if (StringUtils.isEmpty(type)) {
        type = DEFAULT_FUNCTION_TYPE;
    }
    anomalyFunctionSpec.setType(type);
    anomalyFunctionSpec.setWindowSize(Integer.valueOf(windowSize));
    anomalyFunctionSpec.setWindowUnit(TimeUnit.valueOf(windowUnit));
    // Setting window delay time / unit
    TimeUnit dataGranularityUnit = dataGranularity.getUnit();
    // default window delay time = 10 hours
    int windowDelayTime;
    TimeUnit windowDelayTimeUnit;
    switch(dataGranularityUnit) {
        case MINUTES:
            windowDelayTime = 30;
            windowDelayTimeUnit = TimeUnit.MINUTES;
            break;
        case DAYS:
            windowDelayTime = 0;
            windowDelayTimeUnit = TimeUnit.DAYS;
            break;
        case HOURS:
        default:
            windowDelayTime = 10;
            windowDelayTimeUnit = TimeUnit.HOURS;
    }
    anomalyFunctionSpec.setWindowDelayUnit(windowDelayTimeUnit);
    anomalyFunctionSpec.setWindowDelay(windowDelayTime);
    // bucket size and unit are defaulted to the collection granularity
    anomalyFunctionSpec.setBucketSize(dataGranularity.getSize());
    anomalyFunctionSpec.setBucketUnit(dataGranularity.getUnit());
    if (StringUtils.isNotEmpty(exploreDimensions)) {
        anomalyFunctionSpec.setExploreDimensions(getDimensions(dataset, exploreDimensions));
    }
    if (!StringUtils.isBlank(filters)) {
        filters = URLDecoder.decode(filters, UTF8);
        String filterString = ThirdEyeUtils.getSortedFiltersFromJson(filters);
        anomalyFunctionSpec.setFilters(filterString);
    }
    anomalyFunctionSpec.setProperties(properties);
    if (StringUtils.isEmpty(cron)) {
        cron = DEFAULT_CRON;
    } else {
        // validate cron
        if (!CronExpression.isValidExpression(cron)) {
            throw new IllegalArgumentException("Invalid cron expression for cron : " + cron);
        }
    }
    anomalyFunctionSpec.setCron(cron);
    Long id = anomalyFunctionDAO.save(anomalyFunctionSpec);
    return Response.ok(id).build();
}
Example 56
Project: siddhi-master  File: DefinitionParserHelper.java View source code
public static void validateDefinition(TriggerDefinition triggerDefinition) {
    if (triggerDefinition.getId() != null) {
        if (triggerDefinition.getAtEvery() == null) {
            String expression = triggerDefinition.getAt();
            if (expression == null) {
                throw new ExecutionPlanValidationException("Trigger Definition '" + triggerDefinition.getId() + "' must have trigger time defined");
            } else {
                if (!expression.trim().equalsIgnoreCase(SiddhiConstants.TRIGGER_START)) {
                    try {
                        org.quartz.CronExpression.isValidExpression(expression);
                    } catch (Throwable t) {
                        throw new ExecutionPlanValidationException("Trigger Definition '" + triggerDefinition.getId() + "' have invalid trigger time defined, expected 'start' or valid cron but found '" + expression + "'");
                    }
                }
            }
        } else if (triggerDefinition.getAt() != null) {
            throw new ExecutionPlanValidationException("Trigger Definition '" + triggerDefinition.getId() + "' " + "must either have trigger time in cron or 'start' or time interval defined, and it cannot " + "have more than one defined as '" + triggerDefinition + "'");
        }
    } else {
        throw new ExecutionPlanValidationException("Trigger Definition id cannot be null");
    }
}
Example 57
Project: smart-generator-engine-master  File: ReportConfigServiceImpl.java View source code
protected List<Date> getSchedules(ReportConfig config, final Date startDate) {
    try {
        CronExpression expression = new CronExpression(config.getTrigger());
        List<Date> schedules = new ArrayList<Date>(getScheduleSize());
        Date baseDate = startDate == null ? new Date() : startDate;
        for (int i = 0; i < getScheduleSize(); ++i) {
            final Date nextDate = expression.getNextValidTimeAfter(baseDate);
            schedules.add(nextDate);
            baseDate = nextDate;
        }
        return schedules;
    } catch (ParseException ex) {
        logger.warn("Could not parse expression!", ex);
        throw new IllegalStateException(ex);
    } catch (Exception ex) {
        logger.warn("Could not create schedules!", ex);
        throw new IllegalStateException(ex);
    }
}
Example 58
Project: ambari-master  File: ExecutionScheduleManager.java View source code
/**
   * Validate if schedule expression is a valid Cron schedule
   * @param schedule
   * @return
   */
public void validateSchedule(Schedule schedule) throws AmbariException {
    Date startDate = null;
    Date endDate = null;
    if (!schedule.isEmpty()) {
        if (schedule.getStartTime() != null && !schedule.getStartTime().isEmpty()) {
            try {
                startDate = DateUtils.convertToDate(schedule.getStartTime());
            } catch (ParseException pe) {
                throw new AmbariException("Start time in invalid format. startTime " + "= " + schedule.getStartTime() + ", Allowed format = " + DateUtils.ALLOWED_DATE_FORMAT);
            }
        }
        if (schedule.getEndTime() != null && !schedule.getEndTime().isEmpty()) {
            try {
                endDate = DateUtils.convertToDate(schedule.getEndTime());
            } catch (ParseException pe) {
                throw new AmbariException("End time in invalid format. endTime " + "= " + schedule.getEndTime() + ", Allowed format = " + DateUtils.ALLOWED_DATE_FORMAT);
            }
        }
        if (endDate != null) {
            if (endDate.before(new Date())) {
                throw new AmbariException("End date should be in the future. " + "endDate = " + endDate);
            }
            if (startDate != null && endDate.before(startDate)) {
                throw new AmbariException("End date cannot be before start date. " + "startDate = " + startDate + ", endDate = " + endDate);
            }
        }
        String cronExpression = schedule.getScheduleExpression();
        if (cronExpression != null && !cronExpression.trim().isEmpty()) {
            if (!CronExpression.isValidExpression(cronExpression)) {
                throw new AmbariException("Invalid non-empty cron expression " + "provided. " + cronExpression);
            }
        }
    }
}
Example 59
Project: kfs-master  File: SchedulerServiceImpl.java View source code
@Override
public boolean cronConditionMet(String cronExpressionString) {
    boolean cronConditionMet = false;
    CronExpression cronExpression;
    try {
        cronExpression = new CronExpression(cronExpressionString);
        Date currentDate = dateTimeService.getCurrentDate();
        Date validTimeAfter = cronExpression.getNextValidTimeAfter(dateTimeService.getCurrentDate());
        if (validTimeAfter != null) {
            String cronDate = dateTimeService.toString(validTimeAfter, KFSConstants.MONTH_DAY_YEAR_DATE_FORMAT);
            if (cronDate.equals(dateTimeService.toString(currentDate, KFSConstants.MONTH_DAY_YEAR_DATE_FORMAT))) {
                cronConditionMet = true;
            }
        } else {
            LOG.error("Null date returned when calling CronExpression.nextValidTimeAfter() for cronExpression: " + cronExpressionString);
        }
    } catch (ParseException ex) {
        LOG.error("Error parsing cronExpression: " + cronExpressionString, ex);
    }
    return cronConditionMet;
}
Example 60
Project: phresco-master  File: CI.java View source code
public Date[] testCronExpression(String expression) throws ParseException {
    Date[] dates = null;
    try {
        S_LOGGER.debug("Entering Method  CI.testCronExpression(String expression)");
        S_LOGGER.debug("testCronExpression() Expression = " + expression);
        final CronExpression cronExpression = new CronExpression(expression);
        final Date nextValidDate1 = cronExpression.getNextValidTimeAfter(new Date());
        final Date nextValidDate2 = cronExpression.getNextValidTimeAfter(nextValidDate1);
        final Date nextValidDate3 = cronExpression.getNextValidTimeAfter(nextValidDate2);
        final Date nextValidDate4 = cronExpression.getNextValidTimeAfter(nextValidDate3);
        dates = new Date[] { nextValidDate1, nextValidDate2, nextValidDate3, nextValidDate4 };
    } catch (Exception e) {
        S_LOGGER.error("Entered into catch block of CI.testCronExpression()" + FrameworkUtil.getStackTraceAsString(e));
    }
    return dates;
}
Example 61
Project: zeppelin-master  File: NotebookRestApi.java View source code
/**
   * Register cron job REST API
   *
   * @param message - JSON with cron expressions.
   * @return JSON with status.OK
   * @throws IOException, IllegalArgumentException
   */
@POST
@Path("cron/{noteId}")
@ZeppelinApi
public Response registerCronJob(@PathParam("noteId") String noteId, String message) throws IOException, IllegalArgumentException {
    LOG.info("Register cron job note={} request cron msg={}", noteId, message);
    CronRequest request = gson.fromJson(message, CronRequest.class);
    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanWrite(noteId, "Insufficient privileges you cannot set a cron job for this note");
    if (!CronExpression.isValidExpression(request.getCronString())) {
        return new JsonResponse<>(Status.BAD_REQUEST, "wrong cron expressions.").build();
    }
    Map<String, Object> config = note.getConfig();
    config.put("cron", request.getCronString());
    note.setConfig(config);
    notebook.refreshCron(note.getId());
    return new JsonResponse<>(Status.OK).build();
}
Example 62
Project: MIFOSX-master  File: DataValidatorBuilder.java View source code
public DataValidatorBuilder validateCronExpression() {
    if (this.value != null && !CronExpression.isValidExpression(this.value.toString().trim())) {
        final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".").append(this.parameter).append(".invalid");
        final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append(" value is not a valid cron expression");
        final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, this.value);
        this.dataValidationErrors.add(error);
    }
    return this;
}
Example 63
Project: LazySeq-master  File: Seqs.java View source code
public static LazySeq<Date> cronFireTimes(CronExpression expr, Date after) {
    final Date nextFireTime = expr.getNextValidTimeAfter(after);
    if (nextFireTime == null) {
        return empty();
    } else {
        return cons(nextFireTime, cronFireTimes(expr, nextFireTime));
    }
}
Example 64
Project: agile-master  File: CronValidator.java View source code
protected void onValidate(IValidatable<String> validatable) {
    if (ConfigurationItem.CRON_VALUE_NEVER.equals(validatable.getValue())) {
        // nice and simple
        return;
    }
    try {
        new CronExpression(validatable.getValue());
    } catch (Exception e) {
        error(validatable);
    }
}
Example 65
Project: gobblin-master  File: CronValidator.java View source code
@Override
public void validate(ValidatorContext ctx) {
    DataElement element = ctx.dataElement();
    Object value = element.getValue();
    String str = String.valueOf(value);
    if (!CronExpression.isValidExpression(str)) {
        ctx.addResult(new Message(element.path(), "\"%1$s\" is not in Cron format", str));
    }
}
Example 66
Project: jabylon-master  File: JobUtil.java View source code
public static void validateCron(String cronExpression) throws ParseException {
    CronExpression.validateExpression(cronExpression);
}
Example 67
Project: DataHubSystem-master  File: SynchronizerStatus.java View source code
/**
    * Makes a Pending status.
    * @param ce cronExpression scheduling the synchonizer
    * @return Pending.
    */
public static SynchronizerStatus makePendingStatus(CronExpression ce) {
    Date now = new Date();
    return new SynchronizerStatus(Status.PENDING, now, "Next activation: " + ce.getNextValidTimeAfter(now).toString());
}
Example 68
Project: gocd-master  File: TimerConfig.java View source code
public void validate(ValidationContext validationContext) {
    if (timerSpec == null) {
        errors.add(TIMER_SPEC, "Timer Spec can not be null.");
        return;
    }
    try {
        new CronExpression(timerSpec);
    } catch (ParseException pe) {
        errors.add(TIMER_SPEC, "Invalid cron syntax: " + pe.getMessage());
    }
}
Example 69
Project: opencron-master  File: VerifyController.java View source code
@RequestMapping("/exp")
public void validateCronExp(Integer cronType, String cronExp, HttpServletResponse response) {
    boolean pass = false;
    if (cronType == 0)
        pass = SchedulingPattern.validate(cronExp);
    if (cronType == 1)
        pass = CronExpression.isValidExpression(cronExp);
    WebUtils.writeHtml(response, pass ? "true" : "false");
}
Example 70
Project: agile-itsm-master  File: ProcessamentoBatchServiceEjb.java View source code
/**
	* @author euler.ramos
	*/
public boolean permiteAgendamento(String cronExpr) {
    boolean resultado = false;
    if (CronExpression.isValidExpression(cronExpr)) {
        Date dataProxExec = this.proximaExecucao(cronExpr);
        if (dataProxExec != null) {
            resultado = true;
        }
    }
    return resultado;
}
Example 71
Project: bi-platform-v2-master  File: QuartzSubscriptionScheduler.java View source code
public String getCronSummary(final String cron) throws Exception {
    return (new CronExpression(cron).getExpressionSummary());
}
Example 72
Project: SmartHome-master  File: CronExpression.java View source code
/**
     * Indicates whether the specified expression can be parsed into a
     * valid expression
     *
     * @param expression the expression to evaluate
     * @return a boolean indicating whether the given expression is a valid cron expression
     */
public static boolean isValidExpression(String cronExpression) {
    try {
        new CronExpression(cronExpression);
    } catch (ParseException pe) {
        return false;
    }
    return true;
}