/*
Does NOT throw an exception if a step-level listener is annotated with

@JobListener, even if that is the only type of listener annotation found.
330260
private synchronized List<ListenerInfo> getStepListenerInfo(Step step, InjectionReferences injectionRefs) {
        if (!stepLevelListenerInfo.containsKey(step.getId())) {
            List<ListenerInfo> stepListenerInfoList = new ArrayList<ListenerInfo>();
            stepLevelListenerInfo.put(step.getId(), stepListenerInfoList);

            Listeners stepLevelListeners = step.getListeners();
            if (stepLevelListeners != null) {
                for (Listener listener : stepLevelListeners.getListenerList()) {
                    ListenerInfo info = buildListenerInfo(listener, injectionRefs);
                    stepListenerInfoList.add(info);
                }
            }

            return stepListenerInfoList;
        } else {
            return stepLevelListenerInfo.get(step.getId());
        }
    }
1304565
protected boolean trigger(List<InteractionListener> listeners, Type type, Throwable e) {
        if (listeners.isEmpty())
            return false;
        InteractionEvent event = createInteractionEvent(type, e);
        for (InteractionListener listener : listeners) {
            listener.onEvent(event);
        }
        if (event instanceof AfterFailInteractionEvent)
            return ((AfterFailInteractionEvent) event).isRetry();
        return false;
    }
932413
public boolean addOnPageSelectedListener(OnPageSelectedListener listener) {
        final boolean added;
        synchronized (mListeners) {
            added = mListeners.add(listener);
        }
        if (added) {
            listener.onPageSelected(mCurrentPage);
        }
        return added;
    }
367417
@Override
    public void processListener(FacesListener listener) {
        UIComponent c = getComponent();
        UIComponent cFromStack;
        boolean didPush = false;
        FacesContext context = FacesContext.getCurrentInstance();
        cFromStack = UIComponent.getCurrentComponent(context);
        if (null == cFromStack) {
            didPush = true;
            c.pushComponentToEL(context, null);
        }
        try {
            if (listener instanceof SystemEventListener) {
                super.processListener(listener);
            } else if (listener instanceof ComponentSystemEventListener) {
                ((ComponentSystemEventListener)listener).processEvent(this);
            }
        } finally {
            if (didPush) {
                c.popComponentFromEL(context);
            }
        }
    }
825071
private void executeGlobalListeners(CallbackType callbackType, Object entity) {
    if (globalCallbacks == null) {
      return;
    }
    List<CallbackMetadata> callbacks = globalCallbacks.get(callbackType);
    if (callbacks == null) {
      return;
    }
    for (CallbackMetadata callback : callbacks) {
      Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass());
      invokeCallbackMethod(callback.getCallbackMethod(), listener, entity);
    }
  }
784688
protected void jobFinished(Throwable error)
    {
        this.lock.lock();

        try {
            if (this.status instanceof AbstractJobStatus) {
                // Store error
                ((AbstractJobStatus) this.status).setError(error);
            }

            // Give a chance to any listener to do custom action associated to the job
            this.observationManager.notify(new JobFinishingEvent(getRequest().getId(), getType(), this.request), this,
                error);

            if (getRequest().isVerbose()) {
                if (getStatus().getRequest().getId() != null) {
                    this.logger.info(LOG_END_ID, "Finished job of type [{}] with identifier [{}]", getType(),
                        getStatus().getRequest().getId());
                } else {
                    this.logger.info(LOG_END, "Finished job of type [{}]", getType());
                }
            }

            if (this.status instanceof AbstractJobStatus) {
                // Indicate when the job ended
                ((AbstractJobStatus) this.status).setEndDate(new Date());

                // Stop updating job status (progress, log, etc.)
                ((AbstractJobStatus) this.status).stopListening();

                // Update job state
                ((AbstractJobStatus) this.status).setState(JobStatus.State.FINISHED);
            }

            // Release threads waiting for job being done
            this.finishedCondition.signalAll();

            // Remove the job from the current jobs context
            this.jobContext.popCurrentJob();

            // Store the job status
            try {
                if (this.request.getId() != null) {
                    this.store.storeAsync(this.status);
                }
            } catch (Throwable t) {
                this.logger.warn(LOG_STATUS_STORE_FAILED, "Failed to store job status [{}]", this.status, t);
            }
        } finally {
            this.lock.unlock();

            // Notify listener that job is fully finished
            this.observationManager.notify(new JobFinishedEvent(getRequest().getId(), getType(), this.request), this,
                error);
        }
    }
130312
function callListeners(listeners) {
        var current_event_idx = -1;

        // Make sure we have some data to pass to the listeners
        event_data = event_data || undefined;

        // If no bound listeners for this event, leave now
        if (listeners.length === 0) {
            emitComplete();
            return;
        }


        // Call the next listener in our array
        function nextListener() {
            var listener, event_obj;

            // We want the next listener
            current_event_idx++;

            // If we've ran out of listeners end this emit call
            if (!listeners[current_event_idx]) {
                emitComplete();
                return;
            }

            // Object the listener ammends to tell us what it's going to do
            event_obj = {
                // If changed to true, expect this listener is going to callback
                wait: false,

                // If wait is true, this callback must be called to continue running listeners
                callback: function () {
                    // Invalidate this callback incase a listener decides to call it again
                    event_obj.callback = undefined;

                    nextListener.apply(that);
                },

                // Prevents the default 'done' functions from executing
                preventDefault: function () {
                    prevented = true;
                }
            };


            listener = listeners[current_event_idx];
            listener[1].call(listener[2] || that, event_obj, event_data);

            // If the listener hasn't signalled it's going to wait, proceed to next listener
            if (!event_obj.wait) {
                // Invalidate the callback just incase a listener decides to call it anyway
                event_obj.callback = undefined;

                nextListener();
            }
        }

        nextListener();
    }
1043153
public Listeners<JobXMLDescriptor> getOrCreateListeners()
   {
      Node node = model.getOrCreate("listeners");
      Listeners<JobXMLDescriptor> listeners = new ListenersImpl<JobXMLDescriptor>(this, "listeners", model, node);
      return listeners;
   }
272053
public void addListener(IsSimplePromiseResponseHandler<T> listener) {
    if (handlers == null) {
      handlers = new LinkedList<>();
    }

    handlers.add(listener);

    if (response != null || exception != null) {
      listener.onResponse(this);
    }
  }
186255
public static StepExecutionItem createJobRef(
            final String jobIdentifier,
            final String[] args,
            final boolean nodeStep,
            final StepExecutionItem handler,
            final boolean keepgoingOnSuccess,
            final String label
    )
    {
        return createJobRef(
                jobIdentifier,
                args,
                nodeStep,
                handler,
                keepgoingOnSuccess,
                null,
                null,
                null,
                null,
                null,
                label,
                false,
                null,
                false,
                false,
                null,
                false
        );
    }
1261698
public void registerListenersOnEverything(final Object object) {
        try {
            // the removeListener() call ensures that the listener is not added more than once
            new PropertyVisitor(object) {
                @Override
                protected boolean visitSingleValueProperty(final Property<?> fieldValue) {
                    fieldValue.removeListener(propertyListener);
                    fieldValue.addListener(propertyListener);
                    return true;
                }

                @Override
                protected boolean visitCollectionProperty(final ListProperty<?> fieldValue) {
                    fieldValue.removeListener(listListener);
                    fieldValue.addListener(listListener);
                    return true;
                }

                @Override
                protected boolean visitCollectionProperty(final MapProperty<?, ?> fieldValue) {
                    fieldValue.removeListener(mapListener);
                    fieldValue.addListener(mapListener);
                    return true;
                }

                @Override
                protected boolean visitCollectionProperty(final SetProperty<?> fieldValue) {
                    fieldValue.removeListener(setListener);
                    fieldValue.addListener(setListener);
                    return false;
                }
            };
        } catch (final IllegalAccessException e) {
            topology.onError(new SynchronizeFXException(e));
        } catch (final SecurityException e) {
            topology.onError(new SynchronizeFXException(
                    "Maybe you're JVM doesn't allow reflection for this application?", e));
        }
    }
174149
private boolean tryLockJob(Properties properties) {
    try {
      if (Boolean.valueOf(properties.getProperty(ConfigurationKeys.JOB_LOCK_ENABLED_KEY, Boolean.TRUE.toString()))) {
        this.jobLockOptional = Optional.of(getJobLock(properties, new JobLockEventListener() {
          @Override
          public void onLost() {
            executeCancellation();
          }
        }));
      }
      return !this.jobLockOptional.isPresent() || this.jobLockOptional.get().tryLock();
    } catch (JobLockException ioe) {
      LOG.error(String.format("Failed to acquire job lock for job %s: %s", this.jobContext.getJobId(), ioe), ioe);
      return false;
    }
  }
1157411
public void checkForUpdate(UpdateCheckListener updateCheckListener) {
        listeners.add(updateCheckListener);
        if (scheduler != null) {
            scheduler.schedule(new UpdateCheckTask(this, versionServiceUrl, productName), 0, SECONDS);
        } else {
            // the scheduler won't be provided if the service isn't actually running,
            // but management may still ask for a check on update
            new UpdateCheckTask(this, versionServiceUrl, productName).run();
        }
    }
989438
private void validateSingleTableInput(final SourceColumnFinder sourceColumnFinder,
            final Collection<? extends ComponentJob> componentJobs) {
        for (final ComponentJob componentJob : componentJobs) {
            if (!componentJob.getDescriptor().isMultiStreamComponent()) {
                Table originatingTable = null;
                final InputColumn<?>[] input = componentJob.getInput();

                for (final InputColumn<?> inputColumn : input) {
                    final Table table = sourceColumnFinder.findOriginatingTable(inputColumn);
                    if (table != null) {
                        if (originatingTable == null) {
                            originatingTable = table;
                        } else {
                            if (!originatingTable.equals(table)) {
                                throw new IllegalArgumentException(
                                        "Input columns in " + componentJob + " originate from different tables");
                            }
                        }
                    }
                }
            }

            final OutputDataStreamJob[] outputDataStreamJobs = componentJob.getOutputDataStreamJobs();
            for (final OutputDataStreamJob outputDataStreamJob : outputDataStreamJobs) {
                validateSingleTableInput(outputDataStreamJob.getJob());
            }
        }

    }
1113638
@Override
	public boolean isStateful(JobKey jobKey) throws SchedulerException {
		Class<?> jobClazz = scheduler.getJobDetail(jobKey).getJobClass();
		DisallowConcurrentExecution annotation1 = jobClazz.getAnnotation(DisallowConcurrentExecution.class);
		PersistJobDataAfterExecution annotation2 = jobClazz.getAnnotation(PersistJobDataAfterExecution.class);
		return StatefulJob.class.isAssignableFrom(jobClazz) || null != annotation1 || null != annotation2;
	}
198801
public static boolean execute(AbstractBuild build, BuildListener listener) {
        PrintStream logger = listener.getLogger();
        // Check all downstream Project of the project, not just those defined by BuildTrigger
        // TODO this may not yet be up to date if rebuildDependencyGraphAsync has been used; need a method to wait for the last call made before now to finish
        final DependencyGraph graph = Jenkins.getInstance().getDependencyGraph();
        List<Dependency> downstreamProjects = new ArrayList<>(
                graph.getDownstreamDependencies(build.getProject()));
        // Sort topologically
        downstreamProjects.sort(new Comparator<Dependency>() {
            public int compare(Dependency lhs, Dependency rhs) {
                // Swapping lhs/rhs to get reverse sort:
                return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
            }
        });

        for (Dependency dep : downstreamProjects) {
            List<Action> buildActions = new ArrayList<>();
            if (dep.shouldTriggerBuild(build, listener, buildActions)) {
                AbstractProject p = dep.getDownstreamProject();
                // Allow shouldTriggerBuild to return false first, in case it is skipping because of a lack of Item.READ/DISCOVER permission:
                if (p.isDisabled()) {
                    logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(p)));
                    continue;
                }
                boolean scheduled = p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run)build), buildActions.toArray(new Action[0]));
                if (Jenkins.getInstance().getItemByFullName(p.getFullName()) == p) {
                    String name = ModelHyperlinkNote.encodeTo(p);
                    if (scheduled) {
                        logger.println(Messages.BuildTrigger_Triggering(name));
                    } else {
                        logger.println(Messages.BuildTrigger_InQueue(name));
                    }
                } // otherwise upstream users should not know that it happened
            }
        }

        return true;
    }
46730
public boolean start(final FileDownloadListener listener, final boolean isSerial) {
        if (listener == null) {
            Util.w(TAG, "Tasks with the listener can't start, because the listener "
                    + "provided is null: [null, " + isSerial + "]");
            return false;
        }

        List<DownloadTaskAdapter> originalTasks =
                FileDownloadList.getImpl().assembleTasksToStart(listener);
        if (originalTasks.isEmpty()) {
            Util.w(TAG, "no task for listener: " + listener + " to start");
            return false;
        }

        ArrayList<DownloadTask> downloadTasks = new ArrayList<>();
        for (DownloadTaskAdapter task : originalTasks) {
            downloadTasks.add(task.getDownloadTask());
        }
        final DownloadContext downloadContext =
                new DownloadContext.Builder(new DownloadContext.QueueSet(), downloadTasks)
                        .setListener(new DownloadContextListener() {
                            @Override
                            public void taskEnd(@NonNull DownloadContext context,
                                                @NonNull DownloadTask task,
                                                @NonNull EndCause cause,
                                                @Nullable Exception realCause,
                                                int remainCount) {
                                Util.d(TAG, "task " + task.getId() + "end");
                                final DownloadTaskAdapter downloadTaskAdapter =
                                        FileDownloadUtils.findDownloadTaskAdapter(task);
                                if (downloadTaskAdapter != null) {
                                    FileDownloadList.getImpl().remove(downloadTaskAdapter);
                                }
                            }

                            @Override
                            public void queueEnd(@NonNull DownloadContext context) {
                                Util.d(TAG, "queue end");
                            }
                        })
                        .build();

        final CompatListenerAdapter compatListenerAdapter = CompatListenerAdapter.create(listener);
        downloadContext.start(compatListenerAdapter, isSerial);
        return true;
    }