Cancel old waiting jobs.

@param starttimeThreshold threshold for start time
@param checkTimeThreshold threshold for last check time
@param message the error message
196369
public final void cancelOld(
            final long starttimeThreshold, final long checkTimeThreshold, final String message) {
        final CriteriaBuilder builder = getSession().getCriteriaBuilder();
        final CriteriaUpdate<PrintJobStatusExtImpl> update =
                builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);
        final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);
        update.where(builder.and(
                builder.equal(root.get("status"), PrintJobStatus.Status.WAITING),
                builder.or(
                        builder.lessThan(root.get("entry").get("startTime"), starttimeThreshold),
                        builder.and(builder.isNotNull(root.get("lastCheckTime")),
                                    builder.lessThan(root.get("lastCheckTime"), checkTimeThreshold))
                )
        ));
        update.set(root.get("status"), PrintJobStatus.Status.CANCELLED);
        update.set(root.get("error"), message);
        getSession().createQuery(update).executeUpdate();
    }
622284
private void checkStarted() throws SINotPossibleInCurrentConfigurationException 
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "checkStarted");

    synchronized (this)
    {
      if (!isStarted())
      {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
          SibTr.exit(tc, "checkStarted", "ME not started");

        throw new SINotPossibleInCurrentConfigurationException(
          nls.getFormattedMessage("MESSAGE_PROCESSOR_NOT_STARTED_ERROR_CWSIP0211", 
          new Object[] { messageProcessor.getMessagingEngineName(), messageProcessor.getMessagingEngineBus()}, 
          null));
      }
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "checkStarted");
  }
1346997
public void checkForTimeouts(long checkTime) {
        TimeSlot nextSlot = this.firstSlot;
        TimerWorkItem entry = null;
        TimeSlot oldSlot = null;

        while (nextSlot != null && checkTime >= nextSlot.timeoutTime) {
            // Timeout all entries here
            int endIndex = nextSlot.lastEntryIndex;
            for (int i = 0; i <= endIndex; i++) {
                // invoke callback if not already cancelled
                entry = nextSlot.entries[i];

                if (entry.state == TimerWorkItem.ENTRY_ACTIVE) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Found a timeout, calling timerTriggered");
                    }
                    entry.state = TimerWorkItem.ENTRY_CANCELLED;
                    entry.callback.timerTriggered(entry);
                }
            }

            // since we timed out all slot entries, remove it
            oldSlot = nextSlot;
            removeSlot(oldSlot);
            nextSlot = nextSlot.nextEntry;
        }
    }
256141
public final void cancel(CancelException reason) {
		if (cancelling != null)
			return;
		if (reason == null) reason = new CancelException("No reason given");
		cancelling = reason;
		if (TaskScheduler.cancel(this)) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
		if (manager.remove(this)) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
		if (status == Task.STATUS_NOT_STARTED) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
	}
874164
public static synchronized void stop(){
        if(status.equals("stopped"))
            return;
        long t = System.currentTimeMillis();

        startupUpdator.stop();
        messageListener.stop();

        fileExchange.stop();
        queueWorker.stop();

        status = "stopped";
        LOG.info("Cluster node "+nodeId+" stopped ("+(System.currentTimeMillis()-t)+" ms.)");
    }
1044079
@CommandArgument
  public void cancel(int index) {
    if (jobProgressStates == null) {
      System.err.println("Server not running");
      return;
    }
    if (index <= 0 || index > jobProgressStates.size()) {
      System.err.println("Invalid job number");
    }
    ProgressState state = jobProgressStates.get(index - 1);
    state.setCancelPending();
  }
919584
private void scheduleFlushTask()
   {
      // cancel task
      if (flushTask != null)
      {
         flushTask.cancel();
      }
      // clear canceled tasks
      FLUSH_TIMER.purge();
      // new flush task, cause canceled can't be re-used
      flushTask = new TimerTask()
      {
         @Override
         public void run()
         {
            // check if volatile index should be flushed
            checkFlush();
         }
      };
      FLUSH_TIMER.schedule(flushTask, 0, 1000);
      lastFlushTime = System.currentTimeMillis();
      lastFileSystemFlushTime = System.currentTimeMillis();
   }
969199
def delete_running(self, timeout_last_refresh=0, dry_run=False):
        
        running_all = self.handle.jobs_running()
        running_timeout = [job for job in running_all
                           if coarse_utcnow() > job["refresh_time"] +
                           timedelta(seconds=timeout_last_refresh)]
        if len(running_timeout) == 0:
            # Nothing to stop
            self.refresh_tids(None)
            return None

        if dry_run:
            logger.warning("Dry run. Not removing anything.")

        logger.info("Removing {0}/{1} running jobs. # all jobs: {2} ".
                    format(len(running_timeout), len(running_all), len(self)))

        now = coarse_utcnow()
        logger.info("Current utc time: {0}".format(now))
        logger.info("Time horizont: {0}".format(now - timedelta(seconds=timeout_last_refresh)))
        for job in running_timeout:
            logger.info("Removing job: ")
            pjob = job.to_dict()
            del pjob["misc"]  # ignore misc when printing
            logger.info(pprint.pformat(pjob))
            if not dry_run:
                self.handle.delete(job)
                logger.info("Job deleted")
        self.refresh_tids(None)
669585
public boolean cancel(SipApplicationSessionTimerTask expirationTimerTask) {
		//CANCEL needs to remove the shceduled timer see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6602600
		//to improve perf		
		ScheduledFuture<MobicentsSipApplicationSession> future = ((DefaultSasTimerTask)expirationTimerTask).getScheduledFuture();
		if(future != null) {
			boolean removed = super.remove((Runnable) future);
			if(logger.isDebugEnabled()) {
				logger.debug("expiration timer on sip application session " + expirationTimerTask.getSipApplicationSession().getKey() + " removed : " + removed);
			}					
			boolean cancelled = future.cancel(true);
			if(logger.isDebugEnabled()) {
				logger.debug("expiration timer on sip application session " + expirationTimerTask.getSipApplicationSession().getKey() + " Cancelled : " + cancelled);
			}
			future = null;
			// Purge is expensive when called frequently, only call it every now and then.
	        // We do not sync the numCancelled variable. We dont care about correctness of
	        // the number, and we will still call purge rought once on every 25 cancels.
	        numCancelled++;
	        if(numCancelled % 100 == 0) {
	            super.purge();
	        }	
	        return cancelled;
		} else {
			if(logger.isDebugEnabled()) {
				logger.debug("expiration timer future is null, thus cannot be Cancelled");
			}
			return false;
		}
	}
594346
private void pruneExpiredTasks() {
        int numberExpiredTasksPruned = pruneHeadTasks(new Predicate<ReceiveQueueBuffer.ReceiveMessageBatchTask>() {
            @Override
            public boolean test(ReceiveMessageBatchTask t) {
                return t.isExpired() && t.getException() == null;
            }
        });
        // If we pruned any tasks because they are expired we also want to prune any empty tasks
        // afterwards so we have a chance to receive those expired messages again.
        if (numberExpiredTasksPruned > 0) {
            pruneHeadTasks(new Predicate<ReceiveQueueBuffer.ReceiveMessageBatchTask>() {
                @Override
                public boolean test(ReceiveMessageBatchTask t) {
                    return t.isEmpty() && t.getException() == null;
                }
            });
        }
    }
287467
public void cancel1xxTimer() {
		if (proxy1xxTimeoutTask != null && proxyBranch1xxTimerStarted) {
			proxy1xxTimeoutTask.cancel();
			proxy1xxTimeoutTask = null;
			proxyBranch1xxTimerStarted = false;
		}
	}
482235
public void processSync(T message) {
        // If this batcher has been shutdown, do not accept any more messages
        if (isShutDown) {
            return;
        }

        try {
            queueSizeTracer.record(queue.size());
        } catch (Throwable ignored) {
        }

        try {
            Stopwatch s = batchSyncPutTracer.start();
            queue.put(message);
            s.stop();
        } catch (InterruptedException e) {
            return;
        }
        numberAdded.incrementAndGet();
    }
990464
public void dropElementsBelowThreshold(double threshold) {
        Iterator<T> iterator = keySet().iterator();
        while (iterator.hasNext()) {
            T element  = iterator.next();
            double val = map.get(element).get();
            if (val < threshold) {
                iterator.remove();
                dirty.set(true);
            }
        }

    }
1127132
@Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        if (!isInitialized()) {
            return internalFuture.cancel(mayInterruptIfRunning);
        }
        return synchronisationFuture.cancel(mayInterruptIfRunning) && internalFuture.cancel(mayInterruptIfRunning);
    }
795233
@Override
    public void setSetWaitTimeInMessage(boolean setWaitTime)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "setSetWaitTimeInMessage", Boolean.valueOf(setWaitTime));
        _setWaitTimeInMessage = setWaitTime;
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "setSetWaitTimeInMessage");
    }
163269
public void cancelTimer() {
		synchronized (cTimerLock) {
			if (proxyTimeoutTask != null && proxyBranchTimerStarted) {
				proxyTimeoutTask.cancel();
				proxyTimeoutTask = null;
				proxyBranchTimerStarted = false;
			}
		}
	}
1039227
public void cancel(TimerTask task) {
        //CANCEL needs to remove the shceduled timer see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6602600
        //to improve perf

        ScheduledFuture<?> future = null;
        Object[] array = super.getQueue().toArray();
        for(int i = 0; i<array.length; i++) {
            if(array[i] instanceof ScheduledFuture<?>){
                future = (ScheduledFuture<?>)array[i];
                try {

                    Field callableField = future.getClass().getDeclaredField("callable");
                    callableField.setAccessible(true);
                    Object callable = callableField.get(future);
                    callableField.setAccessible(false);

                    if(callable!=null){
                        Field taskField = callable.getClass().getDeclaredField("task");
                        taskField.setAccessible(true);
                        TimerTask scheduledTask = null;
                        if(taskField.get(callable) instanceof TimerTask){
                             scheduledTask = (TimerTask) taskField.get(callable);
                        }
                        taskField.setAccessible(false);

                        if(scheduledTask!=null && scheduledTask.equals(task)){
                            break;
                        }
                    }
                } catch (Exception e) {
                    logger.warn("Couldn't clean the timer from the JVM GC ", e);
                }
            }
        }

        if(future != null) {
            boolean removed = super.remove((Runnable) future);
            if(logger.isDebugEnabled()) {
                logger.debug("expiration timer on sip proxy task" + task + " removed : " + removed);
            }
            boolean cancelled = future.cancel(true);
            if(logger.isDebugEnabled()) {
                logger.debug("expiration timer on sip proxy task" + task + " Cancelled : " + cancelled);
            }

            future = null;
            // Purge is expensive when called frequently, only call it every now and then.
            // We do not sync the numCancelled variable. We dont care about correctness of
            // the number, and we will still call purge rought once on every 25 cancels.
            numCancelled++;
            if(numCancelled % 100 == 0) {
                super.purge();
            }
        } else {
            if(logger.isDebugEnabled()) {
                logger.debug("expiration timer future is null, thus cannot be Cancelled");
            }
        }
    }