Search in sources :

Example 1 with JobDataMap

use of org.quartz.JobDataMap in project jmxtrans by jmxtrans.

the class JmxTransformer method scheduleJob.

private void scheduleJob(Server server) throws ParseException, SchedulerException {
    String name = server.getHost() + ":" + server.getPort() + "-" + System.currentTimeMillis() + "-" + RandomStringUtils.randomNumeric(10);
    JobDetail jd = new JobDetail(name, "ServerJob", ServerJob.class);
    JobDataMap map = new JobDataMap();
    map.put(Server.class.getName(), server);
    jd.setJobDataMap(map);
    Trigger trigger;
    if ((server.getCronExpression() != null) && CronExpression.isValidExpression(server.getCronExpression())) {
        trigger = new CronTrigger();
        ((CronTrigger) trigger).setCronExpression(server.getCronExpression());
        trigger.setName(server.getHost() + ":" + server.getPort() + "-" + Long.toString(System.currentTimeMillis()));
        trigger.setStartTime(computeSpreadStartDate(configuration.getRunPeriod()));
    } else {
        int runPeriod = configuration.getRunPeriod();
        if (server.getRunPeriodSeconds() != null)
            runPeriod = server.getRunPeriodSeconds();
        Trigger minuteTrigger = TriggerUtils.makeSecondlyTrigger(runPeriod);
        minuteTrigger.setName(server.getHost() + ":" + server.getPort() + "-" + Long.toString(System.currentTimeMillis()));
        minuteTrigger.setStartTime(computeSpreadStartDate(runPeriod));
        trigger = minuteTrigger;
    // TODO replace Quartz with a ScheduledExecutorService
    }
    serverScheduler.scheduleJob(jd, trigger);
    if (log.isDebugEnabled()) {
        log.debug("Scheduled job: " + jd.getName() + " for server: " + server);
    }
}
Also used : JobDetail(org.quartz.JobDetail) JobDataMap(org.quartz.JobDataMap) CronTrigger(org.quartz.CronTrigger) Trigger(org.quartz.Trigger) CronTrigger(org.quartz.CronTrigger) MBeanServer(javax.management.MBeanServer) Server(com.googlecode.jmxtrans.model.Server)

Example 2 with JobDataMap

use of org.quartz.JobDataMap in project head by mifos.

the class BatchJobCatchUpIntegrationTest method testIncompleteTaskDelay.

@Test
public void testIncompleteTaskDelay() throws Exception {
    mifosScheduler = getMifosScheduler("org/mifos/framework/components/batchjobs/catchUpTask.xml");
    Scheduler scheduler = mifosScheduler.getScheduler();
    ProductStatus productStatusTask = new ProductStatus();
    productStatusTask.setJobExplorer(mifosScheduler.getBatchJobExplorer());
    productStatusTask.setJobLauncher(mifosScheduler.getBatchJobLauncher());
    productStatusTask.setJobLocator(mifosScheduler.getBatchJobLocator());
    productStatusTask.setJobRepository(mifosScheduler.getBatchJobRepository());
    String quartzJobName = "ProductStatusJob";
    String quartzTriggerName = "ProductStatusTrigger2";
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.set(Calendar.SECOND, 10);
    Date previousFireTime = calendar.getTime();
    calendar.set(Calendar.SECOND, 21);
    Date quartzFireTime = calendar.getTime();
    calendar.set(Calendar.SECOND, 22);
    Date quartzNextFireTime = calendar.getTime();
    calendar.set(Calendar.SECOND, 20);
    Date quartzPrevFireTime = calendar.getTime();
    JobDetail jobDetail = scheduler.getJobDetail(quartzJobName, Scheduler.DEFAULT_GROUP);
    jobDetail.setJobDataMap(new JobDataMap());
    CronTrigger trigger = new CronTrigger(quartzTriggerName, Scheduler.DEFAULT_GROUP, quartzJobName, Scheduler.DEFAULT_GROUP, "* * * * * ?");
    trigger.setJobDataMap(new JobDataMap());
    TriggerFiredBundle triggerFiredBundle = new TriggerFiredBundle(jobDetail, trigger, new BaseCalendar(), false, quartzFireTime, quartzFireTime, quartzPrevFireTime, quartzNextFireTime);
    JobExecutionContext jobExecutionContext = new JobExecutionContext(scheduler, triggerFiredBundle, productStatusTask);
    JobLauncher jobLauncher = mifosScheduler.getBatchJobLauncher();
    JobLocator jobLocator = mifosScheduler.getBatchJobLocator();
    jobLauncher.run(jobLocator.getJob(jobName), MifosBatchJob.createJobParameters(previousFireTime.getTime()));
    Thread.sleep(1500);
    productStatusTask.catchUpMissedLaunches(jobLocator.getJob(jobName), jobExecutionContext);
    JobExplorer explorer = mifosScheduler.getBatchJobExplorer();
    List<JobInstance> jobInstances = explorer.getJobInstances(jobName, 0, 20);
    Assert.assertEquals(11, jobInstances.size());
    for (JobInstance jobInstance : jobInstances) {
        List<JobExecution> jobExecutions = explorer.getJobExecutions(jobInstance);
        Assert.assertEquals(BatchStatus.COMPLETED, jobExecutions.get(0).getStatus());
        Assert.assertEquals(calendar.getTimeInMillis(), jobInstance.getJobParameters().getLong(MifosBatchJob.JOB_EXECUTION_TIME_KEY));
        calendar.roll(Calendar.SECOND, false);
    }
}
Also used : JobDataMap(org.quartz.JobDataMap) CronTrigger(org.quartz.CronTrigger) JobLauncher(org.springframework.batch.core.launch.JobLauncher) BaseCalendar(org.quartz.impl.calendar.BaseCalendar) JobInstance(org.springframework.batch.core.JobInstance) Scheduler(org.quartz.Scheduler) Calendar(java.util.Calendar) BaseCalendar(org.quartz.impl.calendar.BaseCalendar) JobLocator(org.springframework.batch.core.configuration.JobLocator) ProductStatus(org.mifos.framework.components.batchjobs.helpers.ProductStatus) TriggerFiredBundle(org.quartz.spi.TriggerFiredBundle) Date(java.util.Date) JobExecution(org.springframework.batch.core.JobExecution) JobDetail(org.quartz.JobDetail) JobExecutionContext(org.quartz.JobExecutionContext) JobExplorer(org.springframework.batch.core.explore.JobExplorer) Test(org.junit.Test)

Example 3 with JobDataMap

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

the class AbstractSocketChannelBinding method execute.

/**
     * @{inheritDoc}
     */
@Override
protected void execute() {
    // Cycle through the Items and setup channels if required
    for (P provider : providers) {
        for (String itemName : provider.getItemNames()) {
            for (Command aCommand : provider.getAllCommands(itemName)) {
                String remoteHost = provider.getHost(itemName, aCommand);
                String remotePort = provider.getPortAsString(itemName, aCommand);
                Direction direction = provider.getDirection(itemName, aCommand);
                InetSocketAddress remoteAddress = null;
                if (!(remoteHost.equals("*") || remotePort.equals("*"))) {
                    remoteAddress = new InetSocketAddress(remoteHost, Integer.parseInt(remotePort));
                }
                Channel newChannel = null;
                Channel existingChannel = null;
                if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                    newChannel = new Channel(itemName, aCommand, remoteHost, remotePort, provider.getDirection(itemName, aCommand), false, null, false, null);
                    existingChannel = channels.get(itemName, aCommand, direction, remoteHost, remotePort);
                } else {
                    newChannel = new Channel(itemName, aCommand, remoteAddress, provider.getDirection(itemName, aCommand), false, null, false, null);
                    existingChannel = channels.get(itemName, aCommand, direction, remoteAddress);
                }
                if (existingChannel == null) {
                    if (direction == Direction.IN) {
                        boolean assigned = false;
                        if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                            logger.warn("When using address masks we will not verify if we are already listening to similar incoming connections");
                            logger.info("We will accept data coming from the remote end {}:{}", remoteHost, remotePort);
                            channels.add(newChannel);
                        } else {
                            if (itemShareChannels) {
                                Channel firstChannel = channels.getFirstServed(itemName, direction, remoteAddress);
                                if (firstChannel != null) {
                                    newChannel.channel = firstChannel.channel;
                                    assigned = true;
                                }
                            }
                            if (bindingShareChannels) {
                                Channel firstChannel = channels.getFirstServed(direction, remoteAddress);
                                if (firstChannel != null) {
                                    newChannel.channel = firstChannel.channel;
                                    assigned = true;
                                }
                            }
                            if (directionsShareChannels) {
                                Channel firstChannel = channels.getFirstServed(remoteAddress);
                                if (firstChannel != null) {
                                    newChannel.channel = firstChannel.channel;
                                    assigned = true;
                                }
                            }
                            if (!assigned || newChannel.channel == null) {
                                if (channels.contains(itemName, aCommand, Direction.IN, remoteAddress)) {
                                    logger.warn("We already listen for incoming connections from {}", remoteAddress);
                                } else {
                                    logger.debug("Setting up the inbound channel {}", newChannel);
                                    channels.add(newChannel);
                                    logger.info("We will accept data coming from the remote end {}", remoteAddress);
                                }
                            }
                        }
                    } else if (direction == Direction.OUT) {
                        boolean assigned = false;
                        if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                            logger.error("We do not accept outgoing connections for Items that do use address masks");
                        } else {
                            channels.add(newChannel);
                            if (newChannel.channel == null) {
                                if (itemShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(itemName, direction, remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }
                                if (bindingShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(direction, remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }
                                if (directionsShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }
                                if (assigned) {
                                    logger.debug("Setting up the outbound assigned channel {} ", newChannel);
                                }
                                synchronized (this) {
                                    if (!assigned || newChannel.channel == null) {
                                        SocketChannel newSocketChannel = null;
                                        try {
                                            newSocketChannel = SocketChannel.open();
                                        } catch (IOException e2) {
                                            logger.error("An exception occurred while opening a channel: {}", e2.getMessage());
                                        }
                                        try {
                                            newSocketChannel.socket().setKeepAlive(true);
                                            newSocketChannel.configureBlocking(false);
                                        } catch (IOException e) {
                                            logger.error("An exception occurred while configuring a channel: {}", e.getMessage());
                                        }
                                        synchronized (selector) {
                                            selector.wakeup();
                                            int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT;
                                            try {
                                                newSocketChannel.register(selector, interestSet);
                                            } catch (ClosedChannelException e1) {
                                                logger.error("An exception occurred while registering a selector: {}", e1.getMessage());
                                            }
                                        }
                                        newChannel.channel = newSocketChannel;
                                        logger.debug("Setting up the outbound channel {}", newChannel);
                                        try {
                                            logger.info("Connecting the channel {} ", newChannel);
                                            newSocketChannel.connect(remoteAddress);
                                        } catch (IOException e) {
                                            logger.error("An exception occurred while connecting a channel: {}", e.getMessage());
                                        }
                                    }
                                }
                            } else {
                                logger.info("There is already an active channel {} for the remote end {}", newChannel.channel, newChannel.remote);
                            }
                        }
                    }
                }
            }
        }
    }
    // Check on channels for which we have to process data
    synchronized (selector) {
        try {
            // Wait for an event
            selector.selectNow();
        } catch (IOException e) {
            logger.error("An exception occurred while Selecting ({})", e.getMessage());
        }
    }
    // Get list of selection keys with pending events
    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    // Process each key at a time
    while (it.hasNext()) {
        SelectionKey selKey = it.next();
        it.remove();
        if (selKey.isValid()) {
            if (selKey == listenerKey) {
                if (selKey.isAcceptable()) {
                    try {
                        SocketChannel newChannel = listenerChannel.accept();
                        logger.info("Received connection request from {}", newChannel.getRemoteAddress());
                        Channel firstChannel = channels.getFirstNotServed(Direction.IN, (InetSocketAddress) newChannel.getRemoteAddress());
                        if (firstChannel != null) {
                            if (firstChannel.direction == Direction.IN) {
                                if (useAddressMask && (firstChannel.host.equals("*") || firstChannel.port.equals("*"))) {
                                    logger.info("{}:{} is an allowed masked remote end. The channel will now be configured", firstChannel.host, firstChannel.port);
                                } else {
                                    logger.info("{} is an allowed remote end. The channel will now be configured", firstChannel.remote);
                                }
                                if (firstChannel.channel == null || !firstChannel.channel.isOpen()) {
                                    firstChannel.channel = newChannel;
                                    firstChannel.isBlocking = false;
                                    firstChannel.buffer = null;
                                    if (itemShareChannels) {
                                        channels.replace(firstChannel.item, firstChannel.direction, (InetSocketAddress) newChannel.getRemoteAddress(), firstChannel.channel);
                                    }
                                    if (bindingShareChannels) {
                                        channels.replace(firstChannel.direction, (InetSocketAddress) newChannel.getRemoteAddress(), firstChannel.channel);
                                    }
                                    if (directionsShareChannels) {
                                        channels.replace((InetSocketAddress) newChannel.getRemoteAddress(), firstChannel.channel);
                                    }
                                    try {
                                        newChannel.configureBlocking(false);
                                    // setKeepAlive(true);
                                    } catch (IOException e) {
                                        logger.error("An exception occurred while configuring a channel: {}", e.getMessage());
                                    }
                                    synchronized (selector) {
                                        selector.wakeup();
                                        try {
                                            newChannel.register(selector, newChannel.validOps());
                                        } catch (ClosedChannelException e1) {
                                            logger.error("An exception occurred while registering a selector: {}", e1.getMessage());
                                        }
                                    }
                                    Scheduler scheduler = null;
                                    try {
                                        scheduler = StdSchedulerFactory.getDefaultScheduler();
                                    } catch (SchedulerException e1) {
                                        logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                                    }
                                    JobDataMap map = new JobDataMap();
                                    map.put("Channel", firstChannel);
                                    map.put("Binding", this);
                                    JobDetail job = newJob(ConfigureJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Configure-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                                    Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Configure-" + Long.toString(System.currentTimeMillis()), this.toString()).startNow().build();
                                    try {
                                        if (job != null && trigger != null && selKey != listenerKey) {
                                            scheduler.scheduleJob(job, trigger);
                                        }
                                    } catch (SchedulerException e) {
                                        logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                                    }
                                } else {
                                    logger.info("We previously already accepted a connection from the remote end {} for this channel. Goodbye", firstChannel.remote);
                                    newChannel.close();
                                }
                            } else {
                                logger.info("Disconnecting the remote end {} that tries to connect an outbound only port", newChannel.getRemoteAddress());
                                newChannel.close();
                            }
                        } else {
                            logger.info("Disconnecting the unallowed remote end {}", newChannel.getRemoteAddress());
                            newChannel.close();
                        }
                    } catch (IOException e) {
                        logger.error("An exception occurred while configuring a channel: {}", e.getMessage());
                    }
                }
            } else {
                SocketChannel theSocketChannel = (SocketChannel) selKey.channel();
                Channel theChannel = channels.get(theSocketChannel);
                if (selKey.isConnectable()) {
                    channels.setAllReconnecting(theSocketChannel, false);
                    boolean result = false;
                    boolean error = false;
                    try {
                        result = theSocketChannel.finishConnect();
                    } catch (NoConnectionPendingException e) {
                        // this channel is not connected and a connection operation
                        // has not been initiated
                        logger.warn("The channel {} has no connection pending ({})", theSocketChannel, e.getMessage());
                        error = true;
                    } catch (ClosedChannelException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel {} is closed ({})", theSocketChannel, e.getMessage());
                        error = true;
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel {} has encountered an unknown IO Exception: {}", theSocketChannel, e.getMessage());
                        error = true;
                    }
                    if (error) {
                        Scheduler scheduler = null;
                        try {
                            scheduler = StdSchedulerFactory.getDefaultScheduler();
                        } catch (SchedulerException e1) {
                            logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                        }
                        JobDataMap map = new JobDataMap();
                        map.put("Channel", theChannel);
                        map.put("Binding", this);
                        JobDetail job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                        Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).startAt(futureDate(reconnectInterval, IntervalUnit.SECOND)).build();
                        try {
                            if (job != null && trigger != null && selKey != listenerKey) {
                                if (!theChannel.isReconnecting) {
                                    channels.setAllReconnecting(theSocketChannel, true);
                                    scheduler.scheduleJob(job, trigger);
                                }
                            }
                        } catch (SchedulerException e) {
                            logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                        }
                    } else {
                        if (result) {
                            InetSocketAddress remote = null;
                            try {
                                remote = (InetSocketAddress) theSocketChannel.getRemoteAddress();
                            } catch (IOException e) {
                                logger.error("An exception occurred while getting the remote address of channel {} ({})", theSocketChannel, e.getMessage());
                            }
                            logger.info("The channel for {} is now connected", remote);
                            if (itemShareChannels) {
                                channels.replace(theChannel.item, theChannel.direction, remote, theChannel.channel);
                            }
                            if (bindingShareChannels) {
                                channels.replace(theChannel.direction, remote, theChannel.channel);
                            }
                            if (directionsShareChannels) {
                                channels.replace(remote, theChannel.channel);
                            }
                            Scheduler scheduler = null;
                            try {
                                scheduler = StdSchedulerFactory.getDefaultScheduler();
                            } catch (SchedulerException e1) {
                                logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                            }
                            JobDataMap map = new JobDataMap();
                            map.put("Channel", theChannel);
                            map.put("Binding", this);
                            JobDetail job = newJob(ConfigureJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Configure-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                            Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Configure-" + Long.toString(System.currentTimeMillis()), this.toString()).startNow().build();
                            try {
                                if (job != null && trigger != null && selKey != listenerKey) {
                                    scheduler.scheduleJob(job, trigger);
                                }
                            } catch (SchedulerException e) {
                                logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                            }
                            job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                            trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).withSchedule(cronSchedule(reconnectCron)).build();
                            try {
                                if (job != null && trigger != null && selKey != listenerKey) {
                                    scheduler.scheduleJob(job, trigger);
                                }
                            } catch (SchedulerException e) {
                                logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                            }
                        }
                    }
                } else if (selKey.isReadable()) {
                    ByteBuffer readBuffer = ByteBuffer.allocate(maximumBufferSize);
                    int numberBytesRead = 0;
                    boolean error = false;
                    try {
                        // TODO: Additional code to split readBuffer in multiple parts, in case the data send by the
                        // remote end is not correctly fragemented. Could be handed of to implementation class if
                        // for example, the buffer needs to be split based on a special character like line feed or
                        // carriage return
                        numberBytesRead = theSocketChannel.read(readBuffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel for {} has no connection pending ({})", theChannel.remote, e.getMessage());
                        if (!theSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel for {} has encountered an unknown IO Exception: {}", theChannel.remote, e.getMessage());
                        error = true;
                    }
                    if (numberBytesRead == -1) {
                        try {
                            theSocketChannel.close();
                        } catch (IOException e) {
                            logger.warn("The channel for {} is closed ({})", theChannel.remote, e.getMessage());
                        }
                        error = true;
                    }
                    if (error) {
                        if (theChannel.direction == Direction.OUT) {
                            Scheduler scheduler = null;
                            try {
                                scheduler = StdSchedulerFactory.getDefaultScheduler();
                            } catch (SchedulerException e1) {
                                logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                            }
                            JobDataMap map = new JobDataMap();
                            map.put("Channel", theChannel);
                            map.put("Binding", this);
                            JobDetail job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), "AbstractSocketChannelBinding").usingJobData(map).build();
                            Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), "AbstractSocketChannelBinding").startAt(futureDate(reconnectInterval, IntervalUnit.SECOND)).build();
                            try {
                                if (job != null && trigger != null && selKey != listenerKey) {
                                    if (!theChannel.isReconnecting) {
                                        channels.setAllReconnecting(theSocketChannel, true);
                                        scheduler.scheduleJob(job, trigger);
                                    }
                                }
                            } catch (SchedulerException e) {
                                logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                            }
                        } else {
                            theChannel.channel = null;
                        }
                    } else {
                        ArrayList<Channel> channelsToServe = new ArrayList<Channel>();
                        channelsToServe = channels.getAll(theSocketChannel);
                        if (channelsToServe.size() > 0) {
                            readBuffer.flip();
                            boolean isBlocking = channels.isBlocking(theSocketChannel);
                            if (isBlocking) {
                                // if we are in a blocking operation, we get are now finished and we have to reset
                                // the flag. The read buffer will be returned to the instance
                                // that initiated the write opreation - it has to parse the buffer itself
                                theChannel = channels.getBlocking(theSocketChannel);
                                theChannel.buffer = readBuffer;
                                theChannel.isBlocking = false;
                            } else {
                                for (Channel aChannel : channelsToServe) {
                                    // if not, then we parse the buffer as ususal
                                    parseChanneledBuffer(aChannel, readBuffer);
                                }
                            }
                        } else {
                            try {
                                logger.warn("No channel is active or defined for the data we received from {}. It will be discarded.", theSocketChannel.getRemoteAddress());
                            } catch (IOException e) {
                                logger.error("An exception occurred while getting the remote address of the channel {} ({})", theSocketChannel, e.getMessage());
                            }
                        }
                    }
                } else if (selKey.isWritable()) {
                    boolean isBlocking = channels.isBlocking(theSocketChannel);
                    if (isBlocking) {
                    // if this channel is already flagged as being in a blocked write/read operation, we skip
                    // this selKey
                    } else {
                        // pick up a QueueElement for this channel, if any
                        WriteBufferElement theElement = null;
                        Iterator<WriteBufferElement> iterator = writeQueue.iterator();
                        while (iterator.hasNext()) {
                            WriteBufferElement anElement = iterator.next();
                            if (anElement.channel.channel.equals(theSocketChannel)) {
                                theElement = anElement;
                                break;
                            }
                        }
                        if (theElement != null && theElement.buffer != null) {
                            logger.debug("Picked {} from the queue", theElement);
                            if (theElement.isBlocking) {
                                theElement.channel.isBlocking = true;
                            }
                            boolean error = false;
                            theElement.buffer.rewind();
                            try {
                                logger.debug("Sending {} for the outbound channel {}->{}", new Object[] { new String(theElement.buffer.array()), theElement.channel.channel.getLocalAddress(), theElement.channel.channel.getRemoteAddress() });
                                theSocketChannel.write(theElement.buffer);
                            } catch (NotYetConnectedException e) {
                                logger.warn("The channel for {} has no connection pending ({})", theChannel.remote, e.getMessage());
                                if (!theSocketChannel.isConnectionPending()) {
                                    error = true;
                                }
                            } catch (ClosedChannelException e) {
                                // If some other I/O error occurs
                                logger.warn("The channel for {} is closed ({})", theChannel.remote, e.getMessage());
                                error = true;
                            } catch (IOException e) {
                                // If some other I/O error occurs
                                logger.warn("The channel for {} has encountered an unknown IO Exception: {}", theChannel.remote, e.getMessage());
                                error = true;
                            }
                            if (error) {
                                if (theElement.channel.direction == Direction.OUT) {
                                    Scheduler scheduler = null;
                                    try {
                                        scheduler = StdSchedulerFactory.getDefaultScheduler();
                                    } catch (SchedulerException e1) {
                                        logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                                    }
                                    JobDataMap map = new JobDataMap();
                                    map.put("Channel", theElement.channel);
                                    map.put("Binding", this);
                                    JobDetail job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), "AbstractSocketChannelBinding").usingJobData(map).build();
                                    Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), "AbstractSocketChannelBinding").startAt(futureDate(reconnectInterval, IntervalUnit.SECOND)).build();
                                    try {
                                        if (job != null && trigger != null && selKey != listenerKey) {
                                            if (!theElement.channel.isReconnecting) {
                                                channels.setAllReconnecting(theSocketChannel, true);
                                                scheduler.scheduleJob(job, trigger);
                                            }
                                        }
                                    } catch (SchedulerException e) {
                                        logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                                    }
                                } else {
                                    theElement.channel.channel = null;
                                }
                            } else {
                                if (theElement != null) {
                                    writeQueue.remove(theElement);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SchedulerException(org.quartz.SchedulerException) InetSocketAddress(java.net.InetSocketAddress) Scheduler(org.quartz.Scheduler) ArrayList(java.util.ArrayList) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) ClosedChannelException(java.nio.channels.ClosedChannelException) SelectionKey(java.nio.channels.SelectionKey) JobDataMap(org.quartz.JobDataMap) NoConnectionPendingException(java.nio.channels.NoConnectionPendingException) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) IOException(java.io.IOException) NotYetConnectedException(java.nio.channels.NotYetConnectedException) ByteBuffer(java.nio.ByteBuffer) Command(org.openhab.core.types.Command)

Example 4 with JobDataMap

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

the class AbstractSocketChannelBinding method internalReceiveCommand.

/**
     * {@inheritDoc}
     */
@Override
protected void internalReceiveCommand(String itemName, Command command) {
    P provider = findFirstMatchingBindingProvider(itemName);
    if (provider == null) {
        logger.warn("cannot find matching binding provider [itemName={}, command={}]", itemName, command);
        return;
    }
    if (command != null) {
        List<Command> commands = provider.getQualifiedCommands(itemName, command);
        for (Command someCommand : commands) {
            Channel theChannel = null;
            if (useAddressMask && (provider.getHost(itemName, someCommand).equals("*") || provider.getPortAsString(itemName, someCommand).equals("*"))) {
                theChannel = channels.get(itemName, someCommand, provider.getDirection(itemName, someCommand), provider.getHost(itemName, someCommand), provider.getPortAsString(itemName, someCommand));
            } else {
                theChannel = channels.get(itemName, someCommand, provider.getDirection(itemName, someCommand), new InetSocketAddress(provider.getHost(itemName, someCommand), provider.getPort(itemName, someCommand)));
            }
            SocketChannel theSocketChannel = null;
            if (theChannel != null) {
                theSocketChannel = theChannel.channel;
            }
            if (theSocketChannel != null) {
                boolean result = internalReceiveChanneledCommand(itemName, someCommand, theChannel, command.toString());
                if (!theSocketChannel.isConnected() && !(useAddressMask && (provider.getHost(itemName, someCommand).equals("*") || provider.getPortAsString(itemName, someCommand).equals("*")))) {
                    logger.warn("The channel for {} has a connection problem. Data will queued to the new channel when it is successfully set up.", theChannel.remote);
                    if (!theSocketChannel.isConnectionPending() || !theSocketChannel.isOpen()) {
                        Scheduler scheduler = null;
                        try {
                            scheduler = StdSchedulerFactory.getDefaultScheduler();
                        } catch (SchedulerException e1) {
                            logger.error("An exception occurred while getting the Quartz scheduler: {}", e1.getMessage());
                        }
                        JobDataMap map = new JobDataMap();
                        map.put("Channel", theChannel);
                        map.put("Binding", this);
                        JobDetail job = newJob(ReconnectJob.class).withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).usingJobData(map).build();
                        Trigger trigger = newTrigger().withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-" + Long.toString(System.currentTimeMillis()), this.toString()).startNow().build();
                        try {
                            if (job != null && trigger != null) {
                                if (!theChannel.isReconnecting) {
                                    theChannel.isReconnecting = true;
                                    scheduler.scheduleJob(job, trigger);
                                }
                            }
                        } catch (SchedulerException e) {
                            logger.error("An exception occurred while scheduling a job with the Quartz Scheduler {}", e.getMessage());
                        }
                    }
                }
                if (result) {
                    List<Class<? extends State>> stateTypeList = provider.getAcceptedDataTypes(itemName, someCommand);
                    State newState = createStateFromString(stateTypeList, command.toString());
                    if (newState != null) {
                        eventPublisher.postUpdate(itemName, newState);
                    }
                }
            } else {
                logger.error("there is no channel that services [itemName={}, command={}]", itemName, command);
            }
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) JobDataMap(org.quartz.JobDataMap) SchedulerException(org.quartz.SchedulerException) InetSocketAddress(java.net.InetSocketAddress) Scheduler(org.quartz.Scheduler) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) Command(org.openhab.core.types.Command) State(org.openhab.core.types.State)

Example 5 with JobDataMap

use of org.quartz.JobDataMap 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)

Aggregations

JobDataMap (org.quartz.JobDataMap)56 Trigger (org.quartz.Trigger)21 SchedulerException (org.quartz.SchedulerException)20 JobDetail (org.quartz.JobDetail)18 TriggerBuilder.newTrigger (org.quartz.TriggerBuilder.newTrigger)11 Scheduler (org.quartz.Scheduler)10 JobExecutionException (org.quartz.JobExecutionException)9 ApplicationContext (org.springframework.context.ApplicationContext)9 ArrayList (java.util.ArrayList)6 Date (java.util.Date)6 HashMap (java.util.HashMap)6 TriggerBean (org.akaza.openclinica.bean.admin.TriggerBean)6 Command (org.openhab.core.types.Command)5 SchedulerContext (org.quartz.SchedulerContext)5 SimpleTrigger (org.quartz.SimpleTrigger)5 IOException (java.io.IOException)4 InetSocketAddress (java.net.InetSocketAddress)4 SocketChannel (java.nio.channels.SocketChannel)4 Locale (java.util.Locale)4 DatasetBean (org.akaza.openclinica.bean.extract.DatasetBean)4