下面列出了怎么用hudson.model.Item的API类实例代码及写法,或者点击链接到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();
}
@Override
public Iterator<BlueFavorite> iterator(int start, int limit) {
List<BlueFavorite> favorites = new ArrayList<>();
Iterator<Item> favoritesIterator = Favorites.getFavorites(user.user).iterator();
Utils.skip(favoritesIterator, start);
int count = 0;
while(count < limit && favoritesIterator.hasNext()) {
Item item = favoritesIterator.next();
if(item instanceof AbstractFolder) {
continue;
}
BlueFavorite blueFavorite = FavoriteUtil.getFavorite(item);
if(blueFavorite != null){
favorites.add(blueFavorite);
count++;
}
}
return favorites.iterator();
}
@Restricted(NoExternalUse.class)
private String getApiToken(String apiTokenId, Item item) {
ItemGroup<?> context = null != item ? item.getParent() : Jenkins.get();
StandardCredentials credentials = CredentialsMatchers.firstOrNull(
lookupCredentials(
StandardCredentials.class,
context,
ACL.SYSTEM,
URIRequirementBuilder.fromUri(url).build()),
CredentialsMatchers.withId(apiTokenId));
if (credentials != null) {
if (credentials instanceof GitLabApiToken) {
return ((GitLabApiToken) credentials).getApiToken().getPlainText();
}
if (credentials instanceof StringCredentials) {
return ((StringCredentials) credentials).getSecret().getPlainText();
}
}
throw new IllegalStateException("No credentials found for credentialsId: " + apiTokenId);
}
/**
* {@inheritDoc}
*/
@Override
public void onChange(Saveable o, XmlFile file) {
if (!(o instanceof Item)) {
// must be an Item
return;
}
SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem((Item) o);
if (item == null) {
// more specifically must be an SCMTriggerItem
return;
}
SCMTrigger trigger = item.getSCMTrigger();
if (trigger == null || trigger.isIgnorePostCommitHooks()) {
// must have the trigger enabled and not opted out of post commit hooks
return;
}
for (SCM scm : item.getSCMs()) {
if (scm instanceof GitSCM) {
// we have a winner
GiteaWebhookListener.register(item, (GitSCM) scm);
}
}
}
/**
* Populates a {@link ListBoxModel} with the checkout credentials appropriate for the supplied context against the
* supplied API endpoint.
*
* @param context the context.
* @param apiUri the api endpoint.
* @return a {@link ListBoxModel}.
*/
@NonNull
public static ListBoxModel listCheckoutCredentials(@CheckForNull Item context, String apiUri) {
StandardListBoxModel result = new StandardListBoxModel();
result.includeEmptyValue();
result.add("- same as scan credentials -", GitHubSCMSource.DescriptorImpl.SAME);
result.add("- anonymous -", GitHubSCMSource.DescriptorImpl.ANONYMOUS);
return result.includeMatchingAs(
context instanceof Queue.Task
? ((Queue.Task) context).getDefaultAuthentication()
: ACL.SYSTEM,
context,
StandardUsernameCredentials.class,
githubDomainRequirements(apiUri),
GitClient.CREDENTIALS_MATCHER
);
}
public static FormValidation doCheckFillCredentialsId(
final Item item, final String credentialsId, final String uri) {
if (item == null) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.ok();
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ)
&& !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return FormValidation.ok();
}
}
if (isNullOrEmpty(credentialsId)) {
return FormValidation.ok();
}
if (!findCredentials(item, credentialsId, uri).isPresent()) {
return FormValidation.error("Cannot find currently selected credentials");
}
return FormValidation.ok();
}
/**
* 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
@Override
public Object getContent(@Nonnull StaplerRequest staplerRequest, @Nonnull Item item) {
return new ScmFile<TestContent>(){
@Override
public TestContent getContent() {
return new TestContent("Hello World!");
}
};
}
private FolderBasedAuthorizationStrategy createNewFolderBasedAuthorizationStrategy() {
Set<GlobalRole> globalRoles = new HashSet<>();
globalRoles.add(new GlobalRole("admin", wrapPermissions(Jenkins.ADMINISTER), ImmutableSet.of("admin")));
globalRoles.add(new GlobalRole("read", wrapPermissions(Jenkins.READ), ImmutableSet.of("authenticated")));
Set<FolderRole> folderRoles = new HashSet<>();
folderRoles.add(new FolderRole("read", wrapPermissions(Item.READ), ImmutableSet.of("folder"),
ImmutableSet.of("user1")));
Set<AgentRole> agentRoles = new HashSet<>();
agentRoles.add(new AgentRole("configureMaster", wrapPermissions(Computer.CONFIGURE),
Collections.singleton("foo"), Collections.singleton("user1")));
return new FolderBasedAuthorizationStrategy(globalRoles, folderRoles, agentRoles);
}
@RequirePOST
public FormValidation doTestConnection(
@AncestorInPath Item context,
@QueryParameter String uri,
@QueryParameter String credentialsId,
@QueryParameter String apiVersion,
@QueryParameter int connectTimeout,
@QueryParameter int readTimeout
) {
throwIfNoPermission(context);
final FormValidation credentialsIdCheckResult = doCheckCredentialsId(context, uri, credentialsId);
if (credentialsIdCheckResult != FormValidation.ok()) {
return FormValidation.error("Invalid credentials");
}
try {
final DockerServerEndpoint dsep = new DockerServerEndpoint(uri, credentialsId);
final DockerAPI dapi = new DockerAPI(dsep, connectTimeout, readTimeout, apiVersion, null);
try(final DockerClient dc = dapi.getClient()) {
final VersionCmd vc = dc.versionCmd();
final Version v = vc.exec();
final String actualVersion = v.getVersion();
final String actualApiVersion = v.getApiVersion();
return FormValidation.ok("Version = " + actualVersion + ", API Version = " + actualApiVersion);
}
} catch (Exception e) {
return FormValidation.error(e, e.getMessage());
}
}
@SuppressWarnings("unused") // Used by stapler
public ListBoxModel doFillCredentialsIdItems(
@AncestorInPath final Item item,
@QueryParameter final String credentialsId,
@QueryParameter final String gitHubUrl) {
return CredentialsHelper.doFillCredentialsIdItems(item, credentialsId, gitHubUrl);
}
@Override
public void onUpdated(Item item) {
TemplateImplementationProperty property = getTemplateImplementationProperty(item);
if (property != null) {
try {
TemplateUtils.handleTemplateImplementationSaved((AbstractProject) item, property);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
public ListBoxModel doFillInputTypeItems(@AncestorInPath Item item,
@QueryParameter String key, @QueryParameter String type) {
ListBoxModel ret = new ListBoxModel();
ret.add("Json contents", "json");
ret.add("API Object type : API Object key", "kv");
ret.add("Label", "label");
return ret;
}
public ListBoxModel doFillApiTokenIdItems(@QueryParameter String url, @QueryParameter String apiTokenId) {
if (Jenkins.get().hasPermission(Item.CONFIGURE)) {
return new StandardListBoxModel()
.includeEmptyValue()
.includeMatchingAs(ACL.SYSTEM,
Jenkins.get(),
StandardCredentials.class,
URIRequirementBuilder.fromUri(url).build(),
new GitLabCredentialMatcher())
.includeCurrentValue(apiTokenId);
}
return new StandardListBoxModel();
}
@Override
public void onLocationChanged(Item item, String oldFullName, String newFullName) {
if (item instanceof WorkflowJob) {
WorkflowJob pipeline = (WorkflowJob) item;
onLocationChanged(pipeline, oldFullName, newFullName);
} else {
LOGGER.log(Level.FINE, "Ignore onLocationChanged({0}, {1}, {2})", new Object[]{item, oldFullName, newFullName});
}
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
protected List<Action> retrieveActions(@CheckForNull SCMSourceEvent event,
@NonNull TaskListener listener) throws IOException {
// TODO when we have support for trusted events, use the details from event if event was from trusted source
List<Action> result = new ArrayList<>();
result.add(new GitHubRepoMetadataAction());
String repository = this.repository;
StandardCredentials credentials = Connector.lookupScanCredentials((Item) getOwner(), apiUri, credentialsId);
GitHub hub = Connector.connect(apiUri, credentials);
try {
Connector.checkConnectionValidity(apiUri, listener, credentials, hub);
try {
ghRepository = hub.getRepository(getRepoOwner() + '/' + repository);
resolvedRepositoryUrl = ghRepository.getHtmlUrl();
} catch (FileNotFoundException e) {
throw new AbortException(
String.format("Invalid scan credentials when using %s to connect to %s/%s on %s",
credentials == null ? "anonymous access" : CredentialsNameProvider.name(credentials), repoOwner, repository, apiUri));
}
result.add(new ObjectMetadataAction(null, ghRepository.getDescription(), Util.fixEmpty(ghRepository.getHomepage())));
result.add(new GitHubLink("icon-github-repo", ghRepository.getHtmlUrl()));
if (StringUtils.isNotBlank(ghRepository.getDefaultBranch())) {
result.add(new GitHubDefaultBranch(getRepoOwner(), repository, ghRepository.getDefaultBranch()));
}
return result;
} finally {
Connector.release(hub);
}
}
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item, @QueryParameter String serverUrl) {
StandardListBoxModel result = new StandardListBoxModel();
result.includeEmptyValue();
result.includeMatchingAs(
ACL.SYSTEM,
item,
StandardCredentials.class,
URIRequirementBuilder.fromUri(serverUrl).build(),
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(org.jenkinsci.plugins.kubernetes.credentials.TokenProducer.class),
AuthenticationTokens.matcher(KubernetesAuth.class)
)
);
return result;
}
@Test
public void permissionTest() {
Jenkins jenkins = jenkinsRule.jenkins;
try (ACLContext ignored = ACL.as(admin)) {
assertTrue(jenkins.hasPermission(Jenkins.ADMINISTER));
assertTrue(child3.hasPermission(Item.CONFIGURE));
assertTrue(job1.hasPermission(Item.READ));
assertTrue(job2.hasPermission(Item.CREATE));
}
try (ACLContext ignored = ACL.as(user1)) {
assertTrue(jenkins.hasPermission(Permission.READ));
assertTrue(root.hasPermission(Item.READ));
assertTrue(job1.hasPermission(Item.READ));
assertTrue(job2.hasPermission(Item.READ));
assertFalse(job1.hasPermission(Item.CREATE));
assertFalse(job1.hasPermission(Item.DELETE));
assertFalse(job1.hasPermission(Item.CONFIGURE));
assertFalse(job2.hasPermission(Item.CREATE));
assertFalse(job2.hasPermission(Item.CONFIGURE));
}
try (ACLContext ignored = ACL.as(user2)) {
assertTrue(jenkins.hasPermission(Permission.READ));
assertTrue(child2.hasPermission(Item.READ));
assertTrue(child1.hasPermission(Item.READ));
assertTrue(job2.hasPermission(Item.CONFIGURE));
assertFalse(job1.hasPermission(Item.CONFIGURE));
}
}
@CheckForNull
public final BlueOrganization getContainingOrg(Item i) {
if (i instanceof ItemGroup) {
return getContainingOrg((ItemGroup) i);
} else {
return getContainingOrg(i.getParent());
}
}
@Override
public BluePipeline get(String name) {
Item item;
item = itemGroup.getItem(name);
if(item == null){
throw new ServiceException.NotFoundException(String.format("Pipeline %s not found", name));
}
return BluePipelineFactory.getPipelineInstance(item, this);
}
@Test
public void canNotCreateWhenHaveNoPermissionOnDefaultOrg() throws Exception {
MockAuthorizationStrategy authz = new MockAuthorizationStrategy();
authz.grant(Item.READ, Jenkins.READ).everywhere().to(user);
j.jenkins.setAuthorizationStrategy(authz);
// refresh the JWT token otherwise all hell breaks loose.
jwtToken = getJwtToken(j.jenkins, "vivek", "vivek");
createGithubPipeline(false);
}
/**
* Returns a {@link RepositoryUriResolver} according to credentials configuration.
*
* @param context the context within which to resolve the credentials.
* @param apiUri the API url
* @param credentialsId the credentials.
* @return a {@link RepositoryUriResolver}
*/
@NonNull
public static RepositoryUriResolver uriResolver(@CheckForNull Item context, @NonNull String apiUri,
@CheckForNull String credentialsId) {
if (credentialsId == null) {
return HTTPS;
} else {
StandardCredentials credentials = CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
StandardCredentials.class,
context,
context instanceof Queue.Task
? ((Queue.Task) context).getDefaultAuthentication()
: ACL.SYSTEM,
URIRequirementBuilder.create()
.withHostname(RepositoryUriResolver.hostnameFromApiUri(apiUri))
.build()
),
CredentialsMatchers.allOf(
CredentialsMatchers.withId(credentialsId),
CredentialsMatchers.instanceOf(StandardCredentials.class)
)
);
if (credentials instanceof SSHUserPrivateKey) {
return SSH;
} else {
// Defaults to HTTP/HTTPS
return HTTPS;
}
}
}
/**
* 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();
}
@RequirePOST
@Restricted(NoExternalUse.class)
public FormValidation doCheckScanCredentialsId(@CheckForNull @AncestorInPath Item context,
@QueryParameter String apiUri,
@QueryParameter String scanCredentialsId) {
return doCheckCredentialsId(context, apiUri, scanCredentialsId);
}
@Override
public void onDeleted(Item item) {
if (item instanceof WorkflowJob) {
WorkflowJob pipeline = (WorkflowJob) item;
onDeleted(pipeline);
} else {
LOGGER.log(Level.FINE, "Ignore onDeleted({0})", new Object[]{item});
}
}
@Override
public BluePipeline getPipeline(Item item, Reachable parent, BlueOrganization organization) {
if (item instanceof Job) {
return new AbstractPipelineImpl(organization, (Job) item);
}
return null;
}
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);
}
}
@Override
public void parseAssociatedNames(Item item, Collection<GitHubRepositoryName> result) {
if (!(item instanceof Job)) {
return;
}
Job job = (Job) item;
final GitHubBranchTrigger gitHubBranchTrigger = ghBranchTriggerFromJob(job);
if (nonNull(gitHubBranchTrigger)) {
result.add(gitHubBranchTrigger.getRepoFullName(job));
}
}
@Override public void onCopiedFrom(Item src) {
super.onCopiedFrom(src);
for (TopLevelItem item : ((MockFolder) src).getItems()) {
try {
copy(item, item.getName());
} catch (IOException x) {
assert false : x;
}
}
}
/**
* Can be useful to ignore disabled jobs on reregistering hooks
*
* @return predicate with true on apply if item is buildable
*/
public static <ITEM extends Item> Predicate<ITEM> isBuildable() {
return item -> {
if (item instanceof Job) {
return ((Job) item).isBuildable();
} else if (item instanceof ComputedFolder) {
return ((ComputedFolder) item).isBuildable();
}
return item instanceof BuildableItem;
};
}