org.kohsuke.github.GitHubBuilder Java Examples

The following examples show how to use org.kohsuke.github.GitHubBuilder. 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: GithubNotificationConfig.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Constructs a config object from a {@link Run} object and GitHub builder.
 *
 * @param run the build
 * @param githubBuilder the GitHub builder
 * @return the constructed config object
 */
public static @Nullable GithubNotificationConfig fromRun(Run<?, ?> run, GitHubBuilder githubBuilder) {
    BuildStatusConfig buildStatusConfig = BuildStatusConfig.get();
    if (buildStatusConfig.getEnableGithub()) {
        try {
            GithubNotificationConfig result = new GithubNotificationConfig();
            result.githubBuilder = githubBuilder;
            if (!result.extractCommitSha(run)) {
                return null;
            }
            if (!result.extractBranchInfo(run)) {
                return null;
            }
            if (!result.extractGHRepositoryInfo(run)) {
                return null;
            }
            return result;
        } catch (IOException ex) {
            log(Level.SEVERE, ex);
        }
    }
    return null;
}
 
Example #2
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Nonnull
private static GitHubBuilder createGitHubBuilder(@Nonnull String apiUrl, @CheckForNull Cache cache) throws IOException {
    String host;
    try {
        host = new URL(apiUrl).getHost();
    } catch (MalformedURLException e) {
        throw new IOException("Invalid GitHub API URL: " + apiUrl, e);
    }

    GitHubBuilder gb = new GitHubBuilder();
    gb.withEndpoint(apiUrl);
    gb.withRateLimitHandler(CUSTOMIZED);

    OkHttpClient.Builder clientBuilder = baseClient.newBuilder();
    if (JenkinsJVM.isJenkinsJVM()) {
        clientBuilder.proxy(getProxy(host));
    }
    if (cache != null) {
        clientBuilder.cache(cache);
    }
    gb.withConnector(new OkHttpConnector(clientBuilder.build()));
    return gb;
}
 
Example #3
Source File: Configuration.java    From updatebot with Apache License 2.0 6 votes vote down vote up
public GitHub getGithub() throws IOException {
    if (github == null) {
        GitHubBuilder ghb = new GitHubBuilder();
        String username = getGithubUsername();
        String password = getGithubPassword();
        String token = getGithubToken();
        if (Strings.notEmpty(username) && Strings.notEmpty(password)) {
            ghb.withPassword(username, password);
        } else if (Strings.notEmpty(token)) {
            if (Strings.notEmpty(username)) {
                ghb.withOAuthToken(token, username);
            } else {
                ghb.withOAuthToken(token);
            }
        }
        ghb.withRateLimitHandler(RateLimitHandler.WAIT).
                withAbuseLimitHandler(AbuseLimitHandler.WAIT);
        this.github = ghb.build();
    }
    return this.github;
}
 
Example #4
Source File: CommandLine.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static DockerfileGitHubUtil initializeDockerfileGithubUtil(String gitApiUrl) throws IOException {
    if (gitApiUrl == null) {
        gitApiUrl = System.getenv("git_api_url");
        if (gitApiUrl == null) {
            throw new IOException("No Git API URL in environment variables.");
        }
    }
    String token = System.getenv("git_api_token");
    if (token == null) {
        log.error("Please provide GitHub token in environment variables.");
        System.exit(3);
    }

    GitHub github = new GitHubBuilder().withEndpoint(gitApiUrl)
            .withOAuthToken(token)
            .build();
    github.checkApiUrlValidity();

    GitHubUtil gitHubUtil = new GitHubUtil(github);

    return new DockerfileGitHubUtil(gitHubUtil);
}
 
Example #5
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutCommitMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness',  " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_COMMIT, b1);
}
 
Example #6
Source File: KohsukeGitHubServiceFactoryImpl.java    From launchpad-missioncontrol with Apache License 2.0 5 votes vote down vote up
@Override
public GitHubService create(final Identity identity) {

    // Precondition checks
    if (identity == null) {
        throw new IllegalArgumentException("Identity is required");
    }

    final GitHub gitHub;
    try {
        final GitHubBuilder ghb = new GitHubBuilder()
                .withConnector(new OkHttp3Connector(new OkHttpClient()));
        identity.accept(new IdentityVisitor() {
            @Override
            public void visit(TokenIdentity token) {
                ghb.withOAuthToken(token.getToken());
            }

            @Override
            public void visit(UserPasswordIdentity userPassword) {
                ghb.withPassword(userPassword.getUsername(), userPassword.getPassword());
            }
        });
        gitHub = ghb.build();
    } catch (final IOException ioe) {
        throw new RuntimeException("Could not create GitHub client", ioe);
    }
    final GitHubService ghs = new KohsukeGitHubServiceImpl(gitHub, identity);
    log.finest(() -> "Created backing GitHub client for identity using " + identity.getClass().getSimpleName());
    return ghs;
}
 
Example #7
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildEnterprise() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.when(ghb.withEndpoint("https://api.example.com")).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #8
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithFolderCredentials() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Folder f = jenkins.jenkins.createProject(Folder.class, "folder" + jenkins.jenkins.getItems().size());
    CredentialsStore folderStore = getFolderStore(f);
    folderStore.addCredentials(Domain.global(),
            new DummyCredentials(CredentialsScope.GLOBAL, "user", "password"));

    WorkflowJob p = f.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #9
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void build() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #10
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutCredentialsMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', repo: 'acceptance-test-harness'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
Example #11
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutRepoMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
Example #12
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutAccountMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "repo: 'acceptance-test-harness',  " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
Example #13
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithWrongCommitMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenThrow(IOException.class);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.INVALID_COMMIT, b1);
}
 
Example #14
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithWrongRepoMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(null);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);


    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.INVALID_REPO, b1);
}
 
Example #15
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
private static GitHub getGitHubIfValid(String credentialsId, String gitApiUrl, Item context) throws IOException {
    if (credentialsId == null || credentialsId.isEmpty()) {
        throw new IllegalArgumentException(NULL_CREDENTIALS_ID);
    }
    UsernamePasswordCredentials credentials = getCredentials(UsernamePasswordCredentials.class, credentialsId, context);
    if (credentials == null) {
        throw new IllegalArgumentException(CREDENTIALS_ID_NOT_EXISTS);
    }
    GitHubBuilder githubBuilder = new GitHubBuilder();

    githubBuilder.withOAuthToken(credentials.getPassword().getPlainText(), credentials.getUsername());

    if (gitApiUrl == null || gitApiUrl.isEmpty()) {
        githubBuilder = githubBuilder.withProxy(getProxy("https://api.github.com"));
    } else {
        githubBuilder = githubBuilder.withEndpoint(gitApiUrl);
        githubBuilder = githubBuilder.withProxy(getProxy(gitApiUrl));
    }

    GitHub github = githubBuilder.build();

    if (github.isCredentialValid()) {
        return github;
    } else {
        throw new IllegalArgumentException(CREDENTIALS_LOGIN_INVALID);
    }
}
 
Example #16
Source File: AllCommandTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@BeforeClass
public void setUp() throws Exception {
    String gitApiUrl = System.getenv("git_api_url");
    String token = System.getenv("git_api_token");
    github = new GitHubBuilder().withEndpoint(gitApiUrl)
            .withOAuthToken(token)
            .build();
    github.checkApiUrlValidity();
    gitHubUtil = new GitHubUtil(github);

    cleanBefore(REPOS, DUPLICATES_CREATED_BY_GIT_HUB, STORE_NAME, github);

    GHOrganization org = github.getOrganization(ORGS.get(0));
    initializeRepos(org, REPOS, IMAGE_1, createdRepos, gitHubUtil);

    GHRepository store = github.createRepository(STORE_NAME)
            .description("Delete if this exists. If it exists, then an integration test crashed somewhere.")
            .create();
    store.createContent("{\n  \"images\": {\n" +
            "    \"" + IMAGE_1 + "\": \"" + TEST_TAG + "\",\n" +
            "    \"" + IMAGE_2 + "\": \"" + TEST_TAG + "\"\n" +
            "  }\n" +
            "}",
            "Integration Testing", "store.json");
    createdRepos.add(store);

    for (String s: ORGS) {
        org = github.getOrganization(s);
        initializeRepos(org, DUPLICATES, IMAGE_2, createdRepos, gitHubUtil);
    }
    /* We need to wait because there is a delay on the search API used in the all command; it takes time
     * for the search API to pick up recently created repositories.
     */
    checkIfSearchUpToDate("image1", IMAGE_1, REPOS.size(), github);
    checkIfSearchUpToDate("image2", IMAGE_2, DUPLICATES.size() * ORGS.size(), github);
}
 
Example #17
Source File: GitHubClientBuilder.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
private GitHub clientFor(String personalAccessTokenOrUsersAccessToken, GitHubConfiguration gitHubConfiguration) throws IOException {
    if (gitHubConfiguration.authenticateWith() == AuthenticateWith.GITHUB_ENTERPRISE) {
        LOG.debug("Create GitHub connection to enterprise GitHub with token");
        return GitHub.connectToEnterprise(gitHubConfiguration.gitHubEnterpriseApiUrl(), personalAccessTokenOrUsersAccessToken);
    } else {
        LOG.debug("Create GitHub connection to public GitHub with token");
        return new GitHubBuilder()
                .withOAuthToken(personalAccessTokenOrUsersAccessToken).withRateLimitHandler(RateLimitHandler.FAIL).build();
    }
}
 
Example #18
Source File: GithubNotificationConfigTest.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
@Test
public void testConfigBranchSource() throws Exception {
    Run build = Mockito.mock(Run.class);
    SCMRevisionAction mockSCMRevisionAction = mock(SCMRevisionAction.class);
    when(build.getAction(SCMRevisionAction.class)).thenReturn(mockSCMRevisionAction);

    GitHubSCMSource source = mock(GitHubSCMSource.class);
    when(source.getCredentialsId()).thenReturn("git-user");
    when(source.getRepoOwner()).thenReturn("repo-owner");
    when(source.getRepository()).thenReturn("repo");
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision = new SCMRevisionImpl(head, "what-the-hash");
    when(mockSCMRevisionAction.getRevision()).thenReturn(revision);

    WorkflowMultiBranchProject mockProject = mock(WorkflowMultiBranchProject.class);
    WorkflowJob mockJob = new WorkflowJob(mockProject, "job-name");
    when(build.getParent()).thenReturn(mockJob);
    when(mockProject.getSCMSources()).thenReturn(Collections.singletonList(source));

    PowerMockito.mockStatic(CredentialsMatchers.class);
    when(CredentialsMatchers.firstOrNull(any(), any())).thenReturn(new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "user-pass", null, "git-user", "git-password"));

    GitHub github = mock(GitHub.class);
    GHUser mockUser = mock(GHUser.class);
    GHRepository mockRepo = mock(GHRepository.class);
    when(github.getUser(any())).thenReturn(mockUser);
    when(mockUser.getRepository(any())).thenReturn(mockRepo);
    GitHubBuilder builder = PowerMockito.mock(GitHubBuilder.class);

    PowerMockito.when(builder.withProxy(Matchers.<Proxy>anyObject())).thenReturn(builder);
    PowerMockito.when(builder.withOAuthToken(anyString(), anyString())).thenReturn(builder);
    PowerMockito.when(builder.build()).thenReturn(github);
    PowerMockito.when(builder.withEndpoint(any())).thenReturn(builder);

    GithubNotificationConfig instance = GithubNotificationConfig.fromRun(build, builder);
    assertEquals("what-the-hash", instance.getShaString());
    assertEquals("test-branch", instance.getBranchName());
}
 
Example #19
Source File: GitHubCodeSearcher.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
protected void connectToGitHub() throws Exception {		
	Properties properties = new TechrankWorkflowContext(workflow).getProperties();
	github = GitHubBuilder.fromProperties(properties).build();
}
 
Example #20
Source File: Connector.java    From github-branch-source-plugin with MIT License 4 votes vote down vote up
public static @Nonnull GitHub connect(@CheckForNull String apiUri, @CheckForNull StandardCredentials credentials) throws IOException {
    String apiUrl = Util.fixEmptyAndTrim(apiUri);
    apiUrl = apiUrl != null ? apiUrl : GitHubServerConfig.GITHUB_URL;
    String username;
    String password;
    String hash;
    String authHash;
    Jenkins jenkins = Jenkins.get();
    if (credentials == null) {
        username = null;
        password = null;
        hash = "anonymous";
        authHash = "anonymous";
    } else if (credentials instanceof StandardUsernamePasswordCredentials) {
        StandardUsernamePasswordCredentials c = (StandardUsernamePasswordCredentials) credentials;
        username = c.getUsername();
        password = c.getPassword().getPlainText();
        hash = Util.getDigestOf(password + SALT); // want to ensure pooling by credential
        authHash = Util.getDigestOf(password + "::" + jenkins.getLegacyInstanceId());
    } else {
        // TODO OAuth support
        throw new IOException("Unsupported credential type: " + credentials.getClass().getName());
    }
    synchronized (githubs) {
        Details details = new Details(apiUrl, hash);
        GitHub hub = githubs.get(details);
        if (hub != null) {
            Integer count = usage.get(hub);
            usage.put(hub, count == null ? 1 : Math.max(count + 1, 1));
            return hub;
        }

        Cache cache = getCache(jenkins, apiUrl, authHash, username);

        GitHubBuilder gb = createGitHubBuilder(apiUrl, cache);

        if (username != null) {
            gb.withPassword(username, password);
        }

        hub = gb.build();
        githubs.put(details, hub);
        usage.put(hub, 1);
        lastUsed.remove(hub);
        return hub;
    }
}
 
Example #21
Source File: FunnyGuilds.java    From FunnyGuilds with Apache License 2.0 4 votes vote down vote up
@Override
public void onEnable() {
    funnyguilds = this;
    if (this.forceDisabling) {
        return;
    }

    this.dataModel = DataModel.create(this, this.pluginConfiguration.dataModel);
    this.dataModel.load();

    this.dataPersistenceHandler = new DataPersistenceHandler(this);
    this.dataPersistenceHandler.startHandler();

    this.invitationPersistenceHandler = new InvitationPersistenceHandler(this);
    this.invitationPersistenceHandler.loadInvitations();
    this.invitationPersistenceHandler.startHandler();

    MetricsCollector collector = new MetricsCollector(this);
    collector.start();

    this.guildValidationTask = Bukkit.getScheduler().runTaskTimerAsynchronously(this, new GuildValidationHandler(), 100L, 20L);
    this.tablistBroadcastTask = Bukkit.getScheduler().runTaskTimerAsynchronously(this, new TablistBroadcastHandler(), 20L, this.pluginConfiguration.playerListUpdateInterval_);
    this.rankRecalculationTask = Bukkit.getScheduler().runTaskTimerAsynchronously(this, new RankRecalculationTask(), 20L, this.pluginConfiguration.rankingUpdateInterval_);

    PluginManager pluginManager = Bukkit.getPluginManager();
    pluginManager.registerEvents(new GuiActionHandler(), this);
    pluginManager.registerEvents(new EntityDamage(), this);
    pluginManager.registerEvents(new EntityInteract(), this);
    pluginManager.registerEvents(new PlayerChat(), this);
    pluginManager.registerEvents(new PlayerDeath(), this);
    pluginManager.registerEvents(new PlayerJoin(this), this);
    pluginManager.registerEvents(new PlayerLogin(), this);
    pluginManager.registerEvents(new PlayerQuit(), this);
    pluginManager.registerEvents(new GuildHeartProtectionHandler(), this);

    this.dynamicListenerManager.registerDynamic(() -> pluginConfiguration.regionsEnabled,
            new BlockBreak(),
            new BlockIgnite(),
            new BlockPlace(),
            new BucketAction(),
            new EntityExplode(),
            new HangingBreak(),
            new HangingPlace(),
            new PlayerCommand(),
            new PlayerInteract()
    );

    this.dynamicListenerManager.registerDynamic(() -> pluginConfiguration.regionsEnabled && pluginConfiguration.eventMove, new PlayerMove());
    this.dynamicListenerManager.registerDynamic(() -> pluginConfiguration.regionsEnabled && pluginConfiguration.eventPhysics, new BlockPhysics());
    this.dynamicListenerManager.registerDynamic(() -> pluginConfiguration.regionsEnabled && pluginConfiguration.respawnInBase, new PlayerRespawn());
    this.dynamicListenerManager.reloadAll();
    this.patch();

    try {
        this.githubAPI = new GitHubBuilder().build();
    }
    catch (IOException ex) {
        this.getPluginLogger().debug("Could not initialize GitHub API!");
        this.getPluginLogger().debug(Throwables.getStackTraceAsString(ex));
    }

    FunnyGuildsVersion.isNewAvailable(this.getServer().getConsoleSender(), true);
    PluginHook.init();

    FunnyGuilds.getInstance().getPluginLogger().info("~ Created by FunnyGuilds Team ~");
}
 
Example #22
Source File: GithubNotificationConfig.java    From github-autostatus-plugin with MIT License 2 votes vote down vote up
/**
 * Constructs a config object from a Run object.
 *
 * @param run the build
 * @return the GitHub config object
 */
public static @Nullable GithubNotificationConfig fromRun(Run<?, ?> run) {
    return GithubNotificationConfig.fromRun(run, new GitHubBuilder());
}
 
Example #23
Source File: Connector.java    From github-branch-source-plugin with MIT License 2 votes vote down vote up
/**
 * Creates a {@link GitHubBuilder} that can be used to build a {@link GitHub} instance.
 *
 * This method creates and configures a new {@link GitHubBuilder}.
 * This should be used only when {@link #connect(String, StandardCredentials)} cannot be used,
 * such as when using {@link GitHubBuilder#withJwtToken(String)} to getting the {@link GHAppInstallationToken}.
 *
 * This method intentionally does not support caching requests or {@link GitHub} instances.
 *
 * @param apiUrl the GitHub API URL to be used for the connection
 * @return a configured GitHubBuilder instance
 * @throws IOException if I/O error occurs
 */
static GitHubBuilder createGitHubBuilder(@Nonnull String apiUrl) throws IOException {
    return createGitHubBuilder(apiUrl, null);
}