下面列出了怎么用hudson.model.Items的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
/**
* 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();
}
/**
* Common initialization that is invoked when either a new project is created with the constructor
* {@link TemplateDrivenMultiBranchProject#TemplateDrivenMultiBranchProject(ItemGroup, String)} or when a project
* is loaded from disk with {@link #onLoad(ItemGroup, String)}.
*/
protected void init3() {
if (disabledSubProjects == null) {
disabledSubProjects = new PersistedList<>(this);
}
// Owner doesn't seem to be set when loading from XML
disabledSubProjects.setOwner(this);
try {
XmlFile templateXmlFile = Items.getConfigFile(getTemplateDir());
if (templateXmlFile.getFile().isFile()) {
/*
* Do not use Items.load here, since it uses getRootDirFor(i) during onLoad,
* which returns the wrong location since template would still be unset.
* Instead, read the XML directly into template and then invoke onLoad.
*/
//noinspection unchecked
template = (P) templateXmlFile.read();
template.onLoad(this, TEMPLATE);
} else {
/*
* Don't use the factory here because newInstance calls setBranch, attempting
* to save the project before template is set. That would invoke
* getRootDirFor(i) and get the wrong directory to save into.
*/
template = newTemplate();
}
// Prevent tampering
if (!(template.getScm() instanceof NullSCM)) {
template.setScm(new NullSCM());
}
template.disable();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load template project " + getTemplateDir(), e);
}
}
/**
* This is a mirror of {@link hudson.model.AbstractItem#updateByXml(Source)} without the
* {@link hudson.model.listeners.SaveableListener#fireOnChange(Saveable, XmlFile)} trigger.
*
* @param project project to update by XML
* @param source source of XML
* @throws IOException if error performing update
*/
@SuppressWarnings("ThrowFromFinallyBlock")
private void updateByXml(final P project, Source source) throws IOException {
project.checkPermission(Item.CONFIGURE);
final String projectName = project.getName();
XmlFile configXmlFile = project.getConfigFile();
final AtomicFileWriter out = new AtomicFileWriter(configXmlFile.getFile());
try {
try {
XMLUtils.safeTransform(source, new StreamResult(out));
out.close();
} catch (SAXException | TransformerException e) {
throw new IOException("Failed to persist config.xml", e);
}
// try to reflect the changes by reloading
Object o = new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(project);
if (o != project) {
// ensure that we've got the same job type. extending this code to support updating
// to different job type requires destroying & creating a new job type
throw new IOException("Expecting " + project.getClass() + " but got " + o.getClass() + " instead");
}
Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<Void, IOException>() {
@SuppressWarnings("unchecked")
@Override
public Void call() throws IOException {
project.onLoad(project.getParent(), projectName);
return null;
}
});
Jenkins.getActiveInstance().rebuildDependencyGraphAsync();
// if everything went well, commit this new version
out.commit();
} finally {
out.abort();
}
}
/**
* Copied from {@link AbstractProject#updateByXml(javax.xml.transform.Source)}, removing the save event and
* returning the project after the update.
*/
@SuppressWarnings("unchecked")
public static AbstractProject updateProjectWithXmlSource(AbstractProject project, Source source) throws IOException {
XmlFile configXmlFile = project.getConfigFile();
AtomicFileWriter out = new AtomicFileWriter(configXmlFile.getFile());
try {
try {
// this allows us to use UTF-8 for storing data,
// plus it checks any well-formedness issue in the submitted
// data
Transformer t = TransformerFactory.newInstance()
.newTransformer();
t.transform(source,
new StreamResult(out));
out.close();
} catch (TransformerException e) {
throw new IOException2("Failed to persist configuration.xml", e);
}
// try to reflect the changes by reloading
new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(project);
project.onLoad(project.getParent(), project.getRootDir().getName());
Jenkins.getInstance().rebuildDependencyGraph();
// if everything went well, commit this new version
out.commit();
return ProjectUtils.findProject(project.getFullName());
} finally {
out.abort(); // don't leave anything behind
}
}
@Test public void moving() throws Exception {
MockFolder top = j.createFolder("top");
FreeStyleProject p = top.createProject(FreeStyleProject.class, "p");
MockFolder sub = top.createProject(MockFolder.class, "sub");
assertNews("created=top created=top/p created=top/sub");
Items.move(p, j.jenkins);
assertEquals(j.jenkins, p.getParent());
assertEquals(p, j.jenkins.getItem("p"));
assertNull(top.getItem("p"));
assertNews("moved=p;from=top/p");
Items.move(p, sub);
assertEquals(sub, p.getParent());
assertEquals(p, sub.getItem("p"));
assertNull(j.jenkins.getItem("p"));
assertNews("moved=top/sub/p;from=p");
Items.move(sub, j.jenkins);
assertEquals(sub, p.getParent());
assertEquals(p, sub.getItem("p"));
assertEquals(j.jenkins, sub.getParent());
assertEquals(sub, j.jenkins.getItem("sub"));
assertNull(top.getItem("sub"));
assertNews("moved=sub;from=top/sub moved=sub/p;from=top/sub/p");
Items.move(sub, top);
assertNews("moved=top/sub;from=sub moved=top/sub/p;from=sub/p");
assertEquals(sub, top.getItem("sub"));
sub.renameTo("lower");
assertNews("renamed=top/lower;from=sub moved=top/lower;from=top/sub moved=top/lower/p;from=top/sub/p");
top.renameTo("upper");
assertNews("renamed=upper;from=top moved=upper;from=top moved=upper/lower;from=top/lower moved=upper/lower/p;from=top/lower/p");
assertEquals(p, sub.getItem("p"));
p.renameTo("j");
assertNews("renamed=upper/lower/j;from=p moved=upper/lower/j;from=upper/lower/p");
top.renameTo("upperz");
assertNews("renamed=upperz;from=upper moved=upperz;from=upper moved=upperz/lower;from=upper/lower moved=upperz/lower/j;from=upper/lower/j");
assertEquals(sub, top.getItem("lower"));
sub.renameTo("upperzee");
assertNews("renamed=upperz/upperzee;from=lower moved=upperz/upperzee;from=upperz/lower moved=upperz/upperzee/j;from=upperz/lower/j");
Items.move(sub, j.jenkins);
assertNews("moved=upperzee;from=upperz/upperzee moved=upperzee/j;from=upperz/upperzee/j");
assertEquals(p, j.jenkins.getItemByFullName("upperzee/j"));
}
public DescriptorImpl() {
Items.XSTREAM2.addCompatibilityAlias("org.jenkinsci.plugins.pipeline.modeldefinition.config.FolderConfig", FolderConfig.class);
}
/**
* Gives this class an alias for configuration XML.
*/
@Initializer(before = InitMilestone.PLUGINS_STARTED)
@SuppressWarnings(UNUSED)
public static void registerXStream() {
Items.XSTREAM.alias("matrix-multi-branch-project", MatrixMultiBranchProject.class);
}
/**
* Gives this class an alias for configuration XML.
*/
@SuppressWarnings(UNUSED)
@Initializer(before = InitMilestone.PLUGINS_STARTED)
public static void registerXStream() {
Items.XSTREAM.alias("branch-list-view", BranchListView.class);
}
/**
* Gives this class an alias for configuration XML.
*/
@SuppressWarnings(UNUSED)
@Initializer(before = InitMilestone.PLUGINS_STARTED)
public static void registerXStream() {
Items.XSTREAM.alias("ivy-multi-branch-project", IvyMultiBranchProject.class);
}
/**
* Gives this class an alias for configuration XML.
*/
@Initializer(before = InitMilestone.PLUGINS_STARTED)
@SuppressWarnings("unused")
public static void registerXStream() {
Items.XSTREAM.alias("freestyle-multi-branch-project", FreeStyleMultiBranchProject.class);
}
/**
* Gives this class an alias for configuration XML.
*/
@Initializer(before = InitMilestone.PLUGINS_STARTED)
@SuppressWarnings(UNUSED)
public static void registerXStream() {
Items.XSTREAM.alias("maven-multi-branch-project", MavenMultiBranchProject.class);
}
@Override
public void start() throws Exception {
Items.XSTREAM.registerConverter(new Config.ConverterImpl());
load();
LOG.fine("Loading config: " + config);
}
@Initializer(before = InitMilestone.PLUGINS_STARTED)
public static void addAliases() {
Items.XSTREAM2.addCompatibilityAlias("hudson.plugins.humbug.HumbugNotifier", ZulipNotifier.class);
}