Search in sources :

Example 11 with JobKey

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

the class EventReloaderJob method execute.

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    final String config = context.getJobDetail().getJobDataMap().getString(KEY_CONFIG);
    CalendarRuntime eventRuntime = EventStorage.getInstance().getEventCache().get(config);
    log.debug("running EventReloaderJob for config : {}", config);
    // reload cached events (if necessary)
    if (!cachedEventsLoaded.containsKey(config)) {
        try {
            log.debug("reload cached events for config: {}", eventRuntime.getConfig().getKey());
            for (File fileCalendarKeys : new File(CalDavLoaderImpl.CACHE_PATH).listFiles()) {
                if (!eventRuntime.getConfig().getKey().equals(Util.getFilename(fileCalendarKeys.getName()))) {
                    log.trace("not our config : {}", Util.getFilename(fileCalendarKeys.getName()));
                    continue;
                }
                log.trace("found our config : {}", Util.getFilename(fileCalendarKeys.getName()));
                final Collection<File> icsFiles = FileUtils.listFiles(fileCalendarKeys, new String[] { "ics" }, false);
                for (File icsFile : icsFiles) {
                    try {
                        FileInputStream fis = new FileInputStream(icsFile);
                        log.debug("loading events from file : {}", icsFile);
                        loadEvents(Util.getFilename(icsFile.getAbsolutePath()), new org.joda.time.DateTime(icsFile.lastModified()), fis, eventRuntime.getConfig(), new ArrayList<String>(), true);
                    } catch (IOException e) {
                        log.error("cannot load events for file: " + icsFile, e);
                    } catch (ParserException e) {
                        log.error("cannot load events for file: " + icsFile, e);
                    }
                }
                break;
            }
        } catch (Throwable e) {
            log.error("cannot load events", e);
        } finally {
            cachedEventsLoaded.put(config, true);
        }
    }
    try {
        log.debug("loading events for config: " + config);
        List<String> oldEventIds = new ArrayList<String>();
        for (EventContainer eventContainer : eventRuntime.getEventMap().values()) {
            oldEventIds.add(eventContainer.getFilename());
            log.debug("old eventcontainer -- id : {} -- filename : {} -- calcuntil : {} -- lastchanged : {} -- ishistoric : {}", eventContainer.getEventId(), eventContainer.getFilename(), eventContainer.getCalculatedUntil(), eventContainer.getLastChanged(), eventContainer.isHistoricEvent());
            if (log.isDebugEnabled()) {
                for (int i = 0; i < eventContainer.getEventList().size(); i++) {
                    CalDavEvent elem = eventContainer.getEventList().get(i);
                    log.debug("old eventlist contient l'evenement : {} -- deb : {} -- fin : {} -- lastchang {}", elem.getName(), elem.getStart(), elem.getEnd(), elem.getLastChanged());
                }
            }
        }
        loadEvents(eventRuntime, oldEventIds);
        // stop all events in oldMap
        removeDeletedEvents(config, oldEventIds);
        for (EventNotifier notifier : CalDavLoaderImpl.instance.getEventListenerList()) {
            try {
                notifier.calendarReloaded(config);
            } catch (Exception e) {
                log.error("error while invoking listener", e);
            }
        }
        // print All scheduled jobs :
        if (log.isDebugEnabled()) {
            log.debug("jobs scheduled : ");
            Scheduler scheduler = CalDavLoaderImpl.instance.getScheduler();
            for (String groupName : CalDavLoaderImpl.instance.getScheduler().getJobGroupNames()) {
                for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
                    String jobName = jobKey.getName();
                    String jobGroup = jobKey.getGroup();
                    // get job's trigger
                    List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
                    Date nextFireTime = triggers.get(0).getNextFireTime();
                    log.debug("[job] : {} - [groupName] : {} - {}", jobName, jobGroup, nextFireTime);
                }
            }
        }
    } catch (SardineException e) {
        log.error("error while loading calendar entries: {} ({} - {} )", e.getMessage(), e.getStatusCode(), e.getResponsePhrase(), e);
        throw new JobExecutionException("error while loading calendar entries", e, false);
    } catch (Exception e) {
        log.error("error while loading calendar entries: {}", e.getMessage(), e);
        throw new JobExecutionException("error while loading calendar entries", e, false);
    }
}
Also used : Scheduler(org.quartz.Scheduler) ArrayList(java.util.ArrayList) JobKey(org.quartz.JobKey) SardineException(com.github.sardine.impl.SardineException) Trigger(org.quartz.Trigger) JobExecutionException(org.quartz.JobExecutionException) EventNotifier(org.openhab.io.caldav.EventNotifier) PropertyList(net.fortuna.ical4j.model.PropertyList) List(java.util.List) ArrayList(java.util.ArrayList) ComponentList(net.fortuna.ical4j.model.ComponentList) PeriodList(net.fortuna.ical4j.model.PeriodList) ParserException(net.fortuna.ical4j.data.ParserException) EventContainer(org.openhab.io.caldav.internal.EventStorage.EventContainer) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ParserException(net.fortuna.ical4j.data.ParserException) JobExecutionException(org.quartz.JobExecutionException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException) SardineException(com.github.sardine.impl.SardineException) Date(java.util.Date) CalDavEvent(org.openhab.io.caldav.CalDavEvent) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime) File(java.io.File)

Example 12 with JobKey

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

the class DropboxSynchronizer method cancelAllJobs.

/**
     * Delete all quartz scheduler jobs of the group <code>Dropbox</code>.
     */
private void cancelAllJobs() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        Set<JobKey> jobKeys = sched.getJobKeys(jobGroupEquals(DROPBOX_SCHEDULER_GROUP));
        if (jobKeys.size() > 0) {
            sched.deleteJobs(new ArrayList<JobKey>(jobKeys));
            logger.debug("Found {} synchronization jobs to delete from DefaultScheduler (keys={})", jobKeys.size(), jobKeys);
        }
    } catch (SchedulerException e) {
        logger.warn("Couldn't remove synchronization job: {}", e.getMessage());
    }
}
Also used : JobKey(org.quartz.JobKey) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler)

Example 13 with JobKey

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

the class JobScheduler method stop.

/**
     * Stops all scheduled jobs and clears the PlanetPublisher cache.
     */
public void stop() {
    try {
        for (JobKey jobKey : scheduler.getJobKeys(jobGroupEquals(JOB_GROUP))) {
            logger.info("Deleting astro job: " + jobKey.getName());
            scheduler.deleteJob(jobKey);
        }
    } catch (SchedulerException ex) {
        logger.error(ex.getMessage(), ex);
    }
    PlanetPublisher.getInstance().clear();
}
Also used : JobKey(org.quartz.JobKey) SchedulerException(org.quartz.SchedulerException)

Example 14 with JobKey

use of org.quartz.JobKey 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 15 with JobKey

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

the class WeatherJobScheduler method stop.

/**
     * Stops all scheduled jobs and clears the WeatherPublisher cache.
     */
public void stop() {
    try {
        for (JobKey jobKey : scheduler.getJobKeys(jobGroupEquals(JOB_GROUP))) {
            logger.info("Deleting " + jobKey.getName());
            scheduler.deleteJob(jobKey);
        }
    } catch (SchedulerException ex) {
        logger.error(ex.getMessage(), ex);
    }
}
Also used : JobKey(org.quartz.JobKey) SchedulerException(org.quartz.SchedulerException)

Aggregations

JobKey (org.quartz.JobKey)65 SchedulerException (org.quartz.SchedulerException)33 JobDetail (org.quartz.JobDetail)22 Trigger (org.quartz.Trigger)19 Scheduler (org.quartz.Scheduler)17 TriggerKey (org.quartz.TriggerKey)15 Test (org.junit.Test)13 List (java.util.List)6 CronTrigger (org.quartz.CronTrigger)6 JobDataMap (org.quartz.JobDataMap)6 ArrayList (java.util.ArrayList)5 TriggerBuilder.newTrigger (org.quartz.TriggerBuilder.newTrigger)5 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)4 Date (java.util.Date)4 HashMap (java.util.HashMap)4 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)2 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)2 Hashtable (java.util.Hashtable)2 Scheduled (org.apache.deltaspike.scheduler.api.Scheduled)2 CronScheduleBuilder (org.quartz.CronScheduleBuilder)2