下面列出了org.hamcrest.collection.IsArrayWithSize#hudson.model.TopLevelItem 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
/**
* 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;
}
@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;
}
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);
}
/**
* 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);
}
/**
* 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);
}
}
@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;
}
/**
* 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));
}
@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);
}
@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());
}
@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;
}
@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;
}
@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;
}
@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);
}
});
}
/**
* 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;
}
@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));
}
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;
}
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;
}
};
}
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;
}
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);
}
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;
}
@Override
public TopLevelItem getItem(String name) {
final TopLevelItem item = super.getItem(name);
if (item != null && item.hasPermission(Item.READ)) {
return item;
}
return null;
}
@Override public Collection<? extends Job> getAllJobs() {
Set<Job> jobs = new HashSet<Job>();
for (TopLevelItem i : getItems()) {
jobs.addAll(i.getAllJobs());
}
return jobs;
}
@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);
}
@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;
}
/**
* {@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;
}
/**
* {@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;
}
/**
* Creates a freestyle job from a YAML file and verifies that all fields in issue recorder are set correct.
*/
@Test
public void shouldCreateFreestyleJobUsingJobDslAndVerifyIssueRecorderWithValuesSet() {
configureJenkins("job-dsl-warnings-ng.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()).isTrue();
assertThat(recorder.getTrendChartType()).isEqualTo(TrendChartType.NONE);
assertThat(recorder.getBlameDisabled()).isTrue();
assertThat(recorder.getForensicsDisabled()).isTrue();
assertThat(recorder.getEnabledForFailure()).isTrue();
assertThat(recorder.getHealthy()).isEqualTo(10);
assertThat(recorder.getId()).isEqualTo("test-id");
assertThat(recorder.getIgnoreFailedBuilds()).isFalse();
assertThat(recorder.getIgnoreQualityGate()).isTrue();
assertThat(recorder.getMinimumSeverity()).isEqualTo("ERROR");
assertThat(recorder.getName()).isEqualTo("test-name");
assertThat(recorder.getSourceCodeEncoding()).isEqualTo("UTF-8");
assertThat(recorder.getUnhealthy()).isEqualTo(50);
assertThat(recorder.getReferenceJobName()).isEqualTo("test-job");
assertThat(recorder.getQualityGates()).hasSize(1);
List<Tool> tools = recorder.getTools();
assertThat(tools).hasSize(2);
assertThat(tools.get(0)).isInstanceOf(Java.class);
}
public TopLevelItem createProject(final TopLevelItemDescriptor type, final String name, final boolean notify) throws IOException {
return this.mixin.createProject(type, name, notify);
}
public TopLevelItem createProjectFromXML(final String name, final InputStream xml) throws IOException {
return this.mixin.createProjectFromXML(name, xml);
}