Java Code Examples for jenkins.model.ParameterizedJobMixIn

The following examples show how to use jenkins.model.ParameterizedJobMixIn. These examples are extracted from open source projects. 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 Project: github-integration-plugin   Source File: JobHelper.java    License: 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 Project: blueocean-plugin   Source File: Disabler.java    License: MIT License 5 votes vote down vote up
public static void makeDisabled(Object item, boolean b) throws IOException {
    if (item instanceof AbstractFolder) {
        Disabler.makeDisabled((AbstractFolder) item, b);
    }
    if (item instanceof AbstractProject) {
        Disabler.makeDisabled((AbstractProject) item, b);
    }
    if (item instanceof ParameterizedJobMixIn.ParameterizedJob ) {
        Disabler.makeDisabled((ParameterizedJobMixIn.ParameterizedJob ) item, b);
    }
}
 
Example 3
Source Project: blueocean-plugin   Source File: Disabler.java    License: MIT License 5 votes vote down vote up
@SuppressFBWarnings(value = "NP_BOOLEAN_RETURN_NULL", justification = "isDisabled will return null if the job type doesn't support it")
public static Boolean isDisabled(Object item) {
    if (item instanceof AbstractFolder) {
        return Disabler.isDisabled((AbstractFolder) item);
    }
    if (item instanceof AbstractProject) {
        return Disabler.isDisabled((AbstractProject) item);
    }
    if (item instanceof ParameterizedJobMixIn.ParameterizedJob ) {
        return Disabler.isDisabled((ParameterizedJobMixIn.ParameterizedJob ) item);
    }
    return null;
}
 
Example 4
Source Project: jenkins-test-harness   Source File: JenkinsRule.java    License: MIT License 5 votes vote down vote up
/**
 * Runs specified job and asserts that in finished with given build result.
 * @since TODO
 */
@Nonnull
public <J extends Job<J,R> & ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends Run<J,R> & Queue.Executable> R buildAndAssertStatus(@Nonnull Result status, @Nonnull J job) throws Exception {
    final QueueTaskFuture<R> f = new ParameterizedJobMixIn<J, R>() {
        @Override protected J asJob() {
            return job;
        }
    }.scheduleBuild2(0);
    return assertBuildStatus(status, f);
}
 
Example 5
Source Project: github-integration-plugin   Source File: JobRunnerForCauseTest.java    License: MIT License 5 votes vote down vote up
public static QueueTaskFuture schedule(Job<?, ?> job, int number, String param, int queuetPeriod) {
    ParameterizedJobMixIn jobMixIn = JobInfoHelpers.asParameterizedJobMixIn(job);
    GitHubPRCause cause = newGitHubPRCause().withNumber(number);
    ParametersAction parametersAction = new ParametersAction(
            Collections.<ParameterValue>singletonList(new StringParameterValue("value", param))
    );
    return jobMixIn.scheduleBuild2(queuetPeriod, new CauseAction(cause), parametersAction);
}
 
Example 6
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
@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
private void scheduleBuild(Job<?, ?> job, Action[] actions) {
    int projectBuildDelay = 0;
    if (job instanceof ParameterizedJobMixIn.ParameterizedJob) {
        ParameterizedJobMixIn.ParameterizedJob abstractProject = (ParameterizedJobMixIn.ParameterizedJob) job;
        if (abstractProject.getQuietPeriod() > projectBuildDelay) {
            projectBuildDelay = abstractProject.getQuietPeriod();
        }
    }
    retrieveScheduleJob(job).scheduleBuild2(projectBuildDelay, actions);
}
 
Example 9
private ParameterizedJobMixIn retrieveScheduleJob(final Job<?, ?> job) {
    // TODO 1.621+ use standard method
    return new ParameterizedJobMixIn() {
        @Override
        protected Job asJob() {
            return job;
        }
    };
}
 
Example 10
protected void scheduleBuild(Job<?, ?> job, Action[] actions) {
    int projectBuildDelay = 0;
    if (job instanceof ParameterizedJobMixIn.ParameterizedJob) {
        ParameterizedJobMixIn.ParameterizedJob abstractProject = (ParameterizedJobMixIn.ParameterizedJob) job;
        if (abstractProject.getQuietPeriod() > projectBuildDelay) {
            projectBuildDelay = abstractProject.getQuietPeriod();
        }
    }
    retrieveScheduleJob(job).scheduleBuild2(projectBuildDelay, actions);
}
 
Example 11
private ParameterizedJobMixIn retrieveScheduleJob(final Job<?, ?> job) {
    // TODO 1.621+ use standard method
    return new ParameterizedJobMixIn() {
        @Override
        protected Job asJob() {
            return job;
        }
    };
}
 
Example 12
@Override
public void isMatch() {
    if (getPayload().getObjectAttributes().getNoteableType()
        .equals(NoteEvent.NoteableType.MERGE_REQUEST)) {
        Integer mergeRequestId = getPayload().getMergeRequest().getIid();
        final Pattern mergeRequestJobNamePattern = Pattern
            .compile("^MR-" + mergeRequestId + "\\b.*$",
                Pattern.CASE_INSENSITIVE);
        final String commentBody = getPayload().getObjectAttributes().getNote();
        final String commentUrl = getPayload().getObjectAttributes().getUrl();
        try (ACLContext ctx = ACL.as(ACL.SYSTEM)) {
            boolean jobFound = false;
            for (final SCMSourceOwner owner : SCMSourceOwners.all()) {
                LOGGER.log(Level.FINEST, String.format("Source Owner: %s", owner.getFullDisplayName()));
                // This is a hack to skip owners which are children of a SCMNavigator
                if (owner.getFullDisplayName().contains(" » ")) {
                    continue;
                }
                for (SCMSource source : owner.getSCMSources()) {
                    if (!(source instanceof GitLabSCMSource)) {
                        continue;
                    }
                    GitLabSCMSource gitLabSCMSource = (GitLabSCMSource) source;
                    final GitLabSCMSourceContext sourceContext = new GitLabSCMSourceContext(
                        null, SCMHeadObserver.none())
                        .withTraits(gitLabSCMSource.getTraits());
                    if (!sourceContext.mrCommentTriggerEnabled()) {
                        continue;
                    }
                    if (gitLabSCMSource.getProjectId() == getPayload().getMergeRequest()
                        .getTargetProjectId() && isTrustedMember(gitLabSCMSource, sourceContext.onlyTrustedMembersCanTrigger())) {
                        for (Job<?, ?> job : owner.getAllJobs()) {
                            if (mergeRequestJobNamePattern.matcher(job.getName()).matches()) {
                                String expectedCommentBody = sourceContext.getCommentBody();
                                Pattern pattern = Pattern.compile(expectedCommentBody,
                                    Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
                                if (commentBody == null || pattern.matcher(commentBody)
                                    .matches()) {
                                    ParameterizedJobMixIn.scheduleBuild2(job, 0,
                                        new CauseAction(
                                            new GitLabMergeRequestCommentCause(commentUrl)));
                                    LOGGER.log(Level.INFO,
                                        "Triggered build for {0} due to MR comment on {1}",
                                        new Object[]{
                                            job.getFullName(),
                                            getPayload().getProject().getPathWithNamespace()
                                        }
                                    );
                                } else {
                                    LOGGER.log(Level.INFO,
                                        "MR comment does not match the trigger build string ({0}) for {1}",
                                        new Object[]{expectedCommentBody, job.getFullName()}
                                    );
                                }
                                break;
                            }
                            jobFound = true;
                        }
                    }
                }
            }
            if (!jobFound) {
                LOGGER.log(Level.INFO, "MR comment on {0} did not match any job",
                    new Object[]{
                        getPayload().getProject().getPathWithNamespace()
                    }
                );
            }
        }
    }
}
 
Example 13
/**
 * Handles updates of pull requests.
 * @param event only PULL_REQUEST events
 * @param payload payload of gh-event. Never blank
 */
@Override
protected void onEvent(GHEvent event, String payload) {
    JSONObject json = JSONObject.fromObject(payload);

    // Since we receive both pull request and issue comment events in this same code,
    //  we check first which one it is and set values from different fields
    JSONObject pullRequest = json.getJSONObject("pull_request");
    final String pullRequestUrl = pullRequest.getString("html_url");
    Integer pullRequestId = pullRequest.getInt("number");

    // Make sure the action is edited
    String action = json.getString("action");
    if (!ACTION_EDITED.equals(action)) {
        LOGGER.log(Level.FINER, "Pull request action is not edited ({0}) for PR {1}, ignoring",
                new Object[] { action, pullRequestUrl }
        );
        return;
    }

    // Set some values used below
    final Pattern pullRequestJobNamePattern = Pattern.compile("^PR-" + pullRequestId + "\\b.*$",
            Pattern.CASE_INSENSITIVE);

    // Make sure the repository URL is valid
    String repoUrl = json.getJSONObject("repository").getString("html_url");
    Matcher matcher = REPOSITORY_NAME_PATTERN.matcher(repoUrl);
    if (!matcher.matches()) {
        LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl);
        return;
    }
    final GitHubRepositoryName changedRepository = GitHubRepositoryName.create(repoUrl);
    if (changedRepository == null) {
        LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl);
        return;
    }

    LOGGER.log(Level.FINE, "Received update on PR {1} for {2}", new Object[] { pullRequestId, repoUrl });
    ACL.impersonate(ACL.SYSTEM, new Runnable() {
        @Override
        public void run() {
            boolean jobFound = false;
            for (final SCMSourceOwner owner : SCMSourceOwners.all()) {
                for (SCMSource source : owner.getSCMSources()) {
                    if (!(source instanceof GitHubSCMSource)) {
                        continue;
                    }
                    GitHubSCMSource gitHubSCMSource = (GitHubSCMSource) source;
                    if (gitHubSCMSource.getRepoOwner().equalsIgnoreCase(changedRepository.getUserName()) &&
                            gitHubSCMSource.getRepository().equalsIgnoreCase(changedRepository.getRepositoryName())) {
                        for (Job<?, ?> job : owner.getAllJobs()) {
                            if (pullRequestJobNamePattern.matcher(job.getName()).matches()) {
                                if (!(job.getParent() instanceof MultiBranchProject)) {
                                    continue;
                                }
                                boolean propFound = false;
                                for (BranchProperty prop : ((MultiBranchProject) job.getParent()).getProjectFactory().
                                        getBranch(job).getProperties()) {
                                    if (!(prop instanceof TriggerPRUpdateBranchProperty)) {
                                        continue;
                                    }
                                    propFound = true;
                                    ParameterizedJobMixIn.scheduleBuild2(job, 0,
                                            new CauseAction(new GitHubPullRequestUpdateCause(pullRequestUrl)));
                                    break;
                                }

                                if (!propFound) {
                                    LOGGER.log(Level.FINE,
                                            "Job {0} for {1}:{2}/{3} does not have a trigger PR update branch property",
                                            new Object[] {
                                                    job.getFullName(),
                                                    changedRepository.getHost(),
                                                    changedRepository.getUserName(),
                                                    changedRepository.getRepositoryName()
                                            }
                                    );
                                }

                                jobFound = true;
                            }
                        }
                    }
                }
            }
            if (!jobFound) {
                LOGGER.log(Level.FINE, "PR update on {0}:{1}/{2} did not match any job",
                        new Object[] {
                                changedRepository.getHost(), changedRepository.getUserName(),
                                changedRepository.getRepositoryName()
                        }
                );
            }
        }
    });
}
 
Example 14
/**
 * Handles updates of pull requests.
 * @param event only PULL_REQUEST_REVIEW events
 * @param payload payload of gh-event. Never blank
 */
@Override
protected void onEvent(GHEvent event, String payload) {
    JSONObject json = JSONObject.fromObject(payload);

    JSONObject pullRequest = json.getJSONObject("pull_request");
    final String pullRequestUrl = pullRequest.getString("html_url");
    Integer pullRequestId = pullRequest.getInt("number");

    // Set some values used below
    final Pattern pullRequestJobNamePattern = Pattern.compile("^PR-" + pullRequestId + "\\b.*$",
            Pattern.CASE_INSENSITIVE);

    // Make sure the repository URL is valid
    String repoUrl = json.getJSONObject("repository").getString("html_url");
    Matcher matcher = REPOSITORY_NAME_PATTERN.matcher(repoUrl);
    if (!matcher.matches()) {
        LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl);
        return;
    }
    final GitHubRepositoryName changedRepository = GitHubRepositoryName.create(repoUrl);
    if (changedRepository == null) {
        LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl);
        return;
    }

    LOGGER.log(Level.FINE, "Received review on PR {1} for {2}", new Object[] { pullRequestId, repoUrl });
    ACL.impersonate(ACL.SYSTEM, new Runnable() {
        @Override
        public void run() {
            boolean jobFound = false;
            for (final SCMSourceOwner owner : SCMSourceOwners.all()) {
                for (SCMSource source : owner.getSCMSources()) {
                    if (!(source instanceof GitHubSCMSource)) {
                        continue;
                    }
                    GitHubSCMSource gitHubSCMSource = (GitHubSCMSource) source;
                    if (gitHubSCMSource.getRepoOwner().equalsIgnoreCase(changedRepository.getUserName()) &&
                            gitHubSCMSource.getRepository().equalsIgnoreCase(changedRepository.getRepositoryName())) {
                        for (Job<?, ?> job : owner.getAllJobs()) {
                            if (pullRequestJobNamePattern.matcher(job.getName()).matches()) {
                                if (!(job.getParent() instanceof MultiBranchProject)) {
                                    continue;
                                }
                                boolean propFound = false;
                                for (BranchProperty prop : ((MultiBranchProject) job.getParent()).getProjectFactory().
                                        getBranch(job).getProperties()) {
                                    if (!(prop instanceof TriggerPRReviewBranchProperty)) {
                                        continue;
                                    }
                                    propFound = true;
                                    ParameterizedJobMixIn.scheduleBuild2(job, 0,
                                            new CauseAction(new GitHubPullRequestReviewCause(pullRequestUrl)));
                                    break;
                                }

                                if (!propFound) {
                                    LOGGER.log(Level.FINE,
                                            "Job {0} for {1}:{2}/{3} does not have a trigger PR review branch property",
                                            new Object[] {
                                                    job.getFullName(),
                                                    changedRepository.getHost(),
                                                    changedRepository.getUserName(),
                                                    changedRepository.getRepositoryName()
                                            }
                                    );
                                }

                                jobFound = true;
                            }
                        }
                    }
                }
            }
            if (!jobFound) {
                LOGGER.log(Level.FINE, "PR review on {0}:{1}/{2} did not match any job",
                        new Object[] {
                                changedRepository.getHost(), changedRepository.getUserName(),
                                changedRepository.getRepositoryName()
                        }
                );
            }
        }
    });
}
 
Example 15
Source Project: blueocean-plugin   Source File: Disabler.java    License: MIT License 4 votes vote down vote up
public static void makeDisabled(ParameterizedJobMixIn.ParameterizedJob job, boolean b) throws IOException {
    job.makeDisabled(b);
}
 
Example 16
Source Project: blueocean-plugin   Source File: Disabler.java    License: MIT License 4 votes vote down vote up
public static Boolean isDisabled(ParameterizedJobMixIn.ParameterizedJob job) {
    return job.isDisabled();
}
 
Example 17
Source Project: gogs-webhook-plugin   Source File: GogsTrigger.java    License: MIT License 4 votes vote down vote up
@Override
public boolean isApplicable(Item item) {
    return item instanceof Job && SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item) != null
            && item instanceof ParameterizedJobMixIn.ParameterizedJob;
}
 
Example 18
Source Project: gogs-webhook-plugin   Source File: GogsPayloadProcessor.java    License: 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 19
Source Project: jenkins-test-harness   Source File: JenkinsRule.java    License: MIT License 4 votes vote down vote up
@Nonnull
public <J extends Job<J,R> & ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends Run<J,R> & Queue.Executable> R buildAndAssertSuccess(@Nonnull J job) throws Exception {
    return buildAndAssertStatus(Result.SUCCESS, job);
}
 
Example 20
@Override
public boolean isApplicable(Item item) {
    return item instanceof Job && nonNull(SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item))
            && item instanceof ParameterizedJobMixIn.ParameterizedJob;
}
 
Example 21
@Override
public boolean isApplicable(Item item) {
    return item instanceof Job
            && SCMTriggerItems.asSCMTriggerItem(item) != null
            && item instanceof ParameterizedJobMixIn.ParameterizedJob;
}