Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- import java.lang.annotation.ElementType;
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.TYPE)
- public @interface CronType {
- public String name();
- }
- ////////////////////////////
- /**
- * CronMaster service, loads all registered jobs on startup and exposes REST service.
- *
- * @author Alexander
- *
- */
- @ApplicationPath("/cron")
- public class CronMasterApplication extends Application {
- static Map<String,CronAgent> jobs = new HashMap<String, CronAgent>();
- public Set<Class<?>> getClasses() {
- return new HashSet<Class<?>>(Arrays.asList(CronMasterEndpoint.class));
- }
- static { //cool stuff, calls the method whenever this class is initialized
- registerJobs();
- }
- static void registerJobs() {
- final ClassLoader loader = Thread.currentThread().getContextClassLoader();
- try {
- ClassPath classpath = ClassPath.from(loader); // scans the class
- // path used by
- // classloader
- // all job classes have to be in the fi.observis.festivals.cron
- // package or subpackage of that
- for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClassesRecursive("fi.observis.festival.cron")) {
- logger.info(classInfo.getSimpleName() + " <==> " + classInfo.getPackageName());
- /*
- * Do annotation logic here.
- */
- Class<?> currentClass = classInfo.load();//gets ur classes
- Annotation[] annotations = currentClass.getAnnotations(); //need to check if it has CronTask annotation
- logger.info("Annotations are: " + annotations.length);
- for (Annotation cur : annotations) {
- if (cur.annotationType().equals(CronTask.class)) {
- //Annotation is of type CronType
- CronTask type = (CronTask) cur;
- logger.info(cur.annotationType().getName());
- //Put the job in our hashmap with the key of appid
- @SuppressWarnings("unchecked")
- Class<CronAgent> tempClass = (Class<CronAgent>) classInfo.load(); //generic class :D
- jobs.put(type.name(), tempClass.newInstance()); //instantiate object from the generic class, and store to hash!
- logger.info(type.name());
- }
- }
- }
- //calling a job for example
- //jobs.get("aaltofestival").executeJob("aaltofestival");
- } catch (IOException | InstantiationException | IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- }
- ///////////
- package fi.observis.festival.cron.aaltofestival;
- import *...
- //using app id in the annotation for classes that extend the interface
- @CronTask(name = "aaltofestival")
- public class AaltoCronJob implements CronAgent {
- //interface method
- @Override
- public void executeJob(String appId) {
- }
- }
- //////////
- public interface CronAgent {
- public void executeJob(String appId);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement