Search in sources :

Example 31 with Trigger

use of org.quartz.Trigger in project openhab1-addons by openhab.

the class OceanicBinding method execute.

@Override
protected void execute() {
    if (isProperlyConfigured()) {
        Scheduler sched = null;
        try {
            sched = StdSchedulerFactory.getDefaultScheduler();
        } catch (SchedulerException e) {
            logger.error("An exception occurred while getting a reference to the Quartz Scheduler");
        }
        // reset the contextMap before rebuilding it
        for (String serialPort : serialDevices.keySet()) {
            Set<String> itemNames = contextMap.get(serialPort);
            if (itemNames != null) {
                contextMap.clear();
            }
        }
        for (OceanicBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                String serialPort = provider.getSerialPort(itemName);
                SerialDevice serialDevice = serialDevices.get(serialPort);
                boolean serialDeviceReady = true;
                if (serialDevice == null) {
                    serialDevice = new SerialDevice(serialPort);
                    try {
                        serialDevice.initialize();
                    } catch (InitializationException e) {
                        logger.error("Could not open serial port " + serialPort + ": " + e.getMessage());
                        serialDeviceReady = false;
                    } catch (Throwable e) {
                        logger.error("Could not open serial port " + serialPort + ": " + e.getMessage());
                        serialDeviceReady = false;
                    }
                    if (serialDeviceReady) {
                        serialDevice.setEventPublisher(eventPublisher);
                        serialDevices.put(serialPort, serialDevice);
                    }
                }
                Set<String> itemNames = contextMap.get(serialPort);
                if (itemNames == null) {
                    itemNames = new HashSet<String>();
                    contextMap.put(serialPort, itemNames);
                }
                itemNames.add(itemName);
                if (serialDeviceReady) {
                    // set up the polling jobs
                    boolean jobExists = false;
                    // enumerate each job group
                    try {
                        for (String group : sched.getJobGroupNames()) {
                            // enumerate each job in group
                            if (group.equals("Oceanic-" + provider.toString())) {
                                for (JobKey jobKey : sched.getJobKeys(jobGroupEquals(group))) {
                                    if (jobKey.getName().equals(itemName + "-" + provider.getValueSelector(itemName).toString())) {
                                        jobExists = true;
                                        break;
                                    }
                                }
                            }
                        }
                    } catch (SchedulerException e1) {
                        logger.error("An exception occurred while querying the Quartz Scheduler ({})", e1.getMessage());
                    }
                    if (!jobExists && OceanicValueSelector.getValueSelector(provider.getValueSelector(itemName), ValueSelectorType.GET) != null) {
                        // set up the Quartz jobs
                        JobDataMap map = new JobDataMap();
                        map.put("SerialPort", serialPort);
                        map.put("ValueSelector", OceanicValueSelector.getValueSelector(provider.getValueSelector(itemName), ValueSelectorType.GET));
                        map.put("Binding", this);
                        JobDetail job = newJob(OceanicBinding.PollJob.class).withIdentity(itemName + "-" + provider.getValueSelector(itemName).toString(), "Oceanic-" + provider.toString()).usingJobData(map).build();
                        Trigger trigger = newTrigger().withIdentity(itemName + "-" + provider.getValueSelector(itemName).toString(), "Oceanic-" + provider.toString()).startNow().withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(provider.getPollingInterval(itemName))).build();
                        try {
                            logger.debug("Adding a poll job {} for {}", job.getKey(), itemName);
                            sched.scheduleJob(job, trigger);
                        } catch (SchedulerException e) {
                            logger.error("An exception occurred while scheduling a Quartz Job");
                        }
                    }
                    // kill the Quartz jobs that we do not need anymore
                    try {
                        for (String group : sched.getJobGroupNames()) {
                            // enumerate each job in group
                            if (group.equals("Oceanic-" + provider.toString())) {
                                for (JobKey jobKey : sched.getJobKeys(jobGroupEquals(group))) {
                                    if (findFirstMatchingBindingProvider(jobKey.getName().split("-")[0]) == null) {
                                        logger.debug("Removing a poll job {} for {}", jobKey, itemName);
                                        sched.deleteJob(jobKey);
                                    }
                                }
                            }
                        }
                    } catch (SchedulerException e1) {
                        logger.error("An exception occurred while querying the Quartz Scheduler ({})", e1.getMessage());
                    }
                }
            }
        }
        // close down the serial ports that do not have any Items anymore associated to them
        for (String serialPort : serialDevices.keySet()) {
            SerialDevice serialDevice = serialDevices.get(serialPort);
            Set<String> itemNames = contextMap.get(serialPort);
            if (itemNames == null || itemNames.size() == 0) {
                contextMap.remove(serialPort);
                logger.debug("Closing the serial port {}", serialPort);
                serialDevice.close();
                serialDevices.remove(serialPort);
            }
        }
    }
}
Also used : JobDataMap(org.quartz.JobDataMap) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler) OceanicBindingProvider(org.openhab.binding.oceanic.OceanicBindingProvider) JobKey(org.quartz.JobKey) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger)

Example 32 with Trigger

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

the class PauseJobServlet method processRequest.

// also perhaps DRY, tbh
@Override
protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    String triggerName = fp.getString("tname");
    // String gName = fp.getString("gname");
    String gName = request.getParameter("gname");
    String finalGroupName = "";
    if ("".equals(gName) || "0".equals(gName)) {
        finalGroupName = XsltTriggerService.TRIGGER_GROUP_NAME;
    } else {
        // should equal 1
        finalGroupName = groupImportName;
    }
    String deleteMe = fp.getString("del");
    scheduler = getScheduler();
    Trigger trigger = scheduler.getTrigger(TriggerKey.triggerKey(triggerName, finalGroupName));
    try {
        if (("y".equals(deleteMe)) && (ub.isSysAdmin())) {
            scheduler.deleteJob(JobKey.jobKey(triggerName, finalGroupName));
            // set return message here
            logger.debug("deleted job: " + triggerName);
            addPageMessage("The following job " + triggerName + " and its corresponding Trigger have been deleted from the system.");
        } else {
            if (scheduler.getTriggerState(TriggerKey.triggerKey(triggerName, finalGroupName)) == Trigger.TriggerState.PAUSED) {
                scheduler.resumeTrigger(TriggerKey.triggerKey(triggerName, finalGroupName));
                // trigger.setPriority(Trigger.DEFAULT_PRIORITY);
                logger.debug("-- resuming trigger! " + triggerName + " " + finalGroupName);
                addPageMessage("This trigger " + triggerName + " has been resumed and will continue to run until paused or deleted.");
            // set message here
            } else {
                scheduler.pauseTrigger(TriggerKey.triggerKey(triggerName, finalGroupName));
                // trigger.setPriority(Trigger.STATE_PAUSED);
                logger.debug("-- pausing trigger! " + triggerName + " " + finalGroupName);
                addPageMessage("This trigger " + triggerName + " has been paused, and will not run again until it is restored.");
            // set message here
            }
        }
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // set a message
    if ("".equals(gName) || "0".equals(gName)) {
        forwardPage(Page.VIEW_JOB_SERVLET);
    } else {
        forwardPage(Page.VIEW_IMPORT_JOB_SERVLET);
    }
}
Also used : Trigger(org.quartz.Trigger) FormProcessor(org.akaza.openclinica.control.form.FormProcessor)

Example 33 with Trigger

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

the class ViewImportJobServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    // First we must get a reference to a scheduler
    scheduler = getScheduler();
    // then we pull all the triggers that are specifically named
    // IMPORT_TRIGGER.
    Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.groupEquals(IMPORT_TRIGGER));
    // the next bit goes out and processes all the triggers
    ArrayList triggerBeans = new ArrayList<TriggerBean>();
    for (TriggerKey triggerKey : triggerKeys) {
        String triggerName = triggerKey.getName();
        Trigger trigger = scheduler.getTrigger(triggerKey);
        logger.debug("found trigger, full name: " + triggerName);
        try {
            logger.debug("prev fire time " + trigger.getPreviousFireTime().toString());
            logger.debug("next fire time " + trigger.getNextFireTime().toString());
            logger.debug("final fire time: " + trigger.getFinalFireTime().toString());
        } catch (NullPointerException npe) {
        // could be nulls in the dates, etc
        }
        TriggerBean triggerBean = new TriggerBean();
        triggerBean.setFullName(triggerName);
        triggerBean.setPreviousDate(trigger.getPreviousFireTime());
        triggerBean.setNextDate(trigger.getNextFireTime());
        if (trigger.getDescription() != null) {
            triggerBean.setDescription(trigger.getDescription());
        }
        // this next bit of code looks at the job data map and pulls out
        // specific items
        JobDataMap dataMap = new JobDataMap();
        if (trigger.getJobDataMap().size() > 0) {
            dataMap = trigger.getJobDataMap();
            triggerBean.setStudyName(dataMap.getString(ExampleSpringJob.STUDY_NAME));
            String oid = dataMap.getString("study_oid");
        }
        // this next bit of code looks to see if the trigger is paused
        logger.debug("Trigger Priority: " + triggerName + " " + trigger.getPriority());
        if (scheduler.getTriggerState(new TriggerKey(triggerName, IMPORT_TRIGGER)) == Trigger.TriggerState.PAUSED) {
            triggerBean.setActive(false);
            logger.debug("setting active to false for trigger: " + triggerName);
        } else {
            triggerBean.setActive(true);
            logger.debug("setting active to TRUE for trigger: " + triggerName);
        }
        triggerBeans.add(triggerBean);
    // our wrapper to show triggers
    }
    // set up the table here and get ready to send to the web page
    ArrayList allRows = TriggerRow.generateRowsFromBeans(triggerBeans);
    EntityBeanTable table = fp.getEntityBeanTable();
    String[] columns = { resword.getString("name"), resword.getString("previous_fire_time"), resword.getString("next_fire_time"), resword.getString("description"), resword.getString("study"), resword.getString("actions") };
    table.setColumns(new ArrayList(Arrays.asList(columns)));
    table.hideColumnLink(3);
    table.hideColumnLink(5);
    table.setQuery("ViewImportJob", new HashMap());
    // table.addLink("", "CreateUserAccount");
    table.setSortingColumnInd(0);
    table.setRows(allRows);
    table.computeDisplay();
    request.setAttribute("table", table);
    forwardPage(Page.VIEW_IMPORT_JOB);
}
Also used : TriggerKey(org.quartz.TriggerKey) TriggerBean(org.akaza.openclinica.bean.admin.TriggerBean) JobDataMap(org.quartz.JobDataMap) Trigger(org.quartz.Trigger) HashMap(java.util.HashMap) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) EntityBeanTable(org.akaza.openclinica.web.bean.EntityBeanTable) ArrayList(java.util.ArrayList)

Example 34 with Trigger

use of org.quartz.Trigger in project Dempsy by Dempsy.

the class CronOutputSchedule method getCronTrigger.

/**
   * Gets the cron trigger.
   *
   * @param cronExpression the cron expression
   * @return the cron trigger
   */
private Trigger getCronTrigger(String cronExpression) {
    CronScheduleBuilder cronScheduleBuilder = null;
    Trigger cronTrigger = null;
    try {
        cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed();
        TriggerBuilder<Trigger> cronTtriggerBuilder = TriggerBuilder.newTrigger();
        cronTtriggerBuilder.withSchedule(cronScheduleBuilder);
        cronTrigger = cronTtriggerBuilder.build();
    } catch (ParseException pe) {
        logger.error("Error occurred while builiding the cronTrigger : " + pe.getMessage(), pe);
    }
    return cronTrigger;
}
Also used : CronScheduleBuilder(org.quartz.CronScheduleBuilder) Trigger(org.quartz.Trigger) ParseException(java.text.ParseException)

Example 35 with Trigger

use of org.quartz.Trigger in project Dempsy by Dempsy.

the class CronOutputSchedule method start.

/* (non-Javadoc)
   * @see com.nokia.dempsy.output.OutputExecuter#start()
   */
public void start() {
    try {
        JobDetail jobDetail = super.getJobDetail();
        Trigger trigger = getCronTrigger(cronExpression);
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    } catch (SchedulerException se) {
        logger.error("Error occurred while starting the cron scheduler : " + se.getMessage(), se);
    }
}
Also used : JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) SchedulerException(org.quartz.SchedulerException)

Aggregations

Trigger (org.quartz.Trigger)104 JobDetail (org.quartz.JobDetail)51 SchedulerException (org.quartz.SchedulerException)40 CronTrigger (org.quartz.CronTrigger)29 Test (org.junit.Test)23 Scheduler (org.quartz.Scheduler)22 JobDataMap (org.quartz.JobDataMap)21 SimpleTrigger (org.quartz.SimpleTrigger)20 TriggerKey (org.quartz.TriggerKey)20 TriggerBuilder.newTrigger (org.quartz.TriggerBuilder.newTrigger)19 JobKey (org.quartz.JobKey)16 ArrayList (java.util.ArrayList)13 Date (java.util.Date)12 List (java.util.List)5 Command (org.openhab.core.types.Command)5 InetSocketAddress (java.net.InetSocketAddress)4 SocketChannel (java.nio.channels.SocketChannel)4 ParseException (java.text.ParseException)4 FormProcessor (org.akaza.openclinica.control.form.FormProcessor)4 ProtoTrigger (co.cask.cdap.proto.ProtoTrigger)3