hudson.model.TopLevelItem Java Examples

The following examples show how to use hudson.model.TopLevelItem. 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: BitbucketOrg.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public boolean isJenkinsOrganizationPipeline() {
    for(TopLevelItem item: Jenkins.getInstance().getItems()){
        if(item instanceof OrganizationFolder){
            OrganizationFolder folder = (OrganizationFolder) item;
            for(SCMNavigator navigator: folder.getNavigators()) {
                if (navigator instanceof BitbucketSCMNavigator) {
                    BitbucketSCMNavigator scmNavigator = (BitbucketSCMNavigator) navigator;
                    if(scmNavigator.getRepoOwner().equals(getName())){
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
 
Example #2
Source File: AbstractPipelineCreateRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
protected @Nonnull TopLevelItem createProject(String name, String descriptorName, Class<? extends TopLevelItemDescriptor> descriptorClass, BlueOrganization organization) throws IOException {
    ModifiableTopLevelItemGroup p = getParent(organization);

    final ACL acl = (p instanceof AccessControlled) ? ((AccessControlled) p).getACL() : Jenkins.getInstance().getACL();
    Authentication a = Jenkins.getAuthentication();
    if(!acl.hasPermission(a, Item.CREATE)){
        throw new ServiceException.ForbiddenException(
                String.format("Failed to create pipeline: %s. User %s doesn't have Job create permission", name, a.getName()));
    }
    TopLevelItemDescriptor descriptor = Items.all().findByName(descriptorName);
    if(descriptor == null || !(descriptorClass.isAssignableFrom(descriptor.getClass()))){
        throw new ServiceException.BadRequestException(String.format("Failed to create pipeline: %s, descriptor %s is not found", name, descriptorName));
    }

    if (!descriptor.isApplicableIn(p)) {
        throw new ServiceException.ForbiddenException(
                String.format("Failed to create pipeline: %s. Pipeline can't be created in Jenkins root folder", name));
    }

    if (!acl.hasCreatePermission(a, p, descriptor)) {
        throw new ServiceException.ForbiddenException("Missing permission: " + Item.CREATE.group.title+"/"+Item.CREATE.name + " " + Item.CREATE + "/" + descriptor.getDisplayName());
    }
    return p.createProject(descriptor, name, true);
}
 
Example #3
Source File: AbstractGithubOrganization.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public boolean isJenkinsOrganizationPipeline() {
    for(TopLevelItem item: Jenkins.getInstance().getItems()){
        if(item instanceof OrganizationFolder){
            OrganizationFolder folder = (OrganizationFolder) item;
            for(SCMNavigator navigator: folder.getNavigators()) {
                if (navigator instanceof GitHubSCMNavigator) {
                    GitHubSCMNavigator scmNavigator = (GitHubSCMNavigator) navigator;
                    if(scmNavigator.getRepoOwner().equals(getName())){
                        return true;
                    }
                }
            }
        }
    }
    return false;

}
 
Example #4
Source File: BluePipelineFactory.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * Gives {@link BluePipeline} instance from the first pipeline found.
 *
 *
 * @param item {@link Item} for which corresponding BlueOcean API object needs to be found. Must implement
 *                         {@link TopLevelItem} for return to be not null
 * @param parent Parent {@link Reachable} object
 * @return {@link BluePipeline} if a map of item to BlueOcean API found, null otherwise.
 *
 */
public static BluePipeline getPipelineInstance(Item item, final Reachable parent){
    if(!(item instanceof TopLevelItem)) {
        return null;
    }
    BlueOrganization organization = OrganizationFactory.getInstance().getContainingOrg(item);
    if (organization == null) {
        return null;
    }
    for(BluePipelineFactory factory:BluePipelineFactory.all()){
        BluePipeline pipeline = factory.getPipeline(item, parent, organization);

        if(pipeline != null){
            return pipeline;
        }
    }
    return null;
}
 
Example #5
Source File: GitHubBranchFilter.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) {
    for (TopLevelItem item:all) {
        if (added.contains(item)) {
            continue;
        }
        if (SCMHead.HeadByItem.findHead(item) instanceof BranchSCMHead) {
            added.add(item);
        }
    }
    return added;
}
 
Example #6
Source File: AuthenticatedView.java    From DotCi with MIT License 5 votes vote down vote up
@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);
}
 
Example #7
Source File: GithubOrganisationFolderTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@ConfiguredWithCode("GithubOrganisationFolderTest.yml")
public void configure_github_organisation_folder_seed_job() throws Exception {
    final TopLevelItem job = Jenkins.get().getItem("ndeloof");
    assertNotNull(job);
    assertTrue(job instanceof OrganizationFolder);
    OrganizationFolder folder = (OrganizationFolder) job;
    assertEquals(1, folder.getNavigators().size());
    final GitHubSCMNavigator github = folder.getNavigators().get(GitHubSCMNavigator.class);
    assertNotNull(github);
    assertEquals("ndeloof", github.getRepoOwner());
}
 
Example #8
Source File: IntegrationTest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Copies the specified directory recursively to the workspace.
 *
 * @param job
 *         the job to get the workspace for
 * @param directory
 *         the directory to copy
 */
protected void copyDirectoryToWorkspace(final TopLevelItem job, final String directory) {
    try {
        URL resource = getTestResourceClass().getResource(directory);
        assertThat(resource).as("No such file: %s", directory).isNotNull();
        FilePath destination = new FilePath(new File(resource.getFile()));
        assertThat(destination.exists()).as("Directory %s does not exist", resource.getFile()).isTrue();
        destination.copyRecursiveTo(getWorkspace(job));
    }
    catch (IOException | InterruptedException e) {
        throw new AssertionError(e);
    }
}
 
Example #9
Source File: AuthenticatedView.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public TopLevelItem doCreateItem(final StaplerRequest req, final StaplerResponse rsp) throws IOException, ServletException {
    final ItemGroup<? extends TopLevelItem> ig = getOwnerItemGroup();
    if (ig instanceof ModifiableItemGroup) {
        return ((ModifiableItemGroup<? extends TopLevelItem>) ig).doCreateItem(req, rsp);
    }
    return null;
}
 
Example #10
Source File: GitLabMergeRequestFilter.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) {
    for (TopLevelItem item : all) {
        if (added.contains(item)) {
            continue;
        }
        SCMHead head = SCMHead.HeadByItem.findHead(item);
        if (head instanceof GitLabSCMMergeRequestHead && (!originOnly || ((GitLabSCMMergeRequestHead) head).fromOrigin())) {
            added.add(item);
        }
    }
    return added;
}
 
Example #11
Source File: GitHubPRTriggerTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
/**
 * Snapshot of files before Branch trigger refactoring.
 */
@LocalData
@Test
public void ensureOldValid() {
    final TopLevelItem item = j.getInstance().getItem("test-job");
    assertThat(item, notNullValue());
    final FreeStyleProject project = (FreeStyleProject) item;

    final GitHubPRRepository prRepository = project.getAction(GitHubPRRepository.class);
    assertThat(project, notNullValue());

    assertThat(prRepository.getFullName(), is("KostyaSha-auto/test"));

    final Map<Integer, GitHubPRPullRequest> pulls = prRepository.getPulls();
    assertThat(pulls.size(), is(1));
    final GitHubPRPullRequest pullRequest = pulls.get(1);
    assertThat(pullRequest, notNullValue());
    assertThat(pullRequest.getTitle(), is("Update README.md"));
    assertThat(pullRequest.getHeadRef(), is("KostyaSha-auto-patch-1"));
    assertThat(pullRequest.isMergeable(), is(true));
    assertThat(pullRequest.getBaseRef(), is("master"));
    assertThat(pullRequest.getUserLogin(), is("KostyaSha-auto"));
    assertThat(pullRequest.getSourceRepoOwner(), is("KostyaSha-auto"));
    assertThat(pullRequest.getLabels(), Matchers.<String>empty());

    final GitHubPRTrigger trigger = project.getTrigger(GitHubPRTrigger.class);
    assertThat(trigger, notNullValue());
    assertThat(trigger.getTriggerMode(), is(CRON));
    assertThat(trigger.getEvents(), hasSize(2));
    assertThat(trigger.isPreStatus(), is(false));
    assertThat(trigger.isCancelQueued(), is(false));
    assertThat(trigger.isSkipFirstRun(), is(false));
}
 
Example #12
Source File: GitLabTagFilter.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) {
    for (TopLevelItem item : all) {
        if (added.contains(item)) {
            continue;
        }
        if (SCMHead.HeadByItem.findHead(item) instanceof GitLabSCMTagHead) {
            added.add(item);
        }
    }
    return added;
}
 
Example #13
Source File: GitLabBranchFilter.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) {
    for (TopLevelItem item : all) {
        if (added.contains(item)) {
            continue;
        }

        SCMHead head = SCMHead.HeadByItem.findHead(item);
        if (head instanceof GitLabSCMBranchHead && filter(item) && filter((GitLabSCMBranchHead) head)) {
            added.add(item);
        }
    }
    return added;
}
 
Example #14
Source File: PipelineContainerImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Collection<TopLevelItem> getItems() {
    return Collections2.filter(this.jenkins.getItems(), new Predicate<TopLevelItem>() {
        @Override
        public boolean apply(TopLevelItem input) {
            return input.hasPermission(Item.READ);
        }
    });
}
 
Example #15
Source File: SelectJobsBallColorFolderIcon.java    From multi-branch-project-plugin with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: RunSearch.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Pageable<BlueRun> search(Query q) {

    String pipeline = q.param("pipeline", false);

    boolean latestOnly = q.param("latestOnly", Boolean.class);

    if(pipeline != null){
        TopLevelItem p = Jenkins.getActiveInstance().getItem(pipeline);
        if(latestOnly){
            BlueRun r = getLatestRun((Job)p);
            if(r != null) {
                return Pageables.wrap(Collections.singletonList(r));
            }else{
                Pageables.empty();
            }
        }
        if (p instanceof Job) {
            return Pageables.wrap(findRuns((Job)p));
        }else{
            throw new ServiceException.BadRequestException(String.format("Pipeline %s not found", pipeline));
        }
    }else if(latestOnly){
        return Pageables.empty();
    }
    return Pageables.wrap(findRuns(null));
}
 
Example #17
Source File: AbstractMultiBranchCreateRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private MultiBranchProject createMultiBranchProject(BlueOrganization organization) throws IOException {
    TopLevelItem item = createProject(getName(), DESCRIPTOR_NAME, MultiBranchProjectDescriptor.class, organization);
    if (!(item instanceof WorkflowMultiBranchProject)) {
        try {
            item.delete(); // we don't know about this project type
        } catch (InterruptedException e) {
            throw new ServiceException.UnexpectedErrorException("Failed to delete pipeline: " + getName());
        }
    }
    return (MultiBranchProject) item;
}
 
Example #18
Source File: FolderVaultConfigurationSpec.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
private AbstractFolder generateMockFolder(final DescribableList firstFolderProperties,
    final AbstractFolder parentToReturn) {
    return new AbstractFolder<TopLevelItem>(null, null) {
        @NonNull
        @Override
        public ItemGroup getParent() {
            return parentToReturn;
        }

        @Override
        public DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor> getProperties() {
            return firstFolderProperties;
        }
    };
}
 
Example #19
Source File: ViewTracker.java    From rocket-chat-notifier with Apache License 2.0 5 votes vote down vote up
private Collection<View> getViewsAffectedBy(Run<?, ?> run) {
	Collection<View> views = Jenkins.getInstance().getViews();
	List<View> affected = new ArrayList<>(views.size());
	TopLevelItem parent = getTopLevelParent(run);
	if (parent != null) {
		for (View view : views) {
			if (view.contains(parent)) {
				affected.add(view);
			}
		}
	} else {
		LOG.log(Level.WARNING, run.getParent().getClass() + " not instanceof TopLevelItem");
	}
	return affected;
}
 
Example #20
Source File: ViewTracker.java    From rocket-chat-notifier with Apache License 2.0 5 votes vote down vote up
private TopLevelItem getTopLevelParent(Object o) {
	if(o == null) return null;
	if(o instanceof TopLevelItem) return (TopLevelItem) o;
	Object parent = null;
	try {
		Method getParent = o.getClass().getMethod("getParent", null);
		parent = getParent.invoke(o, null);
	} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
		LOG.log(Level.WARNING,e.getMessage());
	}
	return getTopLevelParent(parent);
}
 
Example #21
Source File: ViewTracker.java    From rocket-chat-notifier with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: SecuredMockFolder.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override
public TopLevelItem getItem(String name) {
    final TopLevelItem item = super.getItem(name);
    if (item != null && item.hasPermission(Item.READ)) {
        return item;
    }
    return null;
}
 
Example #23
Source File: MockFolder.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override public Collection<? extends Job> getAllJobs() {
    Set<Job> jobs = new HashSet<Job>();
    for (TopLevelItem i : getItems()) {
        jobs.addAll(i.getAllJobs());
    }
    return jobs;
}
 
Example #24
Source File: MyBuildsView.java    From DotCi with MIT License 5 votes vote down vote up
@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);
}
 
Example #25
Source File: MockFolder.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
    if (items.containsKey(name)) {
        throw new IllegalArgumentException("already an item '" + name + "'");
    }
    items.put(name, item);
    return item;
}
 
Example #26
Source File: GitHubPullRequestFilter.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) {
    for (TopLevelItem item:all) {
        if (added.contains(item)) {
            continue;
        }
        if (SCMHead.HeadByItem.findHead(item) instanceof PullRequestSCMHead) {
            added.add(item);
        }
    }
    return added;
}
 
Example #27
Source File: JobDslITest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Creates a freestyle job from a YAML file and verifies that issue recorder finds warnings.
 */
@Test
public void shouldCreateFreestyleJobUsingJobDslAndVerifyIssueRecorderWithDefaultConfiguration() {
    configureJenkins("job-dsl-warnings-ng-default.yaml");

    TopLevelItem project = getJenkins().jenkins.getItem("dsl-freestyle-job");

    assertThat(project).isNotNull();
    assertThat(project).isInstanceOf(FreeStyleProject.class);

    DescribableList<Publisher, Descriptor<Publisher>> publishers = ((FreeStyleProject) project).getPublishersList();
    assertThat(publishers).hasSize(1);

    Publisher publisher = publishers.get(0);
    assertThat(publisher).isInstanceOf(IssuesRecorder.class);

    HealthReport healthReport = ((FreeStyleProject) project).getBuildHealth();
    assertThat(healthReport.getScore()).isEqualTo(100);

    IssuesRecorder recorder = (IssuesRecorder) publisher;

    assertThat(recorder.getAggregatingResults()).isFalse();
    assertThat(recorder.getTrendChartType()).isEqualTo(TrendChartType.AGGREGATION_TOOLS);
    assertThat(recorder.getBlameDisabled()).isFalse();
    assertThat(recorder.getForensicsDisabled()).isFalse();
    assertThat(recorder.getEnabledForFailure()).isFalse();
    assertThat(recorder.getHealthy()).isEqualTo(0);
    assertThat(recorder.getId()).isNull();
    assertThat(recorder.getIgnoreFailedBuilds()).isTrue();
    assertThat(recorder.getIgnoreQualityGate()).isFalse();
    assertThat(recorder.getMinimumSeverity()).isEqualTo("LOW");
    assertThat(recorder.getName()).isNull();
    assertThat(recorder.getQualityGates()).hasSize(0);
    assertThat(recorder.getSourceCodeEncoding()).isEmpty();
    assertThat(recorder.getUnhealthy()).isEqualTo(0);

    List<Tool> tools = recorder.getTools();
    assertThat(tools).hasSize(2);
    assertThat(tools.get(0)).isInstanceOf(Java.class);
}
 
Example #28
Source File: OrganizationContainer.java    From DotCi with MIT License 4 votes vote down vote up
public TopLevelItem createProjectFromXML(final String name, final InputStream xml) throws IOException {
    return this.mixin.createProjectFromXML(name, xml);
}
 
Example #29
Source File: MockFolder.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
@Override public Collection<TopLevelItem> getItems() {
    return items.values(); // could be filtered by Item.READ
}
 
Example #30
Source File: MockFolder.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
@Override public TopLevelItem getItem(String name) {
    if (items == null) {
        return null; // cf. parent hack in AbstractProject.onLoad
    }
    return items.get(name);
}