/* (non-Javadoc)
@see de.chandre.admintool.quartz.AdminToolQuartzService#changeTrigger(de.chandre.admintool.quartz.JobTriggerTO, boolean)
181313
@Override
	public boolean changeTrigger(JobTriggerTO triggerTO, boolean add) throws SchedulerException {
		if (!config.isChangeTriggerAllowed()) {
			LOGGER.warn("not allowed to change any trigger");
			return false;
		}
		JobDetail detail = findJob(triggerTO.getOriginalJobGroup(), triggerTO.getOriginalJobName());
		if (null == detail) {
			return false;
		}
		Trigger trigger = findTrigger(triggerTO.getOriginalJobGroup(), triggerTO.getOriginalJobName(), 
				triggerTO.getOriginalTriggerGroup(), triggerTO.getOriginalTriggerName());
		if(null == trigger) {
			if (add) {
				this.scheduler.scheduleJob(buildTrigger(detail, null, triggerTO));
				return true;
			}
			return false;
		}
		this.scheduler.rescheduleJob(trigger.getKey(), buildTrigger(detail, trigger, triggerTO));
		return true;
	}
524931
public void setTriggerEvents(java.util.Collection<String> triggerEvents) {
        if (triggerEvents == null) {
            this.triggerEvents = null;
            return;
        }

        this.triggerEvents = new com.amazonaws.internal.SdkInternalList<String>(triggerEvents);
    }
362848
public String getTrigger() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "getTrigger returning " + trigger);
        return this.trigger;
    }
362402
public function doTriggeredJobComplete(Trigger $trigger, JobDetail $jobDetail, $triggerInstCode)
    {
        if ($triggerInstCode === CompletedExecutionInstruction::DELETE_TRIGGER) {
            // remove trigger
            $this->doRemoveTrigger($trigger->getKey());
        } elseif ($triggerInstCode === CompletedExecutionInstruction::SET_TRIGGER_COMPLETE) {
            $this->res->getTriggerStorage()->getCollection()->updateOne([
                'name' => $trigger->getKey()->getName(),
                'group' => $trigger->getKey()->getGroup(),
            ], [
                '$set' => [
                    'state' => Trigger::STATE_COMPLETE,
                    'errorMessage' => $trigger->getErrorMessage(),
                ]
            ]);
        } elseif ($triggerInstCode === CompletedExecutionInstruction::SET_TRIGGER_ERROR) {
            $this->res->getTriggerStorage()->getCollection()->updateOne([
                'name' => $trigger->getKey()->getName(),
                'group' => $trigger->getKey()->getGroup(),
            ], [
                '$set' => [
                    'state' => Trigger::STATE_ERROR,
                    'errorMessage' => $trigger->getErrorMessage(),
                ]
            ]);
        } elseif ($triggerInstCode === CompletedExecutionInstruction::SET_ALL_JOB_TRIGGERS_COMPLETE) {
            $this->res->getTriggerStorage()->getCollection()->updateMany([
                'jobName' => $trigger->getJobKey()->getName(),
                'jobGroup' => $trigger->getJobKey()->getGroup(),
            ], [
                '$set' => [
                    'state' => Trigger::STATE_COMPLETE,
                    'errorMessage' => $trigger->getErrorMessage(),
                ]
            ]);
        } elseif ($triggerInstCode === CompletedExecutionInstruction::SET_ALL_JOB_TRIGGERS_ERROR) {
            $this->res->getTriggerStorage()->getCollection()->updateMany([
                'jobName' => $trigger->getJobKey()->getName(),
                'jobGroup' => $trigger->getJobKey()->getGroup(),
            ], [
                '$set' => [
                    'state' => Trigger::STATE_ERROR,
                    'errorMessage' => $trigger->getErrorMessage(),
                ]
            ]);
        }

        // remove fired triggers
        // TODO: update fired trigger but not remove
        $result = $this->res->getFiredTriggerStorage()->getCollection()->deleteOne([
            'fireInstanceId' => $trigger->getFireInstanceId(),
        ]);

        if (false == $result->isAcknowledged() || false == $result->getDeletedCount()) {
            throw new JobPersistenceException(sprintf('Couldn\'t delete fired trigger: fireInstanceId "%s"', $trigger->getFireInstanceId()));
        }
    }
294213
@Override
  public void releaseAcquiredTrigger(OperableTrigger trigger) {

    synchronized (lock) {
      TriggerWrapper tw = wrappedTriggersByKey.get(trigger.getName());
      if (tw != null && tw.state == TriggerWrapper.STATE_ACQUIRED) {
        tw.state = TriggerWrapper.STATE_WAITING;
        timeWrappedTriggers.add(tw);
      }
    }
  }
1297686
protected void fireTriggerEvent(TriggerEvent event) {
        try {
            for (TriggerListener listener : listeners) {
                listener.triggerValidation(event);
            }
        } catch (RuntimeException e) {
            uncheckedExceptionHandler.handleException(e);
        } catch (Error e) {
            uncheckedExceptionHandler.handleError(e);
        }
    }
23030
public void startTrigger(final FlowTrigger flowTrigger, final String flowId,
      final int flowVersion, final String submitUser, final Project project) {
    final TriggerInstance triggerInst = createTriggerInstance(flowTrigger, flowId, flowVersion,
        submitUser, project);
    this.flowTriggerExecutorService.submit(() -> {
      logger.info("Starting the flow trigger [trigger instance id: {}] by {}",
          triggerInst.getId(), submitUser);
      start(triggerInst);
    });
  }
1039079
public void changeState(String jobName) throws MangooSchedulerException {
        Objects.requireNonNull(this.quartzScheduler, Required.SCHEDULER.toString());
        
        try {
            for (JobKey jobKey : getAllJobKeys()) {
                if (jobKey.getName().equalsIgnoreCase(jobName)) {
                    TriggerState triggerState = getTriggerState(jobKey);
                    if (TriggerState.NORMAL == triggerState) {
                        this.quartzScheduler.pauseJob(jobKey);                        
                    } else {
                        this.quartzScheduler.resumeJob(jobKey);
                    }
                }
            }            
        } catch (SchedulerException | MangooSchedulerException e) {
            throw new MangooSchedulerException(e);
        }
    }
786853
@Override
	public void interruptTrigger(String jobGroup, String jobName, final String triggerGroup, final String triggerName) throws SchedulerException {
		if (!config.isInterruptTriggerAllowed()) {
			LOGGER.warn("not allowed to interrupt any trigger");
			return;
		}
		JobKey jobKey = new JobKey(jobName, jobGroup);
		if (isInteruptable(jobKey)) {
			List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
			JobDetail jobDetail = scheduler.getJobDetail(jobKey);
			Trigger triggerFound = findTrigger(jobGroup, jobName, triggerGroup, triggerName);
			for (JobExecutionContext jobExecutionContext : executingJobs) {
				if (jobExecutionContext.getJobDetail().getKey().equals(jobDetail.getKey()) 
						&& jobExecutionContext.getTrigger().getKey().equals(triggerFound.getKey())) {
					if (LOGGER.isDebugEnabled())
						LOGGER.debug(String.format("interrupting jobTrigger (%s, %s, %s)", jobDetail.getKey().getGroup(),
								jobDetail.getKey().getName(), triggerFound.getKey().getName()));
					((InterruptableJob) jobExecutionContext.getJobInstance()).interrupt();
				}
			}
		}
	}
991612
public final void setCommitTrigger(CommitTrigger commitTrigger) {
        if (this.commitTrigger == commitTrigger) {
            return;
        }
        if (this.commitTrigger != null) {
            this.commitTrigger.removeCommitTriggerListener(commitTriggerHandler);
            this.commitTrigger = null;
        }
        if (commitTrigger != null) {
            if (this.commitTriggerHandler == null) {
                this.commitTriggerHandler = new CommitTriggerHandler();
            }
            this.commitTrigger = commitTrigger;
            this.commitTrigger.addCommitTriggerListener(commitTriggerHandler);
        }
    }
822890
public ICommonsList <? extends ITrigger> getTriggersOfJob (final JobKey jobKey) throws SchedulerException
  {
    validateState ();

    return m_aResources.getJobStore ().getTriggersForJob (jobKey);
  }
654292
@Inject(optional = true)
    public void addTriggerListeners(Set<TriggerListener> triggerListeners) throws SchedulerException {
        for (TriggerListener triggerListener : triggerListeners) {
            scheduler.getListenerManager().addTriggerListener(triggerListener);
        }
    }
298808
@Override
  public synchronized void addTrigger(final Trigger t) throws TriggerLoaderException {
    logger.info("Inserting trigger " + t.toString() + " into db.");

    final SQLTransaction<Long> insertAndGetLastID = transOperator -> {
      transOperator.update(ADD_TRIGGER, DateTime.now().getMillis());
      // This commit must be called in order to unlock trigger table and have last insert ID.
      transOperator.getConnection().commit();
      return transOperator.getLastInsertId();
    };

    try {
      final long id = this.dbOperator.transaction(insertAndGetLastID);
      t.setTriggerId((int) id);
      updateTrigger(t);
      logger.info("uploaded trigger " + t.getDescription());
    } catch (final SQLException ex) {
      logger.error("Adding Trigger " + t.getTriggerId() + " failed.");
      throw new TriggerLoaderException("trigger id is not properly created.", ex);
    }
  }
1056516
private void changeStateTo(int newState) {
    int oldState = this.status.getRunState();
    if (oldState == newState) {
      return; //old and new states are same
    }
    this.status.setRunState(newState);

    //update the metrics
    if (oldState == JobStatus.PREP) {
      this.jobtracker.getInstrumentation().decPrepJob(conf, jobId);
    } else if (oldState == JobStatus.RUNNING) {
      this.jobtracker.getInstrumentation().decRunningJob(conf, jobId);
    }

    if (newState == JobStatus.PREP) {
      this.jobtracker.getInstrumentation().addPrepJob(conf, jobId);
    } else if (newState == JobStatus.RUNNING) {
      this.jobtracker.getInstrumentation().addRunningJob(conf, jobId);
    }

  }
127368
@Override
	public void executionStateChanged(final ExecutionState newExecutionState, final String optionalMessage) {

		// Check the state transition
		ExecutionStateTransition.checkTransition(false, getTaskName(), this.executionState, newExecutionState);

		// Make sure the reason for a transition to FAILED appears in the log files
		if (newExecutionState == ExecutionState.FAILED) {
			LOG.error(optionalMessage);
		}

		// Notify all listener objects
		final Iterator<ExecutionListener> it = this.registeredListeners.iterator();
		while (it.hasNext()) {
			it.next().executionStateChanged(this.environment.getJobID(), this.vertexID, newExecutionState,
					optionalMessage);
		}

		// Store the new execution state
		this.executionState = newExecutionState;

		// Finally propagate the state change to the job manager
		this.taskManager.executionStateChanged(this.environment.getJobID(), this.vertexID, newExecutionState,
				optionalMessage);
	}
534663
@Override
  public List<Trigger> getTriggersForJob(String jobKey) {

    ArrayList<Trigger> trigList = new ArrayList<Trigger>();

    synchronized (lock) {
      for (int i = 0; i < wrappedTriggers.size(); i++) {
        TriggerWrapper tw = wrappedTriggers.get(i);
        if (tw.jobKey.equals(jobKey)) {
          trigList.add((OperableTrigger) tw.trigger.clone());
        }
      }
    }

    return trigList;
  }
536424
@Override
    public boolean onTrigger() {
        List<Event<T>> windowEvents = null;
        List<T> expired = null;
        try {
            lock.lock();
            /*
             * scan the entire window to handle out of order events in
             * the case of time based windows.
             */
            windowEvents = scanEvents(true);
            expired = new ArrayList<>(expiredEvents);
            expiredEvents.clear();
        } finally {
            lock.unlock();
        }
        List<T> events = new ArrayList<>();
        List<T> newEvents = new ArrayList<>();
        for (Event<T> event : windowEvents) {
            events.add(event.get());
            if (!prevWindowEvents.contains(event)) {
                newEvents.add(event.get());
            }
        }
        prevWindowEvents.clear();
        if (!events.isEmpty()) {
            prevWindowEvents.addAll(windowEvents);
            LOG.debug("invoking windowLifecycleListener onActivation, [{}] events in window.", events.size());
            windowLifecycleListener.onActivation(events, newEvents, expired);
        } else {
            LOG.debug("No events in the window, skipping onActivation");
        }
        triggerPolicy.reset();
        return !events.isEmpty();
    }