Search in sources :

Example 21 with SchedulerException

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

the class PlugwiseBinding method scheduleJobs.

private void scheduleJobs(Scheduler scheduler) {
    for (PlugwiseBindingProvider provider : providers) {
        for (PlugwiseBindingConfigElement element : provider.getIntervalList()) {
            PlugwiseCommandType type = element.getCommandType();
            if (type.getJobClass() == null) {
                continue;
            }
            if (stick.getDevice(element.getId()) == null) {
                logger.debug("The Plugwise device with id {} is not yet defined", element.getId());
                // check if the config string really contains a MAC address
                Pattern MAC_PATTERN = Pattern.compile("(\\w{16})");
                Matcher matcher = MAC_PATTERN.matcher(element.getId());
                if (matcher.matches()) {
                    List<CirclePlus> cps = stick.getDevicesByClass(CirclePlus.class);
                    if (!cps.isEmpty()) {
                        CirclePlus cp = cps.get(0);
                        if (!cp.getMAC().equals(element.getId())) {
                            // a circleplus has been added/detected and it is not what is in the binding config
                            PlugwiseDevice device = new Circle(element.getId(), stick, element.getId());
                            stick.addDevice(device);
                            logger.debug("Plugwise added Circle with MAC address: {}", element.getId());
                        }
                    } else {
                        logger.warn("Plugwise can not guess the device that should be added. Consider defining it in the openHAB configuration file");
                    }
                } else {
                    logger.warn("Plugwise can not add a valid device without a proper MAC address. {} can not be used", element.getId());
                }
            }
            if (stick.getDevice(element.getId()) != null) {
                String jobName = element.getId() + "-" + type.getJobClass().toString();
                if (!isExistingJob(scheduler, jobName)) {
                    // set up the Quartz jobs
                    JobDataMap map = new JobDataMap();
                    map.put(STICK_JOB_DATA_KEY, stick);
                    map.put(MAC_JOB_DATA_KEY, stick.getDevice(element.getId()).MAC);
                    JobDetail job = newJob(type.getJobClass()).withIdentity(jobName, "Plugwise-" + provider.toString()).usingJobData(map).build();
                    Trigger trigger = newTrigger().withIdentity(element.getId() + "-" + type.getJobClass().toString(), "Plugwise-" + provider.toString()).startNow().withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(element.getInterval())).build();
                    try {
                        scheduler.scheduleJob(job, trigger);
                    } catch (SchedulerException e) {
                        logger.error("An exception occurred while scheduling a Plugwise Quartz Job", e);
                    }
                }
            } else {
                logger.error("Error scheduling a Quartz Job for a non-defined Plugwise device (" + element.getId() + ")");
            }
        }
    }
    List<CirclePlus> cps = stick.getDevicesByClass(CirclePlus.class);
    if (!cps.isEmpty()) {
        CirclePlus cp = cps.get(0);
        String jobName = cp.MAC + "-SetCirclePlusClock";
        if (!isExistingJob(scheduler, jobName)) {
            JobDataMap map = new JobDataMap();
            map.put(CirclePlus.CIRCLE_PLUS_JOB_DATA_KEY, cp);
            JobDetail job = newJob(SetClockJob.class).withIdentity(jobName, "Plugwise").usingJobData(map).build();
            CronTrigger trigger = newTrigger().withIdentity(jobName, "Plugwise").startNow().withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?")).build();
            try {
                Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
                sched.scheduleJob(job, trigger);
            } catch (SchedulerException e) {
                logger.error("Error scheduling Circle+ setClock Quartz Job", e);
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) JobDataMap(org.quartz.JobDataMap) CronTrigger(org.quartz.CronTrigger) SchedulerException(org.quartz.SchedulerException) Matcher(java.util.regex.Matcher) PlugwiseCommandType(org.openhab.binding.plugwise.PlugwiseCommandType) Scheduler(org.quartz.Scheduler) PlugwiseBindingConfigElement(org.openhab.binding.plugwise.internal.PlugwiseGenericBindingProvider.PlugwiseBindingConfigElement) SetClockJob(org.openhab.binding.plugwise.internal.CirclePlus.SetClockJob) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) CronTrigger(org.quartz.CronTrigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) PlugwiseBindingProvider(org.openhab.binding.plugwise.PlugwiseBindingProvider)

Example 22 with SchedulerException

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

the class CalDavLoaderImpl method addEventToMap.

public synchronized void addEventToMap(EventContainer eventContainer, boolean createTimer) {
    CalendarRuntime calendarRuntime = EventStorage.getInstance().getEventCache().get(eventContainer.getCalendarId());
    ConcurrentHashMap<String, EventContainer> eventContainerMap = calendarRuntime.getEventMap();
    if (eventContainerMap.containsKey(eventContainer.getEventId())) {
        EventContainer eventContainerOld = eventContainerMap.get(eventContainer.getEventId());
        // event is already in map
        if (eventContainer.getLastChanged().isAfter(eventContainerOld.getLastChanged())) {
            log.debug("event is already in event map and newer -> delete the old one, reschedule timer");
            // cancel old jobs
            for (String timerKey : eventContainerOld.getTimerMap()) {
                try {
                    this.scheduler.deleteJob(JobKey.jobKey(timerKey));
                } catch (SchedulerException e) {
                    log.error("cannot cancel event with job-id: " + timerKey, e);
                }
            }
            eventContainerOld.getTimerMap().clear();
            // override event
            eventContainerMap.put(eventContainer.getEventId(), eventContainer);
            for (EventNotifier notifier : eventListenerList) {
                for (CalDavEvent event : eventContainerOld.getEventList()) {
                    log.trace("notify listener... {}", notifier);
                    try {
                        notifier.eventRemoved(event);
                    } catch (Exception e) {
                        log.error("error while invoking listener", e);
                    }
                }
            }
            for (EventNotifier notifier : eventListenerList) {
                for (CalDavEvent event : eventContainer.getEventList()) {
                    log.trace("notify listener... {}", notifier);
                    try {
                        notifier.eventLoaded(event);
                    } catch (Exception e) {
                        log.error("error while invoking listener", e);
                    }
                }
            }
            if (createTimer) {
                int index = 0;
                for (CalDavEvent event : eventContainer.getEventList()) {
                    if (event.getEnd().isAfterNow()) {
                        try {
                            createJob(eventContainer, event, index);
                        } catch (SchedulerException e) {
                            log.error("cannot create jobs for event '{}': ", event.getShortName(), e.getMessage());
                        }
                    }
                    index++;
                }
            }
        } else {
            // event is already in map and not updated (eventContainerold and eventContainer have the same
            // "lastchanged" date) : we need to reschedule possible new events from recurrent events
            log.debug("event is already in map and not updated, we NEED to update eventlist and schedule new events jobs");
            ArrayList<CalDavEvent> eventsToAdd = new ArrayList<>();
            for (CalDavEvent event : eventContainer.getEventList()) {
                boolean eventAlreadyKnown = false;
                for (CalDavEvent oldevent : eventContainerOld.getEventList()) {
                    if (event.equals(oldevent)) {
                        eventAlreadyKnown = true;
                        log.trace("events match");
                    } else {
                        log.trace("eventsarenotequal : {} - {} - {} - {} - {}", event.getId(), event.getName(), event.getStart(), event.getEnd(), event.getLastChanged());
                        log.trace("eventsarenotequal : {} - {} - {} - {} - {}", oldevent.getId(), oldevent.getName(), oldevent.getStart(), oldevent.getEnd(), oldevent.getLastChanged());
                    }
                }
                if (!eventAlreadyKnown) {
                    eventsToAdd.add(event);
                }
            }
            // add only new events
            for (CalDavEvent event : eventsToAdd) {
                if (event.getEnd().isAfterNow()) {
                    eventContainerOld.getEventList().add(event);
                    for (EventNotifier notifier : eventListenerList) {
                        log.trace("notify listener... {}", notifier);
                        try {
                            notifier.eventLoaded(event);
                        } catch (Exception e) {
                            log.error("error while invoking listener", e);
                        }
                    }
                    if (createTimer) {
                        try {
                            log.trace("creating job for event {} ", event.getShortName());
                            createJob(eventContainerOld, event, eventContainerOld.getEventList().size() - 1);
                        // -1 because we already added the event to eventContainerOld
                        } catch (SchedulerException e) {
                            log.error("cannot create jobs for event '{}': ", event.getShortName(), e.getMessage());
                        }
                    }
                }
            }
            // update eventcontainer's calculateduntil
            eventContainerOld.setCalculatedUntil(eventContainer.getCalculatedUntil());
        }
    } else {
        // event is new
        eventContainerMap.put(eventContainer.getEventId(), eventContainer);
        log.trace("listeners for events: {}", eventListenerList.size());
        for (EventNotifier notifier : eventListenerList) {
            for (CalDavEvent event : eventContainer.getEventList()) {
                log.trace("notify listener... {}", notifier);
                try {
                    notifier.eventLoaded(event);
                } catch (Exception e) {
                    log.error("error while invoking listener", e);
                }
            }
        }
        if (createTimer) {
            int index = 0;
            for (CalDavEvent event : eventContainer.getEventList()) {
                if (event.getEnd().isAfterNow()) {
                    try {
                        createJob(eventContainer, event, index);
                    } catch (SchedulerException e) {
                        log.error("cannot create jobs for event: " + event.getShortName());
                    }
                }
                index++;
            }
        }
    }
}
Also used : SchedulerException(org.quartz.SchedulerException) EventContainer(org.openhab.io.caldav.internal.EventStorage.EventContainer) CalDavEvent(org.openhab.io.caldav.CalDavEvent) EventNotifier(org.openhab.io.caldav.EventNotifier) ArrayList(java.util.ArrayList) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime) ConfigurationException(org.osgi.service.cm.ConfigurationException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException)

Example 23 with SchedulerException

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

the class GCalEventDownloader method createTriggerAndSchedule.

/**
     * Creates a set quartz-triggers for <code>job</code>. For each {@link When}
     * object of <code>event</code> a new trigger is created. That is the case
     * in recurring events where gcal creates one event (with one unique IcalUID)
     * and a set of {@link When}-object for each occurrence.
     *
     * @param job the {@link Job} to create triggers for
     * @param event the {@link CalendarEventEntry} to read the {@link When}-objects
     *            from
     * @param modifiedByEvent defines the name of an event which modifies the
     *            schedule of the new Trigger
     * @param isStartEvent indicator to identify whether this trigger will be
     *            triggering a start or an end command.
     *
     * @throws SchedulerException if there is an internal Scheduler error.
     */
protected boolean createTriggerAndSchedule(JobDetail job, Event event, String modifiedByEvent, boolean isStartEvent) {
    boolean triggersCreated = false;
    if (job == null) {
        logger.debug("job is null -> no triggers are created");
        return false;
    }
    String jobIdentity = event.getICalUID() + (isStartEvent ? "_start" : "_end");
    EventDateTime date = isStartEvent ? event.getStart() : event.getEnd();
    long dateValue = date.getDateTime().getValue();
    /*
         * TODO: TEE: do only create a new trigger when the start/endtime
         * lies in the future. This exclusion is necessary because the SimpleTrigger
         * triggers a job even if the startTime lies in the past. If somebody
         * knows the way to let quartz ignore such triggers this exclusion
         * can be omitted.
         */
    if (dateValue >= (new Date()).getTime()) {
        Trigger trigger;
        if (StringUtils.isBlank(modifiedByEvent)) {
            trigger = newTrigger().forJob(job).withIdentity(jobIdentity + "_" + dateValue + "_trigger", GCAL_SCHEDULER_GROUP).startAt(new Date(dateValue)).build();
        } else {
            trigger = newTrigger().forJob(job).withIdentity(jobIdentity + "_" + dateValue + "_trigger", GCAL_SCHEDULER_GROUP).startAt(new Date(dateValue)).modifiedByCalendar(modifiedByEvent).build();
        }
        try {
            scheduler.scheduleJob(job, trigger);
            triggersCreated = true;
        } catch (SchedulerException se) {
            logger.warn("scheduling Trigger '{}' throws an exception: {}", trigger, se);
        }
    }
    // }
    return triggersCreated;
}
Also used : Trigger(org.quartz.Trigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) SchedulerException(org.quartz.SchedulerException) EventDateTime(com.google.api.services.calendar.model.EventDateTime) Date(java.util.Date)

Example 24 with SchedulerException

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

the class EventReloaderJob method removeDeletedEvents.

private synchronized void removeDeletedEvents(String calendarKey, List<String> oldMap) {
    final CalendarRuntime eventRuntime = EventStorage.getInstance().getEventCache().get(calendarKey);
    for (String filename : oldMap) {
        EventContainer eventContainer = eventRuntime.getEventContainerByFilename(filename);
        if (eventContainer == null) {
            log.error("cannot find event container for filename: {}", filename);
            continue;
        }
        // cancel old jobs
        for (String jobId : eventContainer.getTimerMap()) {
            try {
                String group;
                if (jobId.startsWith(CalDavLoaderImpl.JOB_NAME_EVENT_START)) {
                    group = CalDavLoaderImpl.JOB_NAME_EVENT_START;
                } else if (jobId.startsWith(CalDavLoaderImpl.JOB_NAME_EVENT_END)) {
                    group = CalDavLoaderImpl.JOB_NAME_EVENT_END;
                } else {
                    throw new SchedulerException("unknown job id: " + jobId);
                }
                boolean deleteJob = CalDavLoaderImpl.instance.getScheduler().deleteJob(JobKey.jobKey(jobId, group));
                log.debug("old job ({}) deleted? {}", jobId, deleteJob);
            } catch (SchedulerException e) {
                log.error("cannot delete job '{}'", jobId);
            }
        }
        eventContainer.getTimerMap().clear();
        for (EventNotifier notifier : CalDavLoaderImpl.instance.getEventListenerList()) {
            for (CalDavEvent event : eventContainer.getEventList()) {
                try {
                    notifier.eventRemoved(event);
                } catch (Exception e) {
                    log.error("error while invoking listener", e);
                }
            }
        }
        ConcurrentHashMap<String, EventContainer> eventContainerMap = eventRuntime.getEventMap();
        if (eventContainer != null) {
            this.removeFromDisk(eventContainer);
            log.debug("remove deleted event: {}", eventContainer.getEventId());
            eventContainerMap.remove(eventContainer.getEventId());
        }
    }
}
Also used : SchedulerException(org.quartz.SchedulerException) EventContainer(org.openhab.io.caldav.internal.EventStorage.EventContainer) CalDavEvent(org.openhab.io.caldav.CalDavEvent) EventNotifier(org.openhab.io.caldav.EventNotifier) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime) ParserException(net.fortuna.ical4j.data.ParserException) JobExecutionException(org.quartz.JobExecutionException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException) SardineException(com.github.sardine.impl.SardineException)

Example 25 with SchedulerException

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

the class DropboxSynchronizer method schedule.

/**
     * Schedules either a job handling the Upload (<code>LOCAL_TO_DROPBOX</code>)
     * or Download (<code>DROPBOX_TO_LOCAL</code>) direction depending on
     * <code>isUpload</code>.
     * 
     * @param interval the Trigger interval as cron expression
     * @param isUpload
     */
private void schedule(String interval, boolean isUpload) {
    String direction = isUpload ? "Upload" : "Download";
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        JobDetail job = newJob(SynchronizationJob.class).withIdentity(direction, DROPBOX_SCHEDULER_GROUP).build();
        CronTrigger trigger = newTrigger().withIdentity(direction, DROPBOX_SCHEDULER_GROUP).withSchedule(CronScheduleBuilder.cronSchedule(interval)).build();
        logger.debug("Scheduled synchronization job (direction={}) with cron expression '{}'", direction, interval);
        sched.scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        logger.warn("Could not create synchronization job: {}", e.getMessage());
    }
}
Also used : JobDetail(org.quartz.JobDetail) CronTrigger(org.quartz.CronTrigger) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler)

Aggregations

SchedulerException (org.quartz.SchedulerException)133 JobDetail (org.quartz.JobDetail)59 Trigger (org.quartz.Trigger)42 Scheduler (org.quartz.Scheduler)37 JobKey (org.quartz.JobKey)33 SimpleTrigger (org.quartz.SimpleTrigger)19 JobDataMap (org.quartz.JobDataMap)18 CronTrigger (org.quartz.CronTrigger)17 TriggerBuilder.newTrigger (org.quartz.TriggerBuilder.newTrigger)15 ApplicationContext (org.springframework.context.ApplicationContext)15 ArrayList (java.util.ArrayList)12 SchedulerContext (org.quartz.SchedulerContext)12 IOException (java.io.IOException)11 TriggerKey (org.quartz.TriggerKey)10 Date (java.util.Date)9 JobExecutionException (org.quartz.JobExecutionException)9 StdSchedulerFactory (org.quartz.impl.StdSchedulerFactory)6 ParseException (java.text.ParseException)5 Command (org.openhab.core.types.Command)5 JobSystemException (com.dangdang.ddframe.job.exception.JobSystemException)4