hudson.triggers.Trigger Java Examples

The following examples show how to use hudson.triggers.Trigger. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JobHelper.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * support matrix plugin.
 *
 * @see JobInfoHelpers#triggerFrom(hudson.model.Job, java.lang.Class)
 */
@CheckForNull
public static <T extends Trigger> T triggerFrom(final Job<?, ?> job, Class<T> tClass) {
    Job<?, ?> guessJob;
    if (job instanceof MatrixConfiguration) {
        guessJob = ((MatrixConfiguration) job).getParent();
    } else {
        guessJob = job;
    }

    if (guessJob instanceof AbstractProject<?, ?>) {
        final AbstractProject<?, ?> abstractProject = (AbstractProject<?, ?>) guessJob;
        return abstractProject.getTrigger(tClass);
    } else if (guessJob instanceof ParameterizedJobMixIn.ParameterizedJob) {
        ParameterizedJobMixIn.ParameterizedJob pJob = (ParameterizedJobMixIn.ParameterizedJob) guessJob;

        for (Object candidate : pJob.getTriggers().values()) {
            if (tClass.isInstance(candidate)) {
                return tClass.cast(candidate);
            }
        }
    }
    return null;
}
 
Example #2
Source File: Cron.java    From parameterized-scheduler with MIT License 6 votes vote down vote up
private void checkTriggers(Calendar calendar) {
	Jenkins instance = Jenkins.getInstance();

	for (AbstractProject<?, ?> project : instance.getAllItems(AbstractProject.class)) {
		for (Trigger<?> trigger : project.getTriggers().values()) {
			if (trigger instanceof ParameterizedTimerTrigger) {
				LOGGER.fine("cron checking " + project.getName());
				ParameterizedTimerTrigger ptTrigger = (ParameterizedTimerTrigger) trigger;

				try {
					ptTrigger.checkCronTabsAndRun(calendar);
				} catch (Throwable e) {
					// t.run() is a plugin, and some of them throw RuntimeException and other things.
					// don't let that cancel the polling activity. report and move on.
					LOGGER.log(Level.WARNING,
							trigger.getClass().getName() + ".run() failed for " + project.getName(), e);
				}
			}
		}
	}
}
 
Example #3
Source File: TemplateUtils.java    From ez-templates with Apache License 2.0 6 votes vote down vote up
private static void fixBuildTriggers(AbstractProject implementationProject, Map<TriggerDescriptor, Trigger> oldTriggers) {
    List<Trigger<?>> triggersToReplace = ProjectUtils.getTriggers(implementationProject);
    if (triggersToReplace == null) {
        throw new NullPointerException("triggersToReplace");
    }

    if (!triggersToReplace.isEmpty() || !oldTriggers.isEmpty()) {
        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (triggersToReplace) {
            triggersToReplace.clear();
            for (Trigger trigger : oldTriggers.values()) {
                triggersToReplace.add(trigger);
            }
        }
    }
}
 
Example #4
Source File: SQSTrigger.java    From aws-codecommit-trigger-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public Trigger newInstance(StaplerRequest req, @Nonnull JSONObject jsonObject) throws FormException {
    if (jsonObject.has("subscribeInternalScm")) {
        jsonObject.put("subscribeInternalScm", Boolean.TRUE);
    }
    return super.newInstance(req, jsonObject);
}
 
Example #5
Source File: TemplateStaplerRequestWrapper.java    From multi-branch-project-plugin with MIT License 5 votes vote down vote up
/**
 * Overrides certain parameter names with certain values needed when setting the configuration for
 * template projects.  Otherwise, relies on the standard implementation.
 * <br>
 * {@inheritDoc}
 */
@Override
public String getParameter(String name) {
    // Sanitize the following parameters
    if ("name".equals(name)) {
        // Don't set the name
        return null;
    } else if ("description".equals(name)) {
        // Don't set the description
        return null;
    } else if ("disable".equals(name)) {
        // Mark disabled
        return "";
    }

    /*
     * Parameters for conflicting triggers should return null if the
     * corresponding JSON was not provided.  Otherwise, NPEs occur when
     * trying to update the triggers for the template project.
     */
    DescriptorExtensionList<Trigger<?>, TriggerDescriptor> triggerDescriptors = Trigger.all();
    for (TriggerDescriptor triggerDescriptor : triggerDescriptors) {
        String safeName = triggerDescriptor.getJsonSafeClassName();

        try {
            if (name.equals(safeName) && getSubmittedForm().getJSONObject(safeName).isNullObject()) {
                return null;
            }
        } catch (ServletException e) {
            throw new IllegalStateException("Exception getting data from submitted JSON", e);
        }
    }

    // Fallback to standard functionality
    return super.getParameter(name);
}
 
Example #6
Source File: GitLabPushTrigger.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public static GitLabPushTrigger getFromJob(Job<?, ?> job) {
    GitLabPushTrigger trigger = null;
    if (job instanceof ParameterizedJobMixIn.ParameterizedJob) {
        ParameterizedJobMixIn.ParameterizedJob p = (ParameterizedJobMixIn.ParameterizedJob) job;
        Collection<Trigger> triggerList = p.getTriggers().values();
        for (Trigger t : triggerList) {
            if (t instanceof GitLabPushTrigger) {
                trigger = (GitLabPushTrigger) t;
            }
        }
    }
    return trigger;
}
 
Example #7
Source File: OpenMergeRequestPushHookTriggerHandler.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(Job<?, ?> job, PushHook hook, boolean ciSkip, BranchFilter branchFilter, MergeRequestLabelFilter mergeRequestLabelFilter) {
	try {
        if (job instanceof ParameterizedJobMixIn.ParameterizedJob) {
            ParameterizedJob project = (ParameterizedJobMixIn.ParameterizedJob) job;
            GitLabConnectionProperty property = job.getProperty(GitLabConnectionProperty.class);
            Collection<Trigger> triggerList = project.getTriggers().values();
            for (Trigger t : triggerList) {
            	if (t instanceof GitLabPushTrigger) {
            		final GitLabPushTrigger trigger = (GitLabPushTrigger) t;
                    Integer projectId = hook.getProjectId();
                    if (property != null && property.getClient() != null && projectId != null && trigger != null) {
                        GitLabClient client = property.getClient();
                        for (MergeRequest mergeRequest : getOpenMergeRequests(client, projectId.toString())) {
                            if (mergeRequestLabelFilter.isMergeRequestAllowed(mergeRequest.getLabels())) {
                            	handleMergeRequest(job, hook, ciSkip, branchFilter, client, mergeRequest);
                            }
                        }
                    }
            	}
            }

        } else {
        	LOGGER.log(Level.FINE, "Not a ParameterizedJob: {0}",LoggerUtil.toArray(job.getClass().getName()));
        }
    } catch (WebApplicationException | ProcessingException e) {
        LOGGER.log(Level.WARNING, "Failed to communicate with gitlab server to determine if this is an update for a merge request: " + e.getMessage(), e);
    }
}
 
Example #8
Source File: GogsPayloadProcessor.java    From gogs-webhook-plugin with MIT License 4 votes vote down vote up
public GogsResults triggerJobs(String jobName, String deliveryID) {
    SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);
    GogsResults result = new GogsResults();

    try {
        BuildableItem project = GogsUtils.find(jobName, BuildableItem.class);
        if (project != null) {
            GogsTrigger gTrigger = null;
            Cause cause = new GogsCause(deliveryID);

            if (project instanceof ParameterizedJobMixIn.ParameterizedJob) {
                ParameterizedJobMixIn.ParameterizedJob pJob = (ParameterizedJobMixIn.ParameterizedJob) project;
                for (Trigger trigger : pJob.getTriggers().values()) {
                    if (trigger instanceof GogsTrigger) {
                        gTrigger = (GogsTrigger) trigger;
                        break;
                    }
                }
            }

            if (gTrigger != null) {
                SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(project);
                GogsPayload gogsPayload = new GogsPayload(this.payload);
                if (item != null) {
                    item.scheduleBuild2(0, gogsPayload);
                }
            } else {
                project.scheduleBuild(0, cause);
            }
            result.setMessage(String.format("Job '%s' is executed", jobName));
        } else {
            String msg = String.format("Job '%s' is not defined in Jenkins", jobName);
            result.setStatus(404, msg);
            LOGGER.warning(msg);
        }
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        LOGGER.severe(sw.toString());
    } finally {
        SecurityContextHolder.setContext(saveCtx);
    }

    return result;
}
 
Example #9
Source File: GitHubPRTrigger.java    From github-integration-plugin with MIT License 4 votes vote down vote up
public static DescriptorImpl get() {
    return Trigger.all().get(DescriptorImpl.class);
}
 
Example #10
Source File: Functions.java    From github-integration-plugin with MIT License 4 votes vote down vote up
public static <ITEM extends Item> Predicate<ITEM> withTrigger(final Class<? extends Trigger> clazz) {
    return item -> triggerFrom(item, clazz) != null;
}
 
Example #11
Source File: GitHubBranchTrigger.java    From github-integration-plugin with MIT License 4 votes vote down vote up
public static DescriptorImpl get() {
    return Trigger.all().get(DescriptorImpl.class);
}
 
Example #12
Source File: GitHubPRJobDslExtensionTest.java    From github-integration-plugin with MIT License 4 votes vote down vote up
@Test
public void shouldCreateJobWithExtendedDsl() throws Exception {
    FreeStyleProject job = jenkins.createFreeStyleProject();
    job.getBuildersList().add(
            new ExecuteDslScripts(
                    new ExecuteDslScripts.ScriptLocation(
                            null, null,
                            IOUtils.toString(this
                                    .getClass().getClassLoader().getResourceAsStream(JOB_DSL_GROOVY))
                    ),
                    false,
                    RemovedJobAction.DELETE,
                    RemovedViewAction.DELETE,
                    LookupStrategy.JENKINS_ROOT
            )
    );

    jenkins.buildAndAssertSuccess(job);

    assertThat(jenkins.getInstance().getJobNames(), hasItem(is(JOB_NAME_IN_DSL_SCRIPT)));

    FreeStyleProject generated = jenkins.getInstance()
            .getItemByFullName(JOB_NAME_IN_DSL_SCRIPT, FreeStyleProject.class);


    Collection<Trigger<?>> triggers = generated.getTriggers().values();
    assertThat("Should add trigger", triggers, hasSize(1));
    GitHubBranchTrigger trigger = (GitHubBranchTrigger) triggers.toArray()[0];
    assertThat("Should add trigger of GHPR class", trigger, instanceOf(GitHubBranchTrigger.class));
    assertThat("Should have pre status", trigger.isPreStatus(), equalTo(true));
    assertThat("Should have cancel queued", trigger.isCancelQueued(), equalTo(true));
    assertThat("Should add events", trigger.getEvents(), hasSize(5));
    assertThat("Should set mode", trigger.getTriggerMode(), equalTo(HEAVY_HOOKS_CRON));

    /*
     * note: this are explicity placed in the first and second positions so it's easier to
     * pluck them back out for explicit testing
     */
    verifyBranchFilter(trigger.getEvents().get(0));
    verifyCommitChecks(trigger.getEvents().get(1));

    final List<GitHubRepoProvider> repoProviders = trigger.getRepoProviders();
    assertThat("Should contain repoProvider", repoProviders, notNullValue());
    assertThat("Should contain 1 repoProvider", repoProviders, hasSize(1));

    final GitHubRepoProvider repoProvider = repoProviders.get(0);
    assertThat(repoProvider, instanceOf(GitHubPluginRepoProvider.class));
    final GitHubPluginRepoProvider provider = (GitHubPluginRepoProvider) repoProvider;
    assertThat(provider.isCacheConnection(), is(false));
    assertThat(provider.isManageHooks(), is(false));
    assertThat(provider.getRepoPermission(), is(PULL));

}
 
Example #13
Source File: DslIntegrationTest.java    From github-integration-plugin with MIT License 4 votes vote down vote up
@Test
public void shouldCreateJobWithExtendedDsl() throws Exception {
    FreeStyleProject job = jenkins.createFreeStyleProject();
    job.getBuildersList().add(
            new ExecuteDslScripts(
                    new ExecuteDslScripts.ScriptLocation(
                            null, null,
                            IOUtils.toString(this
                                    .getClass().getClassLoader().getResourceAsStream(JOB_DSL_GROOVY))
                    ),
                    false,
                    RemovedJobAction.DELETE,
                    RemovedViewAction.DELETE,
                    LookupStrategy.JENKINS_ROOT
            )
    );

    jenkins.buildAndAssertSuccess(job);

    assertThat(jenkins.getInstance().getJobNames(), hasItem(is(JOB_NAME_IN_DSL_SCRIPT)));

    FreeStyleProject generated = jenkins.getInstance()
            .getItemByFullName(JOB_NAME_IN_DSL_SCRIPT, FreeStyleProject.class);

    final DescribableList<Builder, Descriptor<Builder>> builders = generated.getBuildersList();

    assertThat("Should have builder", builders, hasSize(1));
    assertThat("Should add status builder", builders.get(0), instanceOf(GitHubPRStatusBuilder.class));
    assertThat("Should add message",
            ((GitHubPRStatusBuilder) builders.get(0)).getStatusMessage().getContent(),
            equalTo(JOB_DSL_BUILDER_TEXT_CONTENT));

    verifyPublishers(generated.getPublishersList());

    Collection<Trigger<?>> triggers = generated.getTriggers().values();
    assertThat("Should add trigger", triggers, hasSize(1));
    GitHubPRTrigger trigger = (GitHubPRTrigger) triggers.toArray()[0];
    assertThat("Should add trigger of GHPR class", trigger, instanceOf(GitHubPRTrigger.class));
    assertThat("Should have pre status", trigger.isPreStatus(), equalTo(true));
    assertThat("Should have cancel queued", trigger.isCancelQueued(), equalTo(true));
    assertThat("Should set mode", trigger.getTriggerMode(), equalTo(HEAVY_HOOKS_CRON));

    final List<GitHubRepoProvider> repoProviders = trigger.getRepoProviders();
    assertThat("Should contain repoProvider", repoProviders, notNullValue());
    assertThat("Should contain 1 repoProvider", repoProviders, hasSize(1));

    final GitHubRepoProvider repoProvider = repoProviders.get(0);
    assertThat(repoProvider, instanceOf(GitHubPluginRepoProvider.class));
    final GitHubPluginRepoProvider provider = (GitHubPluginRepoProvider) repoProvider;
    assertThat(provider.isCacheConnection(), is(false));
    assertThat(provider.isManageHooks(), is(false));
    assertThat(provider.getRepoPermission(), is(PUSH));

    final List<GitHubPREvent> events = trigger.getEvents();
    assertThat("Should add events", events, hasSize(17));


    GitHubPREvent event = events.get(15);
    assertThat(event, instanceOf(GitHubPRNumber.class));
    assertThat(((GitHubPRNumber) event).isSkip(), is(false));
    assertThat(((GitHubPRNumber) event).isMatch(), is(true));


    event = events.get(16);
    assertThat(event, instanceOf(GitHubPRNumber.class));
    assertThat(((GitHubPRNumber) event).isSkip(), is(true));
    assertThat(((GitHubPRNumber) event).isMatch(), is(true));
}
 
Example #14
Source File: TemplateUtils.java    From ez-templates with Apache License 2.0 4 votes vote down vote up
public static void handleTemplateImplementationSaved(AbstractProject implementationProject, TemplateImplementationProperty property) throws IOException {
	
    if (property.getTemplateJobName().equals("null")) {
        LOG.warning(String.format("Implementation [%s] was saved. No template selected.", implementationProject.getFullDisplayName()));
        return;
    }
	
    LOG.info(String.format("Implementation [%s] was saved. Syncing with [%s].", implementationProject.getFullDisplayName(), property.getTemplateJobName()));
    
    AbstractProject templateProject = property.findTemplate();        
    if (templateProject == null) {
    	
    	// If the template can't be found, then it's probably a bug
        throw new IllegalStateException(String.format("Cannot find template [%s] used by job [%s]", property.getTemplateJobName(), implementationProject.getFullDisplayName()));
    }

    //Capture values we want to keep
    @SuppressWarnings("unchecked")
    boolean implementationIsTemplate = implementationProject.getProperty(TemplateProperty.class) != null;
    List<ParameterDefinition> oldImplementationParameters = findParameters(implementationProject);
    @SuppressWarnings("unchecked")
    Map<TriggerDescriptor, Trigger> oldTriggers = implementationProject.getTriggers();
    boolean shouldBeDisabled = implementationProject.isDisabled();
    String description = implementationProject.getDescription();
    String displayName = implementationProject.getDisplayNameOrNull();
    AuthorizationMatrixProperty oldAuthMatrixProperty = (AuthorizationMatrixProperty) implementationProject.getProperty(AuthorizationMatrixProperty.class);
    SCM oldScm = (SCM) implementationProject.getScm();
    JobProperty oldOwnership = implementationProject.getProperty("com.synopsys.arc.jenkins.plugins.ownership.jobs.JobOwnerJobProperty");
    Label oldLabel = implementationProject.getAssignedLabel();

    AxisList oldAxisList = null;
    if (implementationProject instanceof MatrixProject && !property.getSyncMatrixAxis()) {
        MatrixProject matrixProject = (MatrixProject) implementationProject;
        oldAxisList = matrixProject.getAxes();
    }

    implementationProject = synchronizeConfigFiles(implementationProject, templateProject);

    // Reverse all the fields that we've marked as "Don't Sync" so that they appear that they haven't changed.

    //Set values that we wanted to keep via reflection to prevent infinite save recursion
    fixProperties(implementationProject, property, implementationIsTemplate);
    fixParameters(implementationProject, oldImplementationParameters);

    ReflectionUtils.setFieldValue(AbstractItem.class, implementationProject, "displayName", displayName);

    if (!property.getSyncBuildTriggers()) {
        fixBuildTriggers(implementationProject, oldTriggers);
    }

    if (!property.getSyncDisabled()) {
        ReflectionUtils.setFieldValue(AbstractProject.class, implementationProject, "disabled", shouldBeDisabled);
    }

    if (oldAxisList != null && implementationProject instanceof MatrixProject && !property.getSyncMatrixAxis()) {
        fixAxisList((MatrixProject) implementationProject, oldAxisList);
    }

    if (!property.getSyncDescription() && description != null) {
        ReflectionUtils.setFieldValue(AbstractItem.class, implementationProject, "description", description);
    }

    if (!property.getSyncSecurity() && oldAuthMatrixProperty != null) {
        implementationProject.removeProperty(AuthorizationMatrixProperty.class);
        implementationProject.addProperty(oldAuthMatrixProperty);
    }

    if (!property.getSyncScm() && oldScm != null) {
        implementationProject.setScm(oldScm);
    }

    if (!property.getSyncOwnership() && oldOwnership != null) {
        implementationProject.removeProperty(oldOwnership.getClass());
        implementationProject.addProperty(oldOwnership);
    }

    if (!property.getSyncAssignedLabel()) {
        implementationProject.setAssignedLabel(oldLabel);
    }

    if (Jenkins.getInstance().getPlugin("promoted-builds") != null) {
        PromotedBuildsTemplateUtils.addPromotions(implementationProject, templateProject);
    } 

    ProjectUtils.silentSave(implementationProject);
}