use of org.quartz.Trigger in project pinot by linkedin.
the class AlertJobSchedulerV2 method run.
public void run() {
try {
// read all alert configs
LOG.info("Reading all alert configs..");
List<AlertConfigDTO> alertConfigs = alertConfigDAO.findAll();
// get active jobs
List<String> scheduledJobs = getScheduledJobs();
LOG.info("Scheduled jobs {}", scheduledJobs);
for (AlertConfigDTO alertConfig : alertConfigs) {
Long id = alertConfig.getId();
String jobKey = getJobKey(id);
boolean isActive = alertConfig.isActive();
boolean isScheduled = scheduledJobs.contains(jobKey);
if (isActive) {
if (isScheduled) {
String cronInDatabase = alertConfig.getCronExpression();
List<Trigger> triggers = (List<Trigger>) quartzScheduler.getTriggersOfJob(JobKey.jobKey(jobKey));
CronTrigger cronTrigger = (CronTrigger) triggers.get(0);
String cronInSchedule = cronTrigger.getCronExpression();
// cron expression has been updated, restart this job
if (!cronInDatabase.equals(cronInSchedule)) {
LOG.info("Cron expression for config {} with jobKey {} has been changed from {} to {}. " + "Restarting schedule", id, jobKey, cronInSchedule, cronInDatabase);
stopJob(jobKey);
startJob(alertConfig, jobKey);
}
} else {
LOG.info("Found active but not scheduled {}", id);
startJob(alertConfig, jobKey);
}
} else {
if (isScheduled) {
LOG.info("Found inactive but scheduled {}", id);
stopJob(jobKey);
}
// for all jobs with not isActive, and not isScheduled, no change required
}
}
// stop the schedule, as function has been deleted
for (String scheduledJobKey : scheduledJobs) {
Long configId = getIdFromJobKey(scheduledJobKey);
AlertConfigDTO alertConfigSpec = alertConfigDAO.findById(configId);
if (alertConfigSpec == null) {
LOG.info("Found scheduled, but not in database {}", configId);
stopJob(scheduledJobKey);
}
}
} catch (SchedulerException e) {
LOG.error("Exception in reading active jobs", e);
}
}
use of org.quartz.Trigger in project head by mifos.
the class MifosBatchJob method catchUpMissedLaunches.
public void catchUpMissedLaunches(Job job, JobExecutionContext context) throws Exception {
List<JobInstance> jobInstances = jobExplorer.getJobInstances(job.getName(), 0, 1);
if (jobInstances.size() > 0) {
JobInstance jobInstance = jobInstances.get(0);
Date previousFireTime = new Date(jobInstance.getJobParameters().getLong(JOB_EXECUTION_TIME_KEY));
Date scheduledFireTime = context.getScheduledFireTime();
Trigger trigger = context.getTrigger();
boolean onDemandRun = false;
if (Scheduler.DEFAULT_MANUAL_TRIGGERS.equals(trigger.getGroup())) {
// this is a manual run
trigger = context.getScheduler().getTrigger(job.getName(), Scheduler.DEFAULT_GROUP);
scheduledFireTime = new DateTimeService().getCurrentDateTime().toDate();
onDemandRun = true;
}
List<Date> missedLaunches = computeMissedJobLaunches(previousFireTime, scheduledFireTime, trigger, onDemandRun);
for (Date missedLaunch : missedLaunches) {
JobParameters jobParameters = createJobParameters(missedLaunch.getTime());
launchJob(job, jobParameters);
}
}
}
use of org.quartz.Trigger in project head by mifos.
the class BatchjobsServiceFacadeWebTier method getBatchjobs.
@Override
public List<BatchjobsDto> getBatchjobs(ServletContext context) throws TaskSystemException, FileNotFoundException, IOException, SchedulerException {
List<BatchjobsDto> batchjobs = new ArrayList<BatchjobsDto>();
MifosScheduler mifosScheduler = (MifosScheduler) context.getAttribute(MifosScheduler.class.getName());
Scheduler scheduler = mifosScheduler.getScheduler();
for (String groupName : scheduler.getJobGroupNames()) {
for (String jobName : scheduler.getJobNames(groupName)) {
Trigger[] triggers = scheduler.getTriggersOfJob(jobName, groupName);
Trigger trigger = triggers.length > 0 ? triggers[0] : null;
JobDetail jobDetail = scheduler.getJobDetail(jobName, groupName);
if (trigger != null && jobDetail != null) {
Date nextFire = trigger.getNextFireTime() != null ? trigger.getNextFireTime() : new Date(0);
Date lastFire = mifosScheduler.getJobsPreviousRunTime(jobName);
Date lastSuccessfulRun = mifosScheduler.getJobsLastSuccessfulRunTime(jobName);
int priority = trigger.getPriority();
String frequency = "";
String taskType = "";
if (trigger instanceof CronTrigger) {
frequency = ((CronTrigger) trigger).getCronExpression();
taskType = CRON_TRIGGER;
}
if (trigger instanceof SimpleTrigger) {
frequency = Long.toString(((SimpleTrigger) trigger).getRepeatInterval());
taskType = SIMPLE_TRIGGER;
}
String previousRunStatus = mifosScheduler.getJobsPreviousRunStatus(jobName);
int triggerState = scheduler.getTriggerState(trigger.getName(), groupName);
String failDescription = mifosScheduler.getJobFailDescription(jobName);
batchjobs.add(new BatchjobsDto(jobName, frequency, taskType, priority, previousRunStatus, lastFire, lastSuccessfulRun, nextFire, triggerState, failDescription));
}
}
}
return batchjobs;
}
use of org.quartz.Trigger in project openhab1-addons by openhab.
the class MyStromEcoPowerBinding method internalReceiveCommand.
/**
* @{inheritDoc
*/
@Override
protected void internalReceiveCommand(String itemName, Command command) {
// the code being executed when a command was sent on the openHAB
// event bus goes here. This method is only called if one of the
// BindingProviders provide a binding for the given 'itemName'.
logger.debug("internalReceiveCommand() is called!");
String deviceId = null;
for (MyStromEcoPowerBindingProvider provider : providers) {
String switchFriendlyName = provider.getMystromFriendlyName(itemName);
deviceId = this.devicesMap.get(switchFriendlyName);
logger.debug("item '{}' is configured as '{}'", itemName, switchFriendlyName);
if (deviceId != null) {
if (provider.getIsSwitch(itemName)) {
try {
logger.debug("Command '{}' is about to be sent to item '{}'", command, itemName);
if (OnOffType.ON.equals(command) || OnOffType.OFF.equals(command)) {
// on/off command
boolean onOff = OnOffType.ON.equals(command);
logger.debug("command '{}' transformed to '{}'", command, onOff ? "on" : "off");
boolean actualState = this.mystromClient.getDeviceInfo(deviceId).state.equals("on");
if (onOff == actualState) {
// mystrom state is the same, may be due to
// change state on/off too
// rapidly, so postpone change state
String scheduledCommand = deviceId + ";" + onOff;
logger.debug("Schedule command: " + scheduledCommand);
JobDetail job = JobBuilder.newJob(org.openhab.binding.mystromecopower.internal.util.ChangeStateJob.class).usingJobData(org.openhab.binding.mystromecopower.internal.util.ChangeStateJob.JOB_DATA_CONTENT_KEY, scheduledCommand).withIdentity(itemName, "MYSTROMECOPOWER").build();
Date dateTrigger = new Date(System.currentTimeMillis() + 5000L);
Trigger trigger = newTrigger().forJob(job).withIdentity(itemName + "_" + dateTrigger + "_trigger", "MYSTROMECOPOWER").startAt(dateTrigger).build();
this.scheduler.scheduleJob(job, trigger);
} else {
if (this.masterDevice == null || (this.masterDevice != null && deviceId != this.masterDevice.id)) {
// This is not the master device.
if (!this.mystromClient.ChangeState(deviceId, onOff)) {
// Unsuccessful state change, inform bus
// that the good
// state is the old one.
eventPublisher.postUpdate(itemName, onOff ? OnOffType.OFF : OnOffType.ON);
}
} else {
// This is the mater device.
if (this.masterDevice != null && OnOffType.OFF.equals(command)) {
// Do a reset if try to set OFF the
// master device.
logger.debug("Restart master device");
this.mystromClient.RestartMaster(deviceId);
}
}
}
}
} catch (Exception e) {
logger.error("Failed to send '{}' command", command, e);
}
}
} else {
logger.error("Unable to send command to '{}'. Device is not in discovery table", itemName);
}
}
}
use of org.quartz.Trigger 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);
}
}
}
}
}
}
}
}
}
Aggregations