hudson.model.ItemGroup Java Examples

The following examples show how to use hudson.model.ItemGroup. 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: DockerConnector.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance());
    if (!ac.hasPermission(Jenkins.ADMINISTER)) {
        return new ListBoxModel();
    }

    List<StandardCredentials> credentials =
            CredentialsProvider.lookupCredentials(StandardCredentials.class,
                    context,
                    ACL.SYSTEM,
                    Collections.emptyList());

    return new CredentialsListBoxModel()
            .includeEmptyValue()
            .withMatching(CredentialsMatchers.always(), credentials);
}
 
Example #2
Source File: OrganizationFolderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
@WithoutJenkins
public void testOrgFolderPipeline() throws IOException {
    AvatarMetadataAction avatarMetadataAction = mock(AvatarMetadataAction.class);
    when(orgFolder.getAction(AvatarMetadataAction.class)).thenReturn(avatarMetadataAction);

    BlueOrganizationFolder organizationFolder = new OrganizationFolderPipelineImpl(organization, orgFolder, organization.getLink().rel("/pipelines/")){};
    assertEquals(organizationFolder.getName(), organizationFolder.getName());
    assertEquals(organizationFolder.getDisplayName(), organizationFolder.getDisplayName());
    assertEquals(organization.getName(), organizationFolder.getOrganizationName());
    assertNotNull(organizationFolder.getIcon());
    MultiBranchProject multiBranchProject = PowerMockito.mock(MultiBranchProject.class);
    when(orgFolder.getItem("repo1")).thenReturn(multiBranchProject);
    PowerMockito.when(OrganizationFactory.getInstance().getContainingOrg((ItemGroup)multiBranchProject)).thenReturn(organization);
    PowerMockito.when(multiBranchProject.getFullName()).thenReturn("p1");
    PowerMockito.when(multiBranchProject.getName()).thenReturn("p1");
    MultiBranchPipelineContainerImpl multiBranchPipelineContainer =
            new MultiBranchPipelineContainerImpl(organization, orgFolder, organizationFolder);

    assertEquals(multiBranchProject.getName(), multiBranchPipelineContainer.get("repo1").getName());
    when(orgFolder.getItems()).thenReturn(Lists.<MultiBranchProject<?, ?>>newArrayList(multiBranchProject));
    assertNotNull(organizationFolder.getPipelineFolderNames());
}
 
Example #3
Source File: AbstractPipelineImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * Returns full display name relative to the <code>BlueOrganization</code> base. Each display name is separated by
 * '/' and each display name is url encoded
 *
 * @param org the organization the item belongs to
 * @param item to return the full display name of
 *
 * @return full display name
 */
public static String getFullDisplayName(@Nullable BlueOrganization org, @Nonnull Item item) {
    ItemGroup<?> group = getBaseGroup(org);
    String[] displayNames = Functions.getRelativeDisplayNameFrom(item, group).split(" ยป ");

    StringBuilder encodedDisplayName=new StringBuilder();
    for(int i=0;i<displayNames.length;i++) {
        if(i!=0) {
            encodedDisplayName.append(String.format("/%s", Util.rawEncode(displayNames[i])));
        }else {
            encodedDisplayName.append(String.format("%s", Util.rawEncode(displayNames[i])));
        }
    }

    return encodedDisplayName.toString();
}
 
Example #4
Source File: CardBuilderTest.java    From office-365-connector-plugin with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    ItemGroup itemGroup = mock(ItemGroup.class);
    when(itemGroup.getFullDisplayName()).thenReturn(StringUtils.EMPTY);

    Job job = mock(Job.class);
    when(job.getDisplayName()).thenReturn(JOB_DISPLAY_NAME);
    when(job.getParent()).thenReturn(itemGroup);

    run = mock(AbstractBuild.class);
    when(run.getNumber()).thenReturn(BUILD_NUMBER);
    when(run.getParent()).thenReturn(job);

    mockDisplayURLProvider(JOB_DISPLAY_NAME, BUILD_NUMBER);
    TaskListener taskListener = mock(TaskListener.class);
    cardBuilder = new CardBuilder(run, taskListener);
}
 
Example #5
Source File: CardBuilderTest.java    From office-365-connector-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void getEscapedDisplayName_OnNameWithSpecialCharacters_EscapesSpecialCharacters() {

    // given
    final String specialDisplayName = "this_is_my-very#special *job*";
    ItemGroup itemGroup = mock(ItemGroup.class);
    when(itemGroup.getFullDisplayName()).thenReturn(StringUtils.EMPTY);

    Job job = mock(Job.class);
    when(job.getDisplayName()).thenReturn(specialDisplayName);
    when(job.getParent()).thenReturn(itemGroup);

    run = mock(AbstractBuild.class);
    when(run.getParent()).thenReturn(job);
    TaskListener taskListener = mock(TaskListener.class);

    mockDisplayURLProvider(JOB_DISPLAY_NAME, BUILD_NUMBER);
    cardBuilder = new CardBuilder(run, taskListener);

    // when
    String displayName = Deencapsulation.invoke(cardBuilder, "getEscapedDisplayName");

    // then
    assertThat(displayName).isEqualTo("this\\_is\\_my\\-very\\#special \\*job\\*");
}
 
Example #6
Source File: ActionResolver.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
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;
        }
    });
}
 
Example #7
Source File: FolderVaultConfiguration.java    From hashicorp-vault-plugin with MIT License 6 votes vote down vote up
@NonNull
@Override
public VaultConfiguration forJob(@NonNull Item job) {
    VaultConfiguration resultingConfig = null;
    for (ItemGroup g = job.getParent(); g instanceof AbstractFolder;
        g = ((AbstractFolder) g).getParent()) {
        FolderVaultConfiguration folderProperty = ((AbstractFolder<?>) g).getProperties()
            .get(FolderVaultConfiguration.class);
        if (folderProperty == null) {
            continue;
        }
        if (resultingConfig != null) {
            resultingConfig = resultingConfig
                .mergeWithParent(folderProperty.getConfiguration());
        } else {
            resultingConfig = folderProperty.getConfiguration();
        }
    }

    return resultingConfig;
}
 
Example #8
Source File: FolderVaultConfigurationSpec.java    From hashicorp-vault-plugin with MIT License 6 votes vote down vote up
private Job generateMockJob(final AbstractFolder firstParent) {
    return new Job(firstParent, "test-job") {
        @Override
        public boolean isBuildable() {
            return true;
        }

        @Override
        protected SortedMap _getRuns() {
            return null;
        }

        @Override
        protected void removeRun(Run run) {

        }

        @NonNull
        @Override
        public ItemGroup getParent() {
            return firstParent;
        }
    };
}
 
Example #9
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@CheckForNull
private MavenConfigFolderOverrideProperty getMavenConfigOverrideProperty() {
    Job<?, ?> job = build.getParent(); // Get the job

    // Iterate until we find an override or until we reach the top. We need it to be an item to be able to do
    // getParent, AbstractFolder which has the properties is also an Item
    for (ItemGroup<?> group = job.getParent(); group != null && group instanceof Item && !(group instanceof Jenkins); group = ((Item) group).getParent()) {
        if (group instanceof AbstractFolder) {
            MavenConfigFolderOverrideProperty mavenConfigProperty = ((AbstractFolder<?>) group).getProperties().get(MavenConfigFolderOverrideProperty.class);
            if (mavenConfigProperty != null && mavenConfigProperty.isOverride()) {
                return mavenConfigProperty;
            }
        }
    }
    return null;
}
 
Example #10
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@RequirePOST
@SuppressWarnings("unused") // used by jelly
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String serverUrl) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    StandardListBoxModel result = new StandardListBoxModel();
    result.includeEmptyValue();
    result.includeMatchingAs(
        ACL.SYSTEM,
        context,
        StandardCredentials.class,
        serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
                    : Collections.EMPTY_LIST,
        CredentialsMatchers.anyOf(
            AuthenticationTokens.matcher(KubernetesAuth.class)
        )
    );
    return result;
}
 
Example #11
Source File: DockerPullImage.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    List<DockerRegistryAuthCredentials> credentials =
            CredentialsProvider.lookupCredentials(DockerRegistryAuthCredentials.class, context, ACL.SYSTEM,
                    Collections.emptyList());

    return new StandardListBoxModel().withEmptySelection()
            .withMatching(CredentialsMatchers.instanceOf(DockerRegistryAuthCredentials.class), credentials);
}
 
Example #12
Source File: FolderConfig.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Override
public String getLabel(@Nullable Run run) {
    if (run != null) {
        Job job = run.getParent();
        ItemGroup parent = job.getParent();
        while (parent != null) {

            if (parent instanceof AbstractFolder) {
                AbstractFolder folder = (AbstractFolder) parent;
                FolderConfig config = (FolderConfig) folder.getProperties().get(FolderConfig.class);
                if (config != null) {
                    String label = config.getDockerLabel();
                    if (!StringUtils.isBlank(label)) {
                        return label;
                    }
                }
            }

            if (parent instanceof Item) {
                parent = ((Item) parent).getParent();
            } else {
                parent = null;
            }
        }
    }
    return null;
}
 
Example #13
Source File: CredentialsHelper.java    From git-changelog-plugin with MIT License 5 votes vote down vote up
private static <C extends Credentials> List<C> getAllCredentials(Class<C> type) {
  ItemGroup<?> itemGroup = null;
  Authentication authentication = SYSTEM;
  DomainRequirement domainRequirement = null;

  return lookupCredentials(type, itemGroup, authentication, domainRequirement);
}
 
Example #14
Source File: LocalRepoPlunger.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public void onDeleted(Item item) {
    if (!(item instanceof Job)) {
        return;
    }

    ItemGroup<? extends Item> parent = item.getParent();
    if (!(parent instanceof MultiBranchProject)) {
        return;
    }

    Job j = (Job) item;
    MultiBranchProject mb = (MultiBranchProject) parent;
    Branch branch = mb.getProjectFactory().getBranch(j);
    SCMHead head = branch.getHead();

    Consumer<GitHubRepo> plunger = null;
    if (head instanceof GitHubBranchSCMHead) {
        plunger = r -> r.getBranchRepository().getBranches().remove(head.getName());
    } else if (head instanceof GitHubTagSCMHead) {
        plunger = r -> r.getTagRepository().getTags().remove(head.getName());
    } else if (head instanceof GitHubPRSCMHead) {
        GitHubPRSCMHead prHead = (GitHubPRSCMHead) head;
        plunger = r -> r.getPrRepository().getPulls().remove(prHead.getPrNumber());
    }

    if (plunger != null) {
        for (SCMSource src : (List<SCMSource>) mb.getSCMSources()) {
            if (src instanceof GitHubSCMSource) {
                GitHubSCMSource gsrc = (GitHubSCMSource) src;
                plunger.accept(gsrc.getLocalRepo());
                LOG.info("Plunging local data for {}", item.getFullName());
            }
        }
    }
}
 
Example #15
Source File: SelectJobsBallColorFolderIcon.java    From multi-branch-project-plugin with MIT License 5 votes vote down vote up
/**
 * Form validation method.  Similar to
 * {@link hudson.tasks.BuildTrigger.DescriptorImpl#doCheck(AbstractProject, String)}.
 *
 * @param folder the folder being configured
 * @param value  the user-entered value
 * @return validation result
 */
public FormValidation doCheck(@AncestorInPath AbstractFolder folder, @QueryParameter String value) {
    // Require CONFIGURE permission on this project
    if (!folder.hasPermission(Item.CONFIGURE)) {
        return FormValidation.ok();
    }

    boolean hasJobs = false;

    StringTokenizer tokens = new StringTokenizer(Util.fixNull(value), ",");
    while (tokens.hasMoreTokens()) {
        String jobName = tokens.nextToken().trim();

        if (StringUtils.isNotBlank(jobName)) {
            Item item = Jenkins.getActiveInstance().getItem(jobName, (ItemGroup) folder, Item.class);

            if (item == null) {
                Job nearest = Items.findNearest(Job.class, jobName, folder);
                String alternative = nearest != null ? nearest.getRelativeNameFrom((ItemGroup) folder) : "?";
                return FormValidation.error(
                        hudson.tasks.Messages.BuildTrigger_NoSuchProject(jobName, alternative));
            }

            if (!(item instanceof Job)) {
                return FormValidation.error(hudson.tasks.Messages.BuildTrigger_NotBuildable(jobName));
            }

            hasJobs = true;
        }
    }

    if (!hasJobs) {
        return FormValidation.error(hudson.tasks.Messages.BuildTrigger_NoProjectSpecified());
    }

    return FormValidation.ok();
}
 
Example #16
Source File: JobStateRecipe.java    From jenkins-build-monitor-plugin with MIT License 5 votes vote down vote up
private JobStateRecipe withShortUrl(String url) {
    when(job.getShortUrl()).thenReturn(url);

    // This might not necessarily belong here,
    // but I don't need to introduce the concept of a parent anywhere else yet.
    ItemGroup parent = mock(ItemGroup.class);
    when(parent.getUrl()).thenReturn("job/");
    when(job.getParent()).thenReturn(parent);

    return this;
}
 
Example #17
Source File: MockAuthorizationStrategy.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * On some item groups, typically folders.
 * The grant applies to the folder itself as well as any (direct or indirect) children.
 */
public GrantOn onFolders(ItemGroup<?>... folders) {
    String[] paths = new String[folders.length];
    for (int i = 0; i < folders.length; i++) {
        paths[i] = Pattern.quote(folders[i].getFullName()) + "(|/.+)";
    }
    return onPaths(paths);
}
 
Example #18
Source File: WithMavenStep.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillPublisherStrategyItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    for(MavenPublisherStrategy publisherStrategy: MavenPublisherStrategy.values()) {
        r.add(publisherStrategy.getDescription(), publisherStrategy.name());
    }
    return r;
}
 
Example #19
Source File: OrganizationFolderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
static OrganizationFolder mockOrgFolder(BlueOrganization organization){
    OrganizationFolder orgFolder = PowerMockito.mock(OrganizationFolder.class);

    OrganizationFactory organizationFactory = mock(OrganizationFactory.class);
    PowerMockito.mockStatic(OrganizationFactory.class);
    PowerMockito.when(OrganizationFactory.getInstance()).thenReturn(organizationFactory);
    when(organizationFactory.getContainingOrg((ItemGroup) orgFolder)).thenReturn(organization);
    PowerMockito.when(orgFolder.getDisplayName()).thenReturn("vivek");
    PowerMockito.when(orgFolder.getName()).thenReturn("vivek");
    PowerMockito.when(orgFolder.getFullName()).thenReturn("vivek");

    return orgFolder;
}
 
Example #20
Source File: WithMavenStep.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillGlobalMavenSettingsConfigItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default settings or file path ---",null);
    for (Config config : ConfigFiles.getConfigsInContext(context, GlobalMavenSettingsConfigProvider.class)) {
        r.add(config.name, config.id);
    }
    return r;
}
 
Example #21
Source File: SseEventTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public OrganizationImpl of(ItemGroup group) {
    if (group == instance.getGroup() || group == Jenkins.getInstance()) {
        return instance;
    }
    return null;
}
 
Example #22
Source File: WithMavenStep.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillMavenSettingsConfigItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default settings or file path ---",null);
    for (Config config : ConfigFiles.getConfigsInContext(context, MavenSettingsConfigProvider.class)) {
        r.add(config.name, config.id);
    }
    return r;
}
 
Example #23
Source File: BlueOceanUrlMapperImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private BlueOrganization getOrganization(ModelObject modelObject ){
    BlueOrganization organization = null;
    if(modelObject instanceof Item){
        organization = OrganizationFactory.getInstance().getContainingOrg((Item) modelObject);
    }else if(modelObject instanceof ItemGroup){
        organization = OrganizationFactory.getInstance().getContainingOrg((ItemGroup) modelObject);
    }else if(modelObject instanceof Run){
        organization = OrganizationFactory.getInstance().getContainingOrg(((Run) modelObject).getParent());
    }
    return organization;
}
 
Example #24
Source File: AbstractTest.java    From office-365-connector-plugin with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: RelativeLocation.java    From jenkins-build-monitor-plugin with MIT License 5 votes vote down vote up
public String name() {
    ItemGroup ig = null;

    StaplerRequest request = Stapler.getCurrentRequest();
    for( Ancestor a : request.getAncestors() ) {
        if(a.getObject() instanceof BuildMonitorView) {
            ig = ((View) a.getObject()).getOwnerItemGroup();
        }
    }

    return Functions.getRelativeDisplayNameFrom(job, ig);
}
 
Example #26
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
static StandardCredentials getCredentials(ItemGroup owner, String uri, String credentialId){
    StandardCredentials standardCredentials =  CredentialsUtils.findCredential(credentialId, StandardCredentials.class, new BlueOceanDomainRequirement());
    if(standardCredentials == null){
        standardCredentials = CredentialsMatchers
                .firstOrNull(
                        CredentialsProvider.lookupCredentials(StandardCredentials.class, owner,
                                ACL.SYSTEM, URIRequirementBuilder.fromUri(uri).build()),
                        CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialId),
                                GitClient.CREDENTIALS_MATCHER));
    }

    return standardCredentials;
}
 
Example #27
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
private GitHubSCMSource getSource() {
    ItemGroup parent = run.getParent().getParent();
    if (parent instanceof SCMSourceOwner) {
        SCMSourceOwner owner = (SCMSourceOwner)parent;
        for (SCMSource source : owner.getSCMSources()) {
            if (source instanceof GitHubSCMSource) {
                return ((GitHubSCMSource) source);
            }
        }
        throw new IllegalArgumentException(UNABLE_TO_INFER_DATA);
    } else {
        throw new IllegalArgumentException(UNABLE_TO_INFER_DATA);
    }
}
 
Example #28
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 #29
Source File: AWSClientFactoryTest.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test(expected=InvalidInputException.class)
public void testNonExistentCreds() {
    String credentialsId = "folder-creds";
    String folder = "folder";

    when(CredentialsMatchers.firstOrNull(any(Iterable.class), any(CredentialsMatcher.class))).thenReturn(null);

    Jenkins mockInstance = mock(Jenkins.class);
    Item mockFolder = mock(Item.class);
    PowerMockito.mockStatic(Jenkins.class);
    when(Jenkins.getInstance()).thenReturn(mockInstance);
    when(mockInstance.getItemByFullName(credentialsId)).thenReturn(mockFolder);

    PowerMockito.mockStatic(CredentialsProvider.class);

    AbstractProject mockProject = mock(AbstractProject.class);
    ItemGroup mockFolderItem = mock(ItemGroup.class);

    when(build.getParent()).thenReturn(mockProject);
    when(mockProject.getParent()).thenReturn(mockFolderItem);
    when(mockFolder.getFullName()).thenReturn(folder);

    try {
        new AWSClientFactory("jenkins", credentialsId, "", "", "", null, "", REGION, build, null);
    } catch (InvalidInputException e) {
        assert(e.getMessage().contains(CodeBuilderValidation.invalidCredentialsIdError));
        throw e;
    }
}
 
Example #30
Source File: GithubOrgFolderPermissionsTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public OrganizationImpl of(ItemGroup group) {
    if (group == instance.getGroup()) {
        return instance;
    }
    return null;
}