@Test public void testIsEmbeddableAnnotated() { assertTrue(finder.isEmbeddableAnnotated(job.getClass())); assertFalse(finder.isEmbeddableAnnotated(person.getClass())); assertFalse(finder.isEmbeddableAnnotated(getClass())); assertFalse(finder.isEmbeddableAnnotated(null)); }
@Test public void testFindMethodColumns() { Map<String, Class> columnMap = new HashMap<String, Class>(); finder.findMethodColumns(Job.class, null, columnMap, false); String columnType = columnMap.get("job_name").getCanonicalName(); assertTrue("expecting size == 2 but found " + columnMap.size(), columnMap.size() == 2); assertNotNull( "expecting not null but found " + columnMap.get("job_name"), columnMap.get("job_name")); assertNotNull( "expecting not null but found " + columnMap.get("postal_code"), columnMap.get("postal_code")); columnMap.clear(); finder.findMethodColumns(Job.class, null, columnMap, true); assertTrue("expecting size == 1 but found " + columnMap.size(), columnMap.size() == 1); assertNotNull( "expecting not null but found " + columnMap.get("job_name"), columnMap.get("job_name")); columnMap.clear(); finder.findMethodColumns(Address.class, "zipcode", columnMap, false); assertTrue("expecting size == 1 but found " + columnMap.size(), columnMap.size() == 1); assertNotNull( "expecting not null but found " + columnMap.get("postal_code"), columnMap.get("postal_code")); assertTrue( "expecting 'java.lang.String' but found " + columnMap.get("postal_code").getCanonicalName(), columnMap.get("postal_code").getCanonicalName().equals("java.lang.String")); columnMap.clear(); finder.findMethodColumns(Address.class, "zipcode", columnMap, true); assertTrue("expecting size == 1 but found " + columnMap.size(), columnMap.size() == 1); assertNotNull( "expecting not null but found " + columnMap.get("postal_code"), columnMap.get("postal_code")); columnMap.clear(); finder.findMethodColumns(Person.class, "", columnMap, false); assertTrue("expecting size == 2 but found " + columnMap.size(), columnMap.size() == 2); assertNotNull( "expecting not null but found " + columnMap.get("job_name"), columnMap.get("job_name")); assertNotNull( "expecting not null but found " + columnMap.get("postal_code"), columnMap.get("postal_code")); columnMap.clear(); finder.findMethodColumns(Person.class, "", columnMap, true); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap.clear(); finder.findMethodColumns(Person.class, "name", columnMap, false); assertTrue("expecting size == 1 but found " + columnMap.size(), columnMap.size() == 1); assertNotNull( "expecting not null but found " + columnMap.get("job_name"), columnMap.get("job_name")); columnMap.clear(); finder.findMethodColumns(Person.class, "name", columnMap, true); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap.clear(); finder.findMethodColumns(job.getClass(), "dummyMethodName", columnMap, false); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); }
public static void scheduleForCRON(Job job) { if (job.getClass().isAnnotationPresent(On.class)) { String cron = ((On) (job.getClass().getAnnotation(On.class))).value(); if (cron.startsWith("cron.")) { cron = Play.configuration.getProperty(cron); } if (cron != null && !cron.equals("")) { try { Date now = new Date(); Date nextDate = Time.parseCRONExpression(cron); long delay = nextDate.getTime() - now.getTime(); executor.schedule((Callable) job, delay, TimeUnit.MILLISECONDS); job.executor = executor; } catch (Exception ex) { throw new UnexpectedException(ex); } } else { Logger.info("Skipping job %s, cron expression is not defined", job.getClass().getName()); } } }
public static <V> void scheduleForCRON(Job<V> job) { if (!job.getClass().isAnnotationPresent(On.class)) { return; } String cron = job.getClass().getAnnotation(On.class).value(); if (cron.startsWith("cron.")) { cron = Play.configuration.getProperty(cron); } cron = Expression.evaluate(cron, cron).toString(); if (cron == null || "".equals(cron) || "never".equalsIgnoreCase(cron)) { if (Logger.isEnabledFor("INFO")) Logger.info("Skipping job %s, cron expression is not defined", job.getClass().getName()); return; } try { Date now = new Date(); cron = Expression.evaluate(cron, cron).toString(); CronExpression cronExp = new CronExpression(cron); Date nextDate = cronExp.getNextValidTimeAfter(now); if (nextDate == null) { if (Logger.isEnabledFor("WARN")) Logger.warn( "The cron expression for job %s doesn't have any match in the future, will never be executed", job.getClass().getName()); return; } if (nextDate.equals(job.nextPlannedExecution)) { // Bug #13: avoid running the job twice for the same time // (happens when we end up running the job a few minutes before the planned time) Date nextInvalid = cronExp.getNextInvalidTimeAfter(nextDate); nextDate = cronExp.getNextValidTimeAfter(nextInvalid); } job.nextPlannedExecution = nextDate; executor.schedule( (Callable<V>) job, nextDate.getTime() - now.getTime(), TimeUnit.MILLISECONDS); job.executor = executor; } catch (Exception ex) { throw new UnexpectedException(ex); } }
@Test public void testFindAllColumnNamesFrom() { checkColumnNameWith(finder.findAllColumnNamesFrom(job.getClass(), null, false)); checkColumnNameWith(finder.findAllColumnNamesFrom(person.getClass(), "", false)); Map<String, Class> columnMap = finder.findAllColumnNamesFrom(person.getClass(), "name", false); assertEquals(columnMap.get("job_name").getCanonicalName(), "java.lang.String"); assertTrue("expecting size == 1 but found " + columnMap.size(), columnMap.size() == 1); columnMap = finder.findAllColumnNamesFrom(person.getClass(), "dummy", false); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap = finder.findAllColumnNamesFrom(job.getClass(), null, true); assertTrue("expecting size == 2 but found " + columnMap.size(), columnMap.size() == 2); assertNotNull( "expecting not null but found " + columnMap.get("job_name"), columnMap.get("job_name")); assertNotNull( "expecting not null but found " + columnMap.get("summary"), columnMap.get("summary")); columnMap = finder.findAllColumnNamesFrom(person.getClass(), "", true); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap = finder.findAllColumnNamesFrom(person.getClass(), "name", true); assertTrue("expecing size == 0 but found " + columnMap.size(), columnMap.isEmpty()); }
/** * are we so overloaded that we should drop the given job? This is driven both by the numReady and * waiting jobs, the type of job in question, and what the router's router.maxWaitingJobs config * parameter is set to. */ private boolean shouldDrop(Job job, long numReady) { if (_maxWaitingJobs <= 0) return false; // dont ever drop jobs if (!_allowParallelOperation) return false; // dont drop during startup [duh] if (numReady > _maxWaitingJobs) { Class cls = job.getClass(); // lets not try to drop too many tunnel messages... // if (cls == HandleTunnelMessageJob.class) // return true; // we don't really *need* to answer DB lookup messages // This is pretty lame, there's actually a ton of different jobs we // could drop, but is it worth making a list? if (cls == HandleFloodfillDatabaseLookupMessageJob.class) return true; } return false; }
public static void startJob(String jobName, Job job, String time) throws SchedulerException, ParseException { Scheduler sched = sf.getScheduler(); JobDetail jobDetail = new JobDetail(); jobDetail.setName(jobName); jobDetail.setGroup(JOB_GROUP_NAME); jobDetail.setJobClass(job.getClass()); CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME); trigger.setCronExpression(time); sched.scheduleJob(jobDetail, trigger); if (!sched.isShutdown()) { sched.start(); } }
@Test public void testFindFieldColumns() { Map<String, Class> columnMap = new HashMap<String, Class>(); finder.findFieldColumns(job.getClass(), null, columnMap, false); String columnType = columnMap.get("summary").getCanonicalName(); assertEquals( "expecting 'java.lang.String' but found " + columnType, columnType, "java.lang.String"); columnMap.clear(); finder.findFieldColumns(job.getClass(), null, columnMap, true); assertNotNull( "expecting not null but found " + columnMap.get("summary"), columnMap.get("summary")); assertTrue("expecting size == 1 but found " + columnMap.size(), columnMap.size() == 1); columnMap.clear(); finder.findFieldColumns(person.getClass(), null, columnMap, false); columnType = columnMap.get("summary").getCanonicalName(); assertTrue( "expecting 'java.lang.String' but found " + columnType, columnType.equals("java.lang.String")); columnMap.clear(); finder.findFieldColumns(person.getClass(), null, columnMap, true); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap.clear(); finder.findFieldColumns(job.getClass(), "zipCode", columnMap, false); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap.clear(); finder.findFieldColumns(job.getClass(), "zipCode", columnMap, true); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap.clear(); finder.findFieldColumns(job.getClass(), "name", columnMap, true); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap.clear(); finder.findFieldColumns(job.getClass(), "dummyFieldName", columnMap, false); assertTrue("expecting size == 0 but found " + columnMap.size(), columnMap.isEmpty()); columnMap.clear(); finder.findFieldColumns(job.getClass(), "description", columnMap, true); assertTrue("expecting size == 1 but found " + columnMap.size(), columnMap.size() == 1); assertNotNull( "expecting not null but found " + columnMap.get("summary"), columnMap.get("summary")); }
@Override public String getStatus() { StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); if (executor == null) { out.println("Jobs execution pool:"); out.println("~~~~~~~~~~~~~~~~~~~"); out.println("(not yet started)"); return sw.toString(); } out.println("Jobs execution pool:"); out.println("~~~~~~~~~~~~~~~~~~~"); out.println("Pool size: " + executor.getPoolSize()); out.println("Active count: " + executor.getActiveCount()); out.println("Scheduled task count: " + executor.getTaskCount()); out.println("Queue size: " + executor.getQueue().size()); SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); if (!scheduledJobs.isEmpty()) { out.println(); out.println("Scheduled jobs (" + scheduledJobs.size() + "):"); out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~"); for (Job job : scheduledJobs) { out.print(job.getClass().getName()); if (job.getClass().isAnnotationPresent(OnApplicationStart.class)) { OnApplicationStart appStartAnnotation = job.getClass().getAnnotation(OnApplicationStart.class); out.print( " run at application start" + (appStartAnnotation.async() ? " (async)" : "") + "."); } if (job.getClass().isAnnotationPresent(On.class)) { String cron = job.getClass().getAnnotation(On.class).value(); if (cron != null && cron.startsWith("cron.")) { cron = Play.configuration.getProperty(cron); } out.print(" run with cron expression " + cron + "."); } if (job.getClass().isAnnotationPresent(Every.class)) { out.print(" run every " + job.getClass().getAnnotation(Every.class).value() + "."); } if (job.lastRun > 0) { out.print(" (last run at " + df.format(new Date(job.lastRun))); if (job.wasError) { out.print(" with error)"); } else { out.print(")"); } } else { out.print(" (has never run)"); } out.println(); } } if (!executor.getQueue().isEmpty()) { out.println(); out.println("Waiting jobs:"); out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~"); for (Object o : executor.getQueue()) { ScheduledFuture task = (ScheduledFuture) o; out.println( Java.extractUnderlyingCallable((FutureTask) task) + " will run in " + task.getDelay(TimeUnit.SECONDS) + " seconds"); } } return sw.toString(); }
@Override public void afterApplicationStart() { List<Class<?>> jobs = new ArrayList<Class<?>>(); for (Class clazz : Play.classloader.getAllClasses()) { if (Job.class.isAssignableFrom(clazz)) { jobs.add(clazz); } } scheduledJobs = new ArrayList<Job>(); for (final Class<?> clazz : jobs) { // @OnApplicationStart if (clazz.isAnnotationPresent(OnApplicationStart.class)) { // check if we're going to run the job sync or async OnApplicationStart appStartAnnotation = clazz.getAnnotation(OnApplicationStart.class); if (!appStartAnnotation.async()) { // run job sync try { Job<?> job = ((Job<?>) clazz.newInstance()); scheduledJobs.add(job); job.run(); if (job.wasError) { if (job.lastException != null) { throw job.lastException; } throw new RuntimeException("@OnApplicationStart Job has failed"); } } catch (InstantiationException e) { throw new UnexpectedException("Job could not be instantiated", e); } catch (IllegalAccessException e) { throw new UnexpectedException("Job could not be instantiated", e); } catch (Throwable ex) { if (ex instanceof PlayException) { throw (PlayException) ex; } throw new UnexpectedException(ex); } } else { // run job async try { Job<?> job = ((Job<?>) clazz.newInstance()); scheduledJobs.add(job); // start running job now in the background @SuppressWarnings("unchecked") Callable<Job> callable = (Callable<Job>) job; executor.submit(callable); } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } } // @On if (clazz.isAnnotationPresent(On.class)) { try { Job<?> job = ((Job<?>) clazz.newInstance()); scheduledJobs.add(job); scheduleForCRON(job); } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } // @Every if (clazz.isAnnotationPresent(Every.class)) { try { Job job = (Job) clazz.newInstance(); scheduledJobs.add(job); String value = job.getClass().getAnnotation(Every.class).value(); if (value.startsWith("cron.")) { value = Play.configuration.getProperty(value); } value = Expression.evaluate(value, value).toString(); if (!"never".equalsIgnoreCase(value)) { executor.scheduleWithFixedDelay( job, Time.parseDuration(value), Time.parseDuration(value), TimeUnit.SECONDS); } } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } } }
@Override public void afterApplicationStart() { List<Class> jobs = new ArrayList(); for (Class clazz : Play.classloader.getAllClasses()) { if (Job.class.isAssignableFrom(clazz)) { jobs.add(clazz); } } scheduledJobs = new ArrayList(); for (final Class clazz : jobs) { // @OnApplicationStart if (clazz.isAnnotationPresent(OnApplicationStart.class)) { try { Job job = ((Job) clazz.newInstance()); scheduledJobs.add(job); job.run(); if (job.wasError) { if (job.lastException != null) { throw job.lastException; } throw new RuntimeException("@OnApplicationStart Job has failed"); } } catch (InstantiationException e) { throw new UnexpectedException("Job could not be instantiated", e); } catch (IllegalAccessException e) { throw new UnexpectedException("Job could not be instantiated", e); } catch (Throwable ex) { if (ex instanceof PlayException) { throw (PlayException) ex; } throw new UnexpectedException(ex); } } // @On if (clazz.isAnnotationPresent(On.class)) { try { Job job = ((Job) clazz.newInstance()); scheduledJobs.add(job); scheduleForCRON(job); } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } // @Every if (clazz.isAnnotationPresent(Every.class)) { try { Job job = (Job) clazz.newInstance(); scheduledJobs.add(job); String value = ((Every) (job.getClass().getAnnotation(Every.class))).value(); executor.scheduleWithFixedDelay( job, Time.parseDuration(value), Time.parseDuration(value), TimeUnit.SECONDS); } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } } }