类hudson.model.Job源码实例Demo

下面列出了怎么用hudson.model.Job的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: gitlab-plugin   文件: ActionResolver.java
private Item resolveProject(final String projectName, final Iterator<String> restOfPathParts) {
    return ACLUtil.impersonate(ACL.SYSTEM, new ACLUtil.Function<Item>() {
        public Item invoke() {
            final Jenkins jenkins = Jenkins.getInstance();
            if (jenkins != null) {
                Item item = jenkins.getItemByFullName(projectName);
                while (item instanceof ItemGroup<?> && !(item instanceof Job<?, ?> || item instanceof SCMSourceOwner) && restOfPathParts.hasNext()) {
                    item = jenkins.getItem(restOfPathParts.next(), (ItemGroup<?>) item);
                }
                if (item instanceof Job<?, ?> || item instanceof SCMSourceOwner) {
                    return item;
                }
            }
            LOGGER.log(Level.FINE, "No project found: {0}, {1}", toArray(projectName, Joiner.on('/').join(restOfPathParts)));
            return null;
        }
    });
}
 
@Test
public void resolverShouldCorrectlyMerge() {
    final DescribableList firstFolderProperties = mock(DescribableList.class);
    when(firstFolderProperties.get(FolderVaultConfiguration.class))
        .thenReturn(completeTestConfigFolder("firstParent", null));

    final DescribableList secondFolderProperties = mock(DescribableList.class);
    when(secondFolderProperties.get(FolderVaultConfiguration.class))
        .thenReturn(completeTestConfigFolder("secondParent", 2));

    final AbstractFolder secondParent = generateMockFolder(secondFolderProperties, null);

    final AbstractFolder firstParent = generateMockFolder(firstFolderProperties, secondParent);

    final Job job = generateMockJob(firstParent);

    VaultConfiguration result = new FolderVaultConfiguration.ForJob().forJob(job);

    VaultConfiguration expected = completeTestConfig("firstParent", null)
        .mergeWithParent(completeTestConfig("secondParent", 2));

    assertThat(result.getVaultCredentialId(), is(expected.getVaultCredentialId()));
    assertThat(result.getVaultUrl(), is(expected.getVaultUrl()));
    assertThat(result.getEngineVersion(), is(expected.getEngineVersion()));
}
 
源代码3 项目: gitlab-plugin   文件: PendingBuildsHandler.java
public void cancelPendingBuilds(Job<?, ?> job, Integer projectId, String branch) {
    Queue queue = Jenkins.getInstance().getQueue();
    for (Queue.Item item : queue.getItems()) {
        if (!job.getName().equals(item.task.getName())) {
            continue;
        }
        GitLabWebHookCause queueItemGitLabWebHookCause = getGitLabWebHookCauseData(item);
        if (queueItemGitLabWebHookCause == null) {
            continue;
        }
        CauseData queueItemCauseData = queueItemGitLabWebHookCause.getData();
        if (!projectId.equals(queueItemCauseData.getSourceProjectId())) {
            continue;
        }
        if (branch.equals(queueItemCauseData.getBranch())) {
            cancel(item, queue, branch);
            setCommitStatusCancelledIfNecessary(queueItemCauseData, job);
        }
    }
}
 
源代码4 项目: pipeline-maven-plugin   文件: MavenReport.java
public synchronized SortedMap<MavenArtifact, Collection<Job>> getDownstreamJobsByArtifact() {
    Map<MavenArtifact, SortedSet<String>> downstreamJobsByArtifact = GlobalPipelineMavenConfig.get().getDao().listDownstreamJobsByArtifact(run.getParent().getFullName(), run.getNumber());
    TreeMap<MavenArtifact, Collection<Job>> result = new TreeMap<>();

    for(Map.Entry<MavenArtifact, SortedSet<String>> entry: downstreamJobsByArtifact.entrySet()) {
        MavenArtifact mavenArtifact = entry.getKey();
        SortedSet<String> downstreamJobFullNames = entry.getValue();
        result.put(mavenArtifact, downstreamJobFullNames.stream().map(jobFullName -> {
            if (jobFullName == null) {
                return null;
            }
            // security / authorization is checked by Jenkins#getItemByFullName
            try {
                return Jenkins.getInstance().getItemByFullName(jobFullName, Job.class);
            } catch (AccessDeniedException e) {
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList()));
    }

    return result;
}
 
源代码5 项目: blueocean-plugin   文件: GithubIssue.java
@Override
public Collection<BlueIssue> getIssues(ChangeLogSet.Entry changeSetEntry) {
    Job job = changeSetEntry.getParent().getRun().getParent();
    if (!(job.getParent() instanceof MultiBranchProject)) {
        return null;
    }
    MultiBranchProject mbp = (MultiBranchProject)job.getParent();
    List<SCMSource> scmSources = (List<SCMSource>) mbp.getSCMSources();
    SCMSource source = scmSources.isEmpty() ? null : scmSources.get(0);
    if (!(source instanceof GitHubSCMSource)) {
        return null;
    }
    GitHubSCMSource gitHubSource = (GitHubSCMSource)source;
    String apiUri =  gitHubSource.getApiUri();
    final String repositoryUri = new HttpsRepositoryUriResolver().getRepositoryUri(apiUri, gitHubSource.getRepoOwner(), gitHubSource.getRepository());
    Collection<BlueIssue> results = new ArrayList<>();
    for (String input : findIssueKeys(changeSetEntry.getMsg())) {
        String uri = repositoryUri.substring(0, repositoryUri.length() - 4);
        results.add(new GithubIssue("#" + input, String.format("%s/issues/%s", uri, input)));
    }
    return results;
}
 
源代码6 项目: blueocean-plugin   文件: RunSearch.java
public static Iterable<BlueRun> findRuns(Job job, final Link parent){
    final List<BlueRun> runs = new ArrayList<>();
    Iterable<Job> pipelines;
    if(job != null){
        pipelines = ImmutableList.of(job);
    }else{
        pipelines = Jenkins.getInstance().getItems(Job.class);
    }
    for (Job p : pipelines) {
        RunList<? extends Run> runList = p.getBuilds();

        for (Run r : runList) {
            BlueRun run = BlueRunFactory.getRun(r, () -> parent);
            if (run != null) {
                runs.add(run);
            }
        }
    }

    return runs;
}
 
源代码7 项目: github-integration-plugin   文件: JobHelper.java
/**
 * @see jenkins.model.ParameterizedJobMixIn#getDefaultParametersValues()
 */
public static List<ParameterValue> getDefaultParametersValues(Job<?, ?> job) {
    ParametersDefinitionProperty paramDefProp = job.getProperty(ParametersDefinitionProperty.class);
    List<ParameterValue> defValues = new ArrayList<>();

    /*
     * This check is made ONLY if someone will call this method even if isParametrized() is false.
     */
    if (isNull(paramDefProp)) {
        return defValues;
    }

    /* Scan for all parameter with an associated default values */
    for (ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) {
        ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();

        if (defaultValue != null) {
            defValues.add(defaultValue);
        }
    }

    return defValues;
}
 
@Test
public void dontFailOnBadJob() throws IOException, ANTLRException {
    String goodRepo = "https://github.com/KostyaSha-auto/test-repo";

    final FreeStyleProject job1 = jRule.createProject(FreeStyleProject.class, "bad job");
    job1.addProperty(new GithubProjectProperty("http://bad.url/deep/bad/path/"));
    job1.addTrigger(new GitHubBranchTrigger("", GitHubPRTriggerMode.HEAVY_HOOKS_CRON, emptyList()));

    Set<Job> jobs = getBranchTriggerJobs(goodRepo);
    assertThat(jobs, hasSize(0));

    final FreeStyleProject job2 = jRule.createProject(FreeStyleProject.class, "good job");
    job2.addProperty(new GithubProjectProperty(goodRepo));
    job2.addTrigger(new GitHubBranchTrigger("", GitHubPRTriggerMode.HEAVY_HOOKS_CRON, emptyList()));

    jobs = getBranchTriggerJobs("KostyaSha-auto/test-repo");
    assertThat(jobs, hasSize(1));
    assertThat(jobs, hasItems(job2));
}
 
源代码9 项目: blueocean-plugin   文件: GithubIssueTest.java
@Test
public void changeSetJobParentNotMultibranch() throws Exception {
    AbstractFolder project = mock(AbstractFolder.class);
    Job job = mock(MockJob.class);
    Run run = mock(Run.class);
    ChangeLogSet logSet = mock(ChangeLogSet.class);
    ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class);

    when(project.getProperties()).thenReturn(new DescribableList(project));
    when(entry.getParent()).thenReturn(logSet);
    when(logSet.getRun()).thenReturn(run);
    when(run.getParent()).thenReturn(job);
    when(job.getParent()).thenReturn(project);

    when(entry.getMsg()).thenReturn("Closed #123 #124");

    Collection<BlueIssue> resolved = BlueIssueFactory.resolve(entry);
    Assert.assertEquals(0, resolved.size());
}
 
public static ConduitCredentials getCredentials(Job owner, String credentialsID) {
    List<ConduitCredentials> available = availableCredentials(owner);
    if (available.size() == 0) {
        return null;
    }
    CredentialsMatcher matcher;
    if (credentialsID != null) {
        matcher = CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsID));
    } else {
        matcher = CredentialsMatchers.always();
    }
    return CredentialsMatchers.firstOrDefault(
            available,
            matcher,
            available.get(0)
    );
}
 
源代码11 项目: office-365-connector-plugin   文件: AbstractTest.java
protected Job mockJob(String jobName, String parentJobName) {
    Job job = mock(Job.class);
    ItemGroup itemGroup = mock(ItemGroup.class);
    when(itemGroup.getFullDisplayName()).thenReturn(parentJobName);
    when(job.getParent()).thenReturn(itemGroup);
    when(job.getFullDisplayName()).thenReturn(jobName);

    return job;
}
 
源代码12 项目: gitlab-plugin   文件: ProjectBranchesProvider.java
public AutoCompletionCandidates doAutoCompleteBranchesSpec(Job<?, ?> job, String query) {
    AutoCompletionCandidates result = new AutoCompletionCandidates();
    // show all suggestions for short strings
    if (query.length() < 2) {
        result.add(getProjectBranchesAsArray(job));
    } else {
        for (String branch : getProjectBranchesAsArray(job)) {
            if (branch.toLowerCase().contains(query.toLowerCase())) {
                result.add(branch);
            }
        }
    }
    return result;
}
 
源代码13 项目: DotCi   文件: MyBuildsView.java
@Override
public Collection<TopLevelItem> getItems() {
    final List<TopLevelItem> items = new LinkedList<>();
    for (final TopLevelItem item : getOwnerItemGroup().getItems()) {
        if (item.hasPermission(Job.CONFIGURE)) {
            items.add(item);
        }
    }
    return Collections.unmodifiableList(items);
}
 
源代码14 项目: blueocean-plugin   文件: BranchImpl.java
@Override
public BluePipeline getPipeline(Item item, Reachable parent, BlueOrganization organization) {
    if (item instanceof WorkflowJob && item.getParent() instanceof MultiBranchProject) {
        return new BranchImpl(organization, (Job) item, parent.getLink());
    }
    return null;
}
 
@Test
public void testCloudBeesFolder() throws Exception {
    Folder folder = createFolder(FOLDERNAME);

    FreeStyleProject project = folder.createProject(FreeStyleProject.class, PROJECTNAME);

    Job job = GogsUtils.find(FOLDERNAME + "/" + PROJECTNAME, Job.class);
    assertEquals("Couldn't find " + FOLDERNAME + "/" + PROJECTNAME, job, project);
}
 
private String getConduitToken(Job owner, Logger logger) {
    ConduitCredentials credentials = getConduitCredentials(owner);
    if (credentials != null) {
        return credentials.getToken().getPlainText();
    }
    logger.warn("credentials", "No credentials configured.");
    return null;
}
 
/**
 * Returns true if the previous job has an AWS Device Farm result with valid tests it should display.
 *
 * @param job The job to test.
 * @return Whether or the not the job should be displayed.
 */
public boolean shouldDisplay(Job job) {
    AWSDeviceFarmTestResult result = getPreviousResult(job);
    if (result == null || result.getTotalCount() <= 0) {
        return false;
    }
    return true;
}
 
/**
 * Calculates the color of the status ball for the owner based on selected descendants.
 * <br>
 * Logic kanged from Branch API (original author Stephen Connolly).
 *
 * @return the color of the status ball for the owner.
 */
@Nonnull
private BallColor calculateBallColor() {
    if (owner instanceof TemplateDrivenMultiBranchProject
            && ((TemplateDrivenMultiBranchProject) owner).isDisabled()) {
        return BallColor.DISABLED;
    }

    BallColor c = BallColor.DISABLED;
    boolean animated = false;

    StringTokenizer tokens = new StringTokenizer(Util.fixNull(jobs), ",");
    while (tokens.hasMoreTokens()) {
        String jobName = tokens.nextToken().trim();
        TopLevelItem item = owner.getItem(jobName);
        if (item != null && item instanceof Job) {
            BallColor d = ((Job) item).getIconColor();
            animated |= d.isAnimated();
            d = d.noAnime();
            if (d.compareTo(c) < 0) {
                c = d;
            }
        }
    }

    if (animated) {
        c = c.anime();
    }

    return c;
}
 
源代码19 项目: warnings-ng-plugin   文件: IssuesTablePortlet.java
PortletTableModel(final List<Job<?, ?>> visibleJobs, final Function<ResultAction, String> namePrinter,
        final Predicate<ResultAction> filter) {
    SortedMap<String, String> toolNamesById = mapToolIdsToNames(visibleJobs, namePrinter, filter);

    toolNames = toolNamesById.values();
    rows = new ArrayList<>();

    populateRows(visibleJobs, toolNamesById);
}
 
源代码20 项目: rocket-chat-notifier   文件: ViewTracker.java
private Result getResult(View view) {
	Result ret = Result.SUCCESS;
	for (TopLevelItem item : view.getAllItems()) {
		for (Job<?,?> job : item.getAllJobs()) {
			Run<?, ?> build = job.getLastCompletedBuild();
			if(build != null) {
				Result result = build.getResult();
				if(result.isBetterOrEqualTo(Result.FAILURE)) 
					ret = ret.combine(result);
			}
		}
	}
	return ret;
}
 
public SQSActivityAction(Job job) {
    this.job = job;
    this.activityDir = new File(this.job.getRootDir(), ".activity");
    if (!this.activityDir.exists() && !this.activityDir.mkdirs()) {
        log.error("Unable to create trigger activity dir %s", this.activityDir.getPath());
    }

    log.debug("Activity dir %s is writeable? %s", this.activityDir.getPath(), this.activityDir.canWrite());
}
 
源代码22 项目: warnings-ng-plugin   文件: IssuesTotalColumnTest.java
@Test
void shouldShowNoResultIfNoAction() {
    IssuesTotalColumn column = createColumn();
    column.setSelectTools(false);

    Job<?, ?> job = createJobWithActions();

    assertThat(column.getTotal(job)).isEmpty();
    assertThat(column.getUrl(job)).isEmpty();
    assertThat(column.getDetails(job)).isEmpty();
    assertThat(column.getTools()).isEmpty();
    assertThat(column.getSelectTools()).isFalse();
    assertThat(column.getName()).isEqualTo(NAME);
}
 
源代码23 项目: gitlab-plugin   文件: ProjectBranchesProvider.java
/**
 * Get the URL of the first declared repository in the project configuration.
 * Use this as default source repository url.
 *
 * @return URIish the default value of the source repository url
 * @throws IllegalStateException Project does not use git scm.
 */
private URIish getSourceRepoURLDefault(Job<?, ?> job) {
    SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job);
    GitSCM gitSCM = getGitSCM(item);
    if (gitSCM == null) {
        LOGGER.log(Level.WARNING, "Could not find GitSCM for project. Project = {1}, next build = {2}",
                array(job.getName(), String.valueOf(job.getNextBuildNumber())));
        throw new IllegalStateException("This project does not use git:" + job.getName());
    }
    return getFirstRepoURL(gitSCM.getRepositories());
}
 
源代码24 项目: warnings-ng-plugin   文件: IssuesTotalColumnTest.java
@Test
void shouldShowTotalOfSelectedTool() {
    IssuesTotalColumn column = createColumn();
    column.setSelectTools(true);
    column.setTools(Collections.singletonList(createTool(CHECK_STYLE_ID)));

    Job<?, ?> job = createJobWithActions(
            createAction(CHECK_STYLE_ID, CHECK_STYLE_NAME, 1),
            createAction(SPOT_BUGS_ID, SPOT_BUGS_NAME, 2));

    assertThat(column.getTotal(job)).isNotEmpty();
    assertThat(column.getTotal(job)).hasValue(1);
    assertThat(column.getUrl(job)).isEqualTo("0/" + CHECK_STYLE_ID);

    column.setTools(Collections.singletonList(createTool(SPOT_BUGS_ID)));

    assertThat(column.getTotal(job)).isNotEmpty();
    assertThat(column.getTotal(job)).hasValue(2);
    assertThat(column.getUrl(job)).isEqualTo("0/" + SPOT_BUGS_ID);

    column.setTools(Collections.singletonList(createTool("unknown")));

    assertThat(column.getTotal(job)).isEmpty();
    assertThat(column.getUrl(job)).isEmpty();

    column.setTools(Collections.emptyList());

    assertThat(column.getTotal(job)).isEmpty();
    assertThat(column.getUrl(job)).isEmpty();
}
 
public boolean isDownstreamVisibleByUpstreamBuildAuth(@Nonnull Item downstreamPipeline) {
    boolean result = getItemByFullName(downstreamPipeline.getFullName(), Job.class) != null;
    LOGGER.log(Level.FINE, "isDownstreamVisibleByUpstreamBuildAuth({0}, auth: {1}): {2}",
            new Object[]{downstreamPipeline, Jenkins.getAuthentication(), result});

    return result;
}
 
源代码26 项目: gitlab-plugin   文件: BuildWebHookAction.java
public void run() {
    GitLabPushTrigger trigger = GitLabPushTrigger.getFromJob((Job<?, ?>) project);
    if (trigger != null) {
        if (StringUtils.isEmpty(trigger.getSecretToken())) {
            checkPermission(Item.BUILD, project);
        } else if (!StringUtils.equals(trigger.getSecretToken(), secretToken)) {
            throw HttpResponses.errorWithoutStack(401, "Invalid token");
        }
        performOnPost(trigger);
    }
}
 
@Test
void shouldShowTableWithOneJob() {
    Job<?, ?> job = createJob(CHECK_STYLE_ID, CHECK_STYLE_NAME, 1);

    PortletTableModel model = createModel(list(job));

    verifySingleTool(job, model, CHECK_STYLE_ID, CHECK_STYLE_NAME, 1);
}
 
/**
 * Returns the most recent AWS Device Farm test result from the previous build.
 *
 * @param job The job which generated an AWS Device Farm test result
 * @return The previous Device Farm build result.
 */
public static AWSDeviceFarmTestResult previousAWSDeviceFarmBuildResult(Job job) {
    Run prev = job.getLastCompletedBuild();
    if (prev == null) {
        return null;
    }
    AWSDeviceFarmTestResultAction action = prev.getAction(AWSDeviceFarmTestResultAction.class);
    if (action == null) {
        return null;
    }
    return action.getResult();
}
 
private void verifySpotBugsAndCheckStyle(final Job job, final PortletTableModel model) {
    assertThat(model.getToolNames()).containsExactly(CHECK_STYLE_NAME, SPOT_BUGS_NAME);

    List<TableRow> rows = model.getRows();
    assertThat(rows).hasSize(1);

    TableRow actualRow = rows.get(0);
    assertThat(actualRow.getJob()).isSameAs(job);

    List<Result> results = actualRow.getResults();
    assertThat(results).hasSize(2);

    verifyResult(results.get(0), CHECK_STYLE_ID, 2);
    verifyResult(results.get(1), SPOT_BUGS_ID, 1);
}
 
@Test
void shouldShowTableWithTwoSelectedTools() {
    Job<?, ?> job = createJobWithActions(
            createAction(SPOT_BUGS_ID, SPOT_BUGS_NAME, 1),
            createAction(CHECK_STYLE_ID, CHECK_STYLE_NAME, 2));

    IssuesTablePortlet portlet = createPortlet();
    portlet.setSelectTools(true);
    portlet.setTools(list(createTool(SPOT_BUGS_ID), createTool(CHECK_STYLE_ID)));

    List<Job<?, ?>> jobs = list(job);
    verifySpotBugsAndCheckStyle(job, portlet.getModel(jobs));

    portlet.setTools(list(createTool(SPOT_BUGS_ID)));
    verifySingleTool(job, portlet.getModel(jobs), SPOT_BUGS_ID, SPOT_BUGS_NAME, 1);

    portlet.setTools(list(createTool(CHECK_STYLE_ID)));
    verifySingleTool(job, portlet.getModel(jobs), CHECK_STYLE_ID, CHECK_STYLE_NAME, 2);

    portlet.setTools(Collections.emptyList());

    PortletTableModel model = portlet.getModel(jobs);
    assertThat(model.getToolNames()).isEmpty();

    List<TableRow> rows = model.getRows();
    assertThat(rows).hasSize(1);

    TableRow actualRow = rows.get(0);
    assertThat(actualRow.getJob()).isSameAs(job);
    assertThat(actualRow.getResults()).isEmpty();
}
 
 类所在包
 同包方法