下面列出了hudson.model.ModelObject#hudson.model.ItemGroup 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
@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());
}
@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);
}
@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\\*");
}
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;
}
});
}
@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;
}
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;
}
};
}
@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;
}
@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;
}
@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);
}
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;
}
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);
}
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;
}
/**
* Tries to obtain the base group for a <code>BlueOrganization</code>
*
* @param org to get the base group of
* @return the base group
*/
public static ItemGroup<?> getBaseGroup(BlueOrganization org) {
ItemGroup<?> group = null;
if (org != null && org instanceof AbstractOrganization) {
group = ((AbstractOrganization) org).getGroup();
}
return group;
}
@Restricted(NoExternalUse.class)
public static AuthConfig getAuthConfig(DockerRegistryEndpoint registry, ItemGroup context) {
AuthConfig auth = new AuthConfig();
// we can't use DockerRegistryEndpoint#getToken as this one do check domainRequirement based on registry URL
// but in some context (typically, passing registry auth for `docker build`) we just can't guess this one.
final Credentials c = firstOrNull(CredentialsProvider.lookupCredentials(
IdCredentials.class, context, ACL.SYSTEM, Collections.EMPTY_LIST),
withId(registry.getCredentialsId()));
final DockerRegistryToken t = c == null ? null : AuthenticationTokens.convert(DockerRegistryToken.class, c);
if (t == null) {
throw new IllegalArgumentException("Invalid Credential ID " + registry.getCredentialsId());
}
final String token = t.getToken();
// What docker-commons claim to be a "token" is actually configuration storage
// see https://github.com/docker/docker-ce/blob/v17.09.0-ce/components/cli/cli/config/configfile/file.go#L214
// i.e base64 encoded username : password
final String decode = new String(Base64.decodeBase64(token), StandardCharsets.UTF_8);
int i = decode.indexOf(':');
if (i > 0) {
String username = decode.substring(0, i);
auth.withUsername(username);
}
auth.withPassword(decode.substring(i+1));
if (registry.getUrl() != null) {
auth.withRegistryAddress(registry.getUrl());
}
return auth;
}
/**
* If the search restricts the scope to a specific org (aka ItemGroup), return that, or else
* the default scope, which is {@link Jenkins}.
*/
private ItemGroup findItemGroup(Query q) {
String org = q.param(ORGANIZATION_PARAM);
if (org==null) return Jenkins.getInstance();
ItemGroup group = OrganizationFactory.getItemGroup(org);
if (group==null) {
throw new ServiceException.BadRequestException(
String.format("Organization %s not found. Query parameter %s value: %s is invalid. ", org,ORGANIZATION_PARAM,org));
}
return group;
}
private boolean exclude(ItemGroup item, List<Class> excludeList){
for(Class c:excludeList){
if(c.isAssignableFrom(item.getClass())){
return true;
}
}
return false;
}
@Override
public OrganizationImpl of(ItemGroup group) {
if (group == instance.getGroup()) {
return instance;
}
return null;
}
/**
* Finds a nearest organization that contains the given {@link ItemGroup}.
*
* @return
* null if the given object doesn't belong to any organization.
*/
@CheckForNull
public BlueOrganization getContainingOrg(ItemGroup p) {
while (true) {
BlueOrganization n = of(p);
if (n != null) {
return n;
}
if (p instanceof Item) {
p = ((Item) p).getParent();
} else {
return null; // hit the top
}
}
}
@CheckForNull
public final BlueOrganization getContainingOrg(Item i) {
if (i instanceof ItemGroup) {
return getContainingOrg((ItemGroup) i);
} else {
return getContainingOrg(i.getParent());
}
}
@Override
public OrganizationImpl of(ItemGroup group) {
if (group == instance.getGroup()) {
return instance;
}
return null;
}
@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());
}
}
}
}
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;
}
@Override
public OrganizationImpl of(ItemGroup group) {
if (group == instance.getGroup() || group == Jenkins.getInstance()) {
return instance;
}
return null;
}
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;
}
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;
}
};
}
@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;
}
}
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);
}
}
@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;
}
@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;
}