jenkins.branch.MultiBranchProject Java Examples

The following examples show how to use jenkins.branch.MultiBranchProject. 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: 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 #2
Source File: BitbucketServerScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketServerScm.ID, alice);

    StaplerRequest staplerRequest = mockStapler();

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new BitbucketServerScmContentProvider().getContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #3
Source File: GitLabSCMItemListener.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 6 votes vote down vote up
private boolean updateBranchBuildStrategies(MultiBranchProject<?, ?> project) {
    boolean changed = false;

    for (BranchSource branchSource : project.getSources()) {
        if (GitLabSCMBranchBuildStrategy.INSTANCE.isApplicable(branchSource)) {
            List<BranchBuildStrategy> strategies = new ArrayList<>(branchSource.getBuildStrategies());
            if (!strategies.contains(GitLabSCMBranchBuildStrategy.INSTANCE)) {
                strategies.add(GitLabSCMBranchBuildStrategy.INSTANCE);
                branchSource.setBuildStrategies(strategies);
                changed = true;
            }
        }
    }

    return changed;
}
 
Example #4
Source File: BitbucketCloudScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private MultiBranchProject mockMbp(String credentialId, User user) {
    MultiBranchProject mbp = mock(MultiBranchProject.class);
    when(mbp.getName()).thenReturn("pipeline1");
    when(mbp.getParent()).thenReturn(j.jenkins);
    BitbucketSCMSource scmSource = mock(BitbucketSCMSource.class);
    when(scmSource.getServerUrl()).thenReturn(apiUrl);
    when(scmSource.getCredentialsId()).thenReturn(credentialId);
    when(scmSource.getRepoOwner()).thenReturn(USER_UUID);
    when(scmSource.getRepository()).thenReturn("demo1");
    when(mbp.getSCMSources()).thenReturn(Lists.<SCMSource>newArrayList(scmSource));

    //mock blueocean credential provider stuff
    BlueOceanCredentialsProvider.FolderPropertyImpl folderProperty = mock(BlueOceanCredentialsProvider.FolderPropertyImpl.class);
    DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor> properties = new DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor>(mbp);
    properties.add(new BlueOceanCredentialsProvider.FolderPropertyImpl(
            user.getId(), credentialId,
            BlueOceanCredentialsProvider.createDomain(apiUrl)
    ));
    Domain domain = mock(Domain.class);
    when(domain.getName()).thenReturn(BitbucketCloudScm.DOMAIN_NAME);
    when(folderProperty.getDomain()).thenReturn(domain);

    when(mbp.getProperties()).thenReturn(properties);
    return mbp;
}
 
Example #5
Source File: BitbucketCloudScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketCloudScm.ID, "cloud", alice);

    StaplerRequest staplerRequest = mockStapler();

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new BitbucketCloudScmContentProvider().getContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #6
Source File: BitbucketServerScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private MultiBranchProject mockMbp(String credentialId, User user) {
    MultiBranchProject mbp = mock(MultiBranchProject.class);
    when(mbp.getName()).thenReturn("pipeline1");
    when(mbp.getParent()).thenReturn(j.jenkins);
    BitbucketSCMSource scmSource = mock(BitbucketSCMSource.class);
    when(scmSource.getServerUrl()).thenReturn(apiUrl);
    when(scmSource.getCredentialsId()).thenReturn(credentialId);
    when(scmSource.getRepoOwner()).thenReturn("TESTP");
    when(scmSource.getRepository()).thenReturn("pipeline-demo-test");
    when(mbp.getSCMSources()).thenReturn(Lists.<SCMSource>newArrayList(scmSource));

    //mock blueocean credential provider stuff
    BlueOceanCredentialsProvider.FolderPropertyImpl folderProperty = mock(BlueOceanCredentialsProvider.FolderPropertyImpl.class);
    DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor> properties = new DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor>(mbp);
    properties.add(new BlueOceanCredentialsProvider.FolderPropertyImpl(
            user.getId(), credentialId,
            BlueOceanCredentialsProvider.createDomain(apiUrl)
    ));
    Domain domain = mock(Domain.class);
    when(domain.getName()).thenReturn(BitbucketServerScm.DOMAIN_NAME);
    when(folderProperty.getDomain()).thenReturn(domain);

    when(mbp.getProperties()).thenReturn(properties);
    return mbp;
}
 
Example #7
Source File: GitPipelineCreateRequestTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void createPipeline() throws UnirestException, IOException {
    User user = login("vivek", "Vivek Pandey", "[email protected]");
    Map r = new PipelineBaseTest.RequestBuilder(baseUrl)
        .status(201)
        .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
        .crumb( crumb )
        .post("/organizations/jenkins/pipelines/")
        .data(ImmutableMap.of("name", "pipeline1",
            "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
            "scmConfig", ImmutableMap.of("id", GitScm.ID, "uri", sampleRepo.toString())))
        .build(Map.class);
    assertNotNull(r);
    assertEquals("pipeline1", r.get("name"));

    MultiBranchProject mbp = (MultiBranchProject) j.getInstance().getItem("pipeline1");
    GitSCMSource source = (GitSCMSource) mbp.getSCMSources().get(0);
    List<SCMSourceTrait> traits = source.getTraits();

    Assert.assertNotNull(SCMTrait.find(traits, BranchDiscoveryTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, CleanAfterCheckoutTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, CleanBeforeCheckoutTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, LocalBranchTrait.class));
}
 
Example #8
Source File: GithubScmContentProvider.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public String getApiUrl(@Nonnull Item item) {
    if (item instanceof OrganizationFolder) {
        List<SCMNavigator> navigators = ((OrganizationFolder) item).getSCMNavigators();
        if ((!navigators.isEmpty() && navigators.get(0) instanceof GitHubSCMNavigator)) {
            return ((GitHubSCMNavigator) navigators.get(0)).getApiUri();
        }
    } else if (item instanceof MultiBranchProject) {
        List<SCMSource> sources = ((MultiBranchProject) item).getSCMSources();
        if ((!sources.isEmpty() && sources.get(0) instanceof GitHubSCMSource)) {
            return ((GitHubSCMSource) sources.get(0)).getApiUri();
        }
    }

    return null;
}
 
Example #9
Source File: GithubPipelineCreateRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
protected SCMSource createSource(@Nonnull MultiBranchProject project, @Nonnull BlueScmConfig scmConfig) {
    // Update endpoint only if its GitHub Enterprise
    if(scmConfig.getId().equals(GithubEnterpriseScm.ID)) {
        updateEndpoints(scmConfig.getUri());
    }

    Set<ChangeRequestCheckoutStrategy> strategies = new HashSet<>();
    strategies.add(ChangeRequestCheckoutStrategy.MERGE);

    return new GitHubSCMSourceBuilder(null, scmConfig.getUri(), computeCredentialId(scmConfig),
            (String)scmConfig.getConfig().get("repoOwner"),
            (String)scmConfig.getConfig().get("repository"))
            .withTrait(new BranchDiscoveryTrait(true, true)) //take all branches
            .withTrait(new ForkPullRequestDiscoveryTrait(strategies, new ForkPullRequestDiscoveryTrait.TrustPermission()))
            .withTrait(new OriginPullRequestDiscoveryTrait(strategies))
            .withTrait(new CleanBeforeCheckoutTrait())
            .withTrait(new CleanAfterCheckoutTrait())
            .withTrait(new LocalBranchTrait())
            .build();
}
 
Example #10
Source File: GithubIssue.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public Collection<BlueIssue> getIssues(ChangeLogSet.Entry changeSetEntry) {
    Job job = changeSetEntry.getParent().getRun().getParent();
    if (!(job.getParent() instanceof MultiBranchProject)) {
        return null;
    }
    MultiBranchProject mbp = (MultiBranchProject)job.getParent();
    List<SCMSource> scmSources = (List<SCMSource>) mbp.getSCMSources();
    SCMSource source = scmSources.isEmpty() ? null : scmSources.get(0);
    if (!(source instanceof GitHubSCMSource)) {
        return null;
    }
    GitHubSCMSource gitHubSource = (GitHubSCMSource)source;
    String apiUri =  gitHubSource.getApiUri();
    final String repositoryUri = new HttpsRepositoryUriResolver().getRepositoryUri(apiUri, gitHubSource.getRepoOwner(), gitHubSource.getRepository());
    Collection<BlueIssue> results = new ArrayList<>();
    for (String input : findIssueKeys(changeSetEntry.getMsg())) {
        String uri = repositoryUri.substring(0, repositoryUri.length() - 4);
        results.add(new GithubIssue("#" + input, String.format("%s/issues/%s", uri, input)));
    }
    return results;
}
 
Example #11
Source File: GithubEnterpriseScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private void testScmSourceProperties(String mockedApiUrl) throws Exception {
    String credentialId = createGithubEnterpriseCredential();
    MultiBranchProject mbp = mockMbp(credentialId, user, GithubEnterpriseScm.DOMAIN_NAME);
    // ensure the enterprise provider works with enterprise org folder
    ScmContentProvider provider = new GithubEnterpriseScmContentProvider();
    assertTrue("github enterprise provider should support github enterprise org folder", provider.support(mbp));
    assertEquals(GithubEnterpriseScm.ID, provider.getScmId());
    assertEquals(githubApiUrl, provider.getApiUrl(mbp));

    // ensure the enterprise provider doesn't support cloud org folder
    credentialId = createGithubCredential(user);
    mbp = mockMbp(credentialId, user, GithubScm.DOMAIN_NAME);
    // unfortunately overriding the GitHub apiUrl for WireMock returns a "localhost" URL here, so we mock the call
    when(((GitHubSCMSource) mbp.getSCMSources().get(0)).getApiUri()).thenReturn(mockedApiUrl);
    assertFalse("github enterprise provider should not support github org folder", provider.support(mbp));
}
 
Example #12
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentForMbpShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice, GithubEnterpriseScm.DOMAIN_NAME);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #13
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentForMbpGHEShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubEnterpriseCredential(alice);

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice, GithubEnterpriseScm.DOMAIN_NAME);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #14
Source File: GithubMockBase.java    From blueocean-plugin with MIT License 6 votes vote down vote up
protected MultiBranchProject mockMbp(String credentialId,User user, String credentialDomainName){
    MultiBranchProject mbp = mock(MultiBranchProject.class);
    when(mbp.getName()).thenReturn("PR-demo");
    when(mbp.getParent()).thenReturn(j.jenkins);
    GitHubSCMSource scmSource = mock(GitHubSCMSource.class);
    when(scmSource.getApiUri()).thenReturn(githubApiUrl);
    when(scmSource.getCredentialsId()).thenReturn(credentialId);
    when(scmSource.getRepoOwner()).thenReturn("cloudbeers");
    when(scmSource.getRepository()).thenReturn("PR-demo");
    when(mbp.getSCMSources()).thenReturn(Lists.<SCMSource>newArrayList(scmSource));
    BlueOceanCredentialsProvider.FolderPropertyImpl folderProperty = mock(BlueOceanCredentialsProvider.FolderPropertyImpl.class);
    DescribableList<AbstractFolderProperty<?>,AbstractFolderPropertyDescriptor> mbpProperties = new DescribableList<AbstractFolderProperty<?>,AbstractFolderPropertyDescriptor>(mbp);
    mbpProperties.add(new BlueOceanCredentialsProvider.FolderPropertyImpl(
            user.getId(), credentialId,
            BlueOceanCredentialsProvider.createDomain(githubApiUrl)
    ));
    Domain domain = mock(Domain.class);
    when(domain.getName()).thenReturn(credentialDomainName);
    when(folderProperty.getDomain()).thenReturn(domain);
    when(mbp.getProperties()).thenReturn(mbpProperties);
    return mbp;
}
 
Example #15
Source File: AbstractMultiBranchCreateRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public BluePipeline create(@Nonnull BlueOrganization organization, @Nonnull Reachable parent) throws IOException {
    validateInternal(getName(), scmConfig, organization);
    MultiBranchProject project = createMultiBranchProject(organization);
    assignCredentialToProject(scmConfig, project);
    SCMSource source = createSource(project, scmConfig).withId("blueocean");
    project.setSourcesList(ImmutableList.of(new BranchSource(source)));
    source.afterSave();
    project.save();
    final boolean hasJenkinsfile = repoHasJenkinsFile(source);
    if(!hasJenkinsfile){
        sendMultibranchIndexingCompleteEvent(project, 5);
        AbstractScmSourceEvent scmSourceEvent = getScmSourceEvent(project, source);
        if(scmSourceEvent != null) {
            SCMSourceEvent.fireNow(scmSourceEvent);
        }
    }else{
        project.scheduleBuild(new Cause.UserIdCause());
    }
    return BluePipelineFactory.getPipelineInstance(project, OrganizationFactory.getInstance().getContainingOrg(project.getItemGroup()));
}
 
Example #16
Source File: AbstractMultiBranchCreateRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private void _sendMultibranchIndexingCompleteEvent(MultiBranchProject mbp, int iterations) {
    try {
        SimpleMessage msg = new SimpleMessage();
        msg.set("jenkins_object_type", "org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject");
        msg.set("job_run_status","ALLOCATED");
        msg.set("job_name",mbp.getName());
        msg.set("jenkins_org","jenkins");
        msg.set("job_orgfolder_indexing_status","COMPLETE");
        msg.set("job_run_queueId","1");
        msg.set("jenkins_object_name",mbp.getName());
        msg.set("blueocean_job_rest_url","/blue/rest/organizations/jenkins/pipelines/"+mbp.getName()+"/");
        msg.set("jenkins_event","job_run_queue_task_complete");
        msg.set("job_multibranch_indexing_result","SUCCESS");
        msg.set("blueocean_job_pipeline_name",mbp.getName());
        msg.set("jenkins_object_url","job/"+mbp.getName()+"/");
        msg.set("jenkins_channel","job");
        msg.set("jenkinsfile_present","false");
        PubsubBus.getBus().publish(msg);
    } catch (MessageException e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: GithubIssueTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void changeSetEntryIsNotGithub() throws Exception {
    MultiBranchProject project = mock(MultiBranchProject.class);
    Job job = mock(MockJob.class);
    Run run = mock(Run.class);
    ChangeLogSet logSet = mock(ChangeLogSet.class);
    ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class);

    when(project.getProperties()).thenReturn(new DescribableList(project));
    when(entry.getParent()).thenReturn(logSet);
    when(logSet.getRun()).thenReturn(run);
    when(run.getParent()).thenReturn(job);
    when(job.getParent()).thenReturn(project);

    when(entry.getMsg()).thenReturn("Closed #123 #124");
    when(project.getSCMSources()).thenReturn(Lists.newArrayList(new GitSCMSource("http://example.com/repo.git")));

    Collection<BlueIssue> resolved = BlueIssueFactory.resolve(entry);
    Assert.assertEquals(0, resolved.size());
}
 
Example #18
Source File: ScmContentProviderParams.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public ScmContentProviderParams(Item item) {
    String apiUrl = null;
    String owner=null;
    String repo = null;
    if (item instanceof OrganizationFolder) {
        List<SCMNavigator> navigators = ((OrganizationFolder) item).getSCMNavigators();
        if (!navigators.isEmpty()) {
            SCMNavigator navigator = navigators.get(0);
            apiUrl = apiUrl(navigator);
            owner = owner(navigator);
        }
    } else if (item instanceof MultiBranchProject) {
        List<SCMSource> sources = ((MultiBranchProject) item).getSCMSources();
        if (!sources.isEmpty()) {
            SCMSource source = sources.get(0);
            apiUrl = apiUrl(source);
            owner = owner(source);
            repo = repo(source);
        }
    }
    this.apiUrl = apiUrl == null ? GitHubSCMSource.GITHUB_URL : apiUrl;;
    this.owner = owner;
    this.repo = repo;
    this.credentials = getCredentialForUser(item, this.apiUrl);;
}
 
Example #19
Source File: GitHubSourceContext.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private void forceScheduling(GitHubSCMRevision scmRevision) throws IOException {
    SCMSourceOwner owner = source.getOwner();
    if (owner instanceof MultiBranchProject) {
        MultiBranchProject mb = (MultiBranchProject) owner;
        BranchProjectFactory pf = mb.getProjectFactory();

        SCMHead scmHead = scmRevision.getHead();
        Job j = mb.getItemByBranchName(scmHead.getName());
        if (j != null) {
            SCMRevision rev = pf.getRevision(j);
            // set current rev to dummy to force scheduling
            if (rev != null && rev.equals(scmRevision)) {
                pf.setRevisionHash(j, new DummyRevision(scmHead));
            }
        }
    }
}
 
Example #20
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentForOrgFolderShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);

    StaplerRequest staplerRequest = mockStapler();

    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubScm.DOMAIN_NAME);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #21
Source File: MultiBranchPipelineImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public MultiBranchPipelineImpl getPipeline(Item item, Reachable parent, BlueOrganization organization) {
    if (item instanceof MultiBranchProject) {
        MultiBranchPipelineImpl mbpi = new MultiBranchPipelineImpl(organization, (MultiBranchProject) item);
        if (item instanceof WorkflowMultiBranchProject) {
            WorkflowMultiBranchProject wfmbp = (WorkflowMultiBranchProject)item;
            BranchProjectFactory<WorkflowJob, WorkflowRun> bpf = wfmbp.getProjectFactory();
            if (bpf instanceof WorkflowBranchProjectFactory) {
                String sp = ((WorkflowBranchProjectFactory) bpf).getScriptPath();
                mbpi.setScriptPath(sp);
            }
        }
        return mbpi;
    }
    return null;
}
 
Example #22
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToOrgFolderShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);


    StaplerRequest staplerRequest = mockStapler();

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));
    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #23
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void saveContentToOrgFolderGHE() throws UnirestException, IOException {
    String credentialId = createGithubEnterpriseCredential();

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(credentialId, user, GithubEnterpriseScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    GithubFile file = (GithubFile) new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    assertEquals("Jenkinsfile", file.getContent().getName());
    assertEquals("e23b8ef5c2c4244889bf94db6c05cc08ea138aef", file.getContent().getSha());
    assertEquals("PR-demo", file.getContent().getRepo());
    assertEquals("cloudbeers", file.getContent().getOwner());
}
 
Example #24
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToOrgFolderGHEShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubEnterpriseCredential(alice);


    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubEnterpriseScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));
    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #25
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToMbpGHEShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubEnterpriseCredential(alice);

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubEnterpriseScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #26
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void saveContentToMbpMissingBranch() throws UnirestException, IOException {
    String credentialId = createGithubCredential(user);

    StaplerRequest staplerRequest = mockStapler();

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test2").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(credentialId, user, GithubScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test2\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    GithubFile file = (GithubFile) new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    assertEquals("Jenkinsfile", file.getContent().getName());
    assertEquals("e23b8ef5c2c4244889bf94db6c05cc08ea138aef", file.getContent().getSha());
    assertEquals("PR-demo", file.getContent().getRepo());
    assertEquals("cloudbeers", file.getContent().getOwner());
}
 
Example #27
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private void testScmSourceProperties(String mockedApiUrl) throws Exception {
    // ensure the cloud provider works with cloud org folder
    String credentialId = createGithubCredential(user);
    MultiBranchProject mbp = mockMbp(credentialId, user, GithubScm.DOMAIN_NAME);
    // unfortunately overriding the GitHub apiUrl for WireMock returns a "localhost" URL here, so we mock the call
    when(((GitHubSCMSource) mbp.getSCMSources().get(0)).getApiUri()).thenReturn(mockedApiUrl);
    ScmContentProvider provider = new GithubScmContentProvider();
    assertTrue("github provider should support github multi-branch folder", provider.support(mbp));
    assertEquals(GithubScm.ID, provider.getScmId());
    assertEquals(mockedApiUrl, provider.getApiUrl(mbp));

    // ensure the cloud provider doesn't support enterprise org folder
    mbp = mockMbp(createGithubEnterpriseCredential(), user, GithubEnterpriseScm.DOMAIN_NAME);
    assertFalse("github provider should not support github enterprise org folder", provider.support(mbp));
}
 
Example #28
Source File: BitbucketCloudScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getContent() throws UnirestException, IOException {
    String credentialId = createCredential(BitbucketCloudScm.ID);
    StaplerRequest staplerRequest = mockStapler();
    MultiBranchProject mbp = mockMbp(credentialId);

    ScmFile<GitContent> content = (ScmFile<GitContent>) new BitbucketCloudScmContentProvider().getContent(staplerRequest, mbp);
    assertEquals("Jenkinsfile", content.getContent().getName());
    assertEquals("04553981a05754d4bffef56a59d9d996d500301c", content.getContent().getCommitId());
    assertEquals("demo1", content.getContent().getRepo());
    assertEquals(BbCloudWireMock.USER_UUID, content.getContent().getOwner());
}
 
Example #29
Source File: AbstractBitbucketScmContentProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@CheckForNull
protected BitbucketSCMSource getSourceFromItem(@Nonnull Item item) {
    if (item instanceof MultiBranchProject) {
        List<SCMSource> sources = ((MultiBranchProject) item).getSCMSources();
        if (!sources.isEmpty() && sources.get(0) instanceof BitbucketSCMSource) {
            return (BitbucketSCMSource) sources.get(0);
        }
    }
    return null;
}
 
Example #30
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void saveContentToMbpGHE() throws UnirestException, IOException {
    String credentialId = createGithubEnterpriseCredential();

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(credentialId, user, GithubEnterpriseScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    GithubFile file = (GithubFile) new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    assertEquals("Jenkinsfile", file.getContent().getName());
    assertEquals("e23b8ef5c2c4244889bf94db6c05cc08ea138aef", file.getContent().getSha());
    assertEquals("PR-demo", file.getContent().getRepo());
    assertEquals("cloudbeers", file.getContent().getOwner());
}