org.kohsuke.github.GitHub Java Examples

The following examples show how to use org.kohsuke.github.GitHub. 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: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 7 votes vote down vote up
private GitHub connectToGitHub() {
	if(gitHub == null) {
		try {
			Properties prop = new Properties();
			InputStream input = new FileInputStream("github-oauth.properties");
			prop.load(input);
			String oAuthToken = prop.getProperty("OAuthToken");
			if (oAuthToken != null) {
				gitHub = GitHub.connectUsingOAuth(oAuthToken);
				if(gitHub.isCredentialValid()) {
					logger.info("Connected to GitHub with OAuth token");
				}
			}
			else {
				gitHub = GitHub.connect();
			}
		} catch(FileNotFoundException e) {
			logger.warn("File github-oauth.properties was not found in RefactoringMiner's execution directory", e);
		} catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	return gitHub;
}
 
Example #2
Source File: GHPRMultiBranchSubscriber.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
protected void onEvent(GHSubscriberEvent event) {
    try {
        GitHub gh = GitHub.offline();

        PullRequestInfo ref = extractPullRequestInfo(event.getGHEvent(), event.getPayload(), gh);
        SCMHeadEvent.fireNow(new GitHubPullRequestScmHeadEvent(
                SCMEvent.Type.UPDATED,
                event.getTimestamp(),
                ref,
                ref.getRepo())
        );

    } catch (Exception e) {
        LOG.error("Can't process {} hook", event, e);
    }
}
 
Example #3
Source File: MembershipChecker.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
private boolean checkTeamMembershipUsingPersonalAccessToken(GHUser ghUser, AuthConfig authConfig, Map<String, List<String>> organizationAndTeamsAllowed) throws IOException {
    final GitHub gitHubForPersonalAccessToken = clientBuilder.from(authConfig.gitHubConfiguration());

    for (String organizationName : organizationAndTeamsAllowed.keySet()) {
        final GHOrganization organization = gitHubForPersonalAccessToken.getOrganization(organizationName);

        if (organization != null) {
            final List<String> allowedTeamsFromRole = organizationAndTeamsAllowed.get(organizationName);
            final Map<String, GHTeam> teamsFromGitHub = organization.getTeams();

            for (GHTeam team : teamsFromGitHub.values()) {
                if (allowedTeamsFromRole.contains(team.getName().toLowerCase()) && team.hasMember(ghUser)) {
                    LOG.info(format("[MembershipChecker] User `{0}` is a member of `{1}` team.", ghUser.getLogin(), team.getName()));
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example #4
Source File: Updater.java    From PYX-Reloaded with Apache License 2.0 6 votes vote down vote up
public static void update() throws IOException, SQLException {
    logger.info("Checking for a newer version...");
    Updater updater = new Updater(GitHub.connectAnonymously());
    if (updater.checkVersion()) {
        File backupDir = updater.doBackup();
        logger.info("Files have been backed up into " + backupDir.getAbsolutePath());

        File updateDir = new File(updater.currentFiles, ".update");
        if (!updateDir.exists() && !updateDir.mkdir())
            throw new IllegalStateException("Cannot create update directory: " + updateDir.getAbsolutePath());

        FileUtils.cleanDirectory(updateDir);

        File updateFiles = updater.downloadLatest(updateDir);
        updater.copyPreferences(updateFiles);
        updater.copyDatabase(updateFiles);

        updater.moveUpdatedFiles(updateFiles);
        FileUtils.deleteDirectory(updateDir);
        logger.info("The server has been updated successfully!");
        System.exit(0);
    }
}
 
Example #5
Source File: GitHubProvider.java    From gocd-build-status-notifier with Apache License 2.0 6 votes vote down vote up
GitHub createGitHubClient(String usernameToUse, String passwordToUse, String oauthAccessTokenToUse, String endPointToUse) throws Exception {
    LOGGER.info("Creating GitHub client"); 

    GitHub github = null;
    if (usernameAndPasswordIsAvailable(usernameToUse, passwordToUse)) {
        if (endPointIsAvailable(endPointToUse)) {
            github = GitHub.connectToEnterprise(endPointToUse, usernameToUse, passwordToUse);
        } else {
            github = GitHub.connectUsingPassword(usernameToUse, passwordToUse);
        }
    }
    if (oAuthTokenIsAvailable(oauthAccessTokenToUse)) {
        if (endPointIsAvailable(endPointToUse)) {
            github = GitHub.connectUsingOAuth(endPointToUse, oauthAccessTokenToUse);
        } else {
            github = GitHub.connectUsingOAuth(oauthAccessTokenToUse);
        }
    }
    if (github == null) {
        github = GitHub.connect();
    }
    return github;
}
 
Example #6
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Override
protected void doRun() throws Exception {
    // free any connection unused for the last 5 minutes
    long threshold = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5);
    synchronized (githubs) {
        for (Iterator<Map.Entry<GitHub, Long>> iterator = lastUsed.entrySet().iterator();
             iterator.hasNext(); ) {
            Map.Entry<GitHub, Long> entry = iterator.next();
            Long lastUse = entry.getValue();
            if (lastUse == null || lastUse < threshold) {
                iterator.remove();
                unused(entry.getKey());
            }
        }
    }
}
 
Example #7
Source File: GitHubAppCredentials.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@POST
@SuppressWarnings("unused") // stapler
@Restricted(NoExternalUse.class) // stapler
public FormValidation doTestConnection(
        @QueryParameter("appID") final String appID,
        @QueryParameter("privateKey") final String privateKey,
        @QueryParameter("apiUri") final String apiUri,
        @QueryParameter("owner") final String owner

) {
    GitHubAppCredentials gitHubAppCredential = new GitHubAppCredentials(
            CredentialsScope.GLOBAL, "test-id-not-being-saved", null,
            appID, Secret.fromString(privateKey)
    );
    gitHubAppCredential.setApiUri(apiUri);
    gitHubAppCredential.setOwner(owner);

    try {
        GitHub connect = Connector.connect(apiUri, gitHubAppCredential);
        return FormValidation.ok("Success, Remaining rate limit: " + connect.getRateLimit().getRemaining());
    } catch (Exception e) {
        return FormValidation.error(e, String.format(ERROR_AUTHENTICATING_GITHUB_APP, appID));
    }
}
 
Example #8
Source File: GitHubBuildStatusNotification.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Returns the GitHub Repository associated to a Job.
 *
 * @param job A {@link Job}
 * @return A {@link GHRepository} or {@code null}, if any of: a credentials was not provided; notifications were
 * disabled, or the job is not from a {@link GitHubSCMSource}.
 * @throws IOException
 */
@CheckForNull
private static GitHub lookUpGitHub(@NonNull Job<?,?> job) throws IOException {
    SCMSource src = SCMSource.SourceByItem.findSource(job);
    if (src instanceof GitHubSCMSource) {
        GitHubSCMSource source = (GitHubSCMSource) src;
        if (new GitHubSCMSourceContext(null, SCMHeadObserver.none())
                .withTraits(source.getTraits())
                .notificationsDisabled()) {
            return null;
        }
        if (source.getScanCredentialsId() != null) {
            return Connector.connect(source.getApiUri(), Connector.lookupScanCredentials
                    (job, source.getApiUri(), source.getScanCredentialsId()));
        }
    }
    return null;
}
 
Example #9
Source File: GetRolesExecutor.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse execute() throws IOException {
    if (request.getRoles().isEmpty()) {
        LOG.debug("[Get User Roles] Server sent empty roles config. Nothing to do!.");
        return DefaultGoPluginApiResponse.success("[]");
    }

    GitHub gitHub = clientBuilder.from(request.getAuthConfig().gitHubConfiguration());
    GHUser user = gitHub.getUser(request.getUsername());

    if (user == null) {
        LOG.error(format("[Get User Roles] User %s does not exist in GitHub.", request.getUsername()));
        return DefaultGoPluginApiResponse.error("");
    }

    List<String> roles = gitHubAuthorizer.authorize(user, request.getAuthConfig(), request.getRoles());

    LOG.debug(format("[Get User Roles] User %s has %s roles.", request.getUsername(), roles));
    return DefaultGoPluginApiResponse.success(GSON.toJson(roles));
}
 
Example #10
Source File: TestGitHubRepository.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
public static void deleteAllRepos(String repoPrefix, String gitHubUsername, String gitHubPassword)
    throws IOException {
  GitHub gitHub = GitHub.connectUsingPassword(gitHubUsername, gitHubPassword);

  gitHub
      .getMyself()
      .getAllRepositories()
      .keySet()
      .stream()
      .filter(repoName -> repoName.startsWith(repoPrefix))
      .forEach(
          repoName -> {
            String repoAddress = gitHubUsername + "/" + repoName;
            LOG.info("Removing repo " + repoAddress + "...");
            try {
              gitHub.getRepository(repoAddress).delete();
            } catch (IOException e) {
              e.printStackTrace();
            }
          });
}
 
Example #11
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
private static void ensureDetailedGHPullRequest(GHPullRequest pr, TaskListener listener, GitHub github, GHRepository ghRepository) throws IOException, InterruptedException {
    final long sleep = 1000;
    int retryCountdown = 4;

    Connector.checkApiRateLimit(listener, github);
    while (pr.getMergeable() == null && retryCountdown > 1) {
        listener.getLogger().format(
            "Waiting for GitHub to create a merge commit for pull request %d.  Retrying %d more times...%n",
            pr.getNumber(),
            retryCountdown);
        retryCountdown -= 1;
        Thread.sleep(sleep);
        Connector.checkApiRateLimit(listener, github);
    }


}
 
Example #12
Source File: GitHubSCMNavigator.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void afterSave(@NonNull SCMNavigatorOwner owner) {
    GitHubWebHook.get().registerHookFor(owner);
    try {
        // FIXME MINOR HACK ALERT
        StandardCredentials credentials = Connector.lookupScanCredentials((Item)owner, getApiUri(), credentialsId);
        GitHub hub = Connector.connect(getApiUri(), credentials);
        try {
            GitHubOrgWebHook.register(hub, repoOwner);
        } finally {
            Connector.release(hub);
        }
    } catch (IOException e) {
        DescriptorImpl.LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
}
 
Example #13
Source File: GitHubProvider.java    From gocd-oauth-login with Apache License 2.0 6 votes vote down vote up
private boolean isAMemberOfOrganization(GithubPluginSettings pluginSettings, User user) {
    try {
        GitHub github = getGitHub(pluginSettings);
        GHUser ghUser = github.getUser(user.getUsername());

        if(ghUser == null) return false;

        for(String orgName: pluginSettings.getGithubOrganizations()) {
            GHOrganization organization = github.getOrganization(orgName);

            if(organization != null && ghUser.isMemberOf(organization)){
                return true;
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Error occurred while trying to check if user is member of organization", e);
    }
    return false;
}
 
Example #14
Source File: GetRolesExecutorTest.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnSuccessResponseWithRoles() throws IOException, JSONException {
    GitHub gitHub = mock(GitHub.class);
    GHUser ghUser = mock(GHUser.class);

    when(clientBuilder.from(request.getAuthConfig().gitHubConfiguration())).thenReturn(gitHub);
    when(gitHub.getUser("bob")).thenReturn(ghUser);
    when(request.getRoles()).thenReturn(rolesWithName("blackbird", "super-admin", "view"));
    when(authorizer.authorize(ghUser, request.getAuthConfig(), request.getRoles())).thenReturn(Arrays.asList("blackbird", "super-admin"));

    GoPluginApiResponse response = executor.execute();

    assertThat(response.responseCode(), is(200));
    JSONAssert.assertEquals("[\"blackbird\",\"super-admin\"]", response.responseBody(), true);

    InOrder inOrder = inOrder(clientBuilder, gitHub, authorizer);
    inOrder.verify(clientBuilder).from(request.getAuthConfig().gitHubConfiguration());
    inOrder.verify(gitHub).getUser(request.getUsername());
    inOrder.verify(authorizer).authorize(ghUser, request.getAuthConfig(), request.getRoles());
}
 
Example #15
Source File: GetRolesExecutorTest.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnErrorResponseWhenUserWithProvidedUsernameNotFound() throws IOException {
    GitHub gitHub = mock(GitHub.class);

    when(clientBuilder.from(request.getAuthConfig().gitHubConfiguration())).thenReturn(gitHub);
    when(gitHub.getUser("bob")).thenReturn(null);
    when(request.getRoles()).thenReturn(rolesWithName("blackbird", "super-admin", "view"));

    GoPluginApiResponse response = executor.execute();

    assertThat(response.responseCode(), is(500));

    InOrder inOrder = inOrder(clientBuilder, gitHub);
    inOrder.verify(clientBuilder).from(request.getAuthConfig().gitHubConfiguration());
    inOrder.verify(gitHub).getUser(request.getUsername());
    verifyZeroInteractions(authorizer);
}
 
Example #16
Source File: GitHubProvider.java    From gocd-oauth-login with Apache License 2.0 6 votes vote down vote up
@Override
public List<User> searchUser(GithubPluginSettings pluginSettings, String searchTerm) {
    List<User> users = new ArrayList<User>();
    try {
        GitHub github = getGitHub(pluginSettings);

        PagedSearchIterable<GHUser> githubSearchResults = github.searchUsers().q(searchTerm).list();
        int count = 0;
        for (GHUser githubSearchResult : githubSearchResults) {
            users.add(new User(githubSearchResult.getLogin(), githubSearchResult.getName(), githubSearchResult.getEmail()));
            count++;

            if (count == 10) {
                break;
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Error occurred while trying to perform user search", e);
    }
    return users;
}
 
Example #17
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 #18
Source File: AbstractGHPullRequestSubsriber.java    From github-integration-plugin with MIT License 6 votes vote down vote up
protected PullRequestInfo extractPullRequestInfo(GHEvent event, String payload, GitHub gh) throws IOException {
    switch (event) {
        case ISSUE_COMMENT: {
            GHEventPayload.IssueComment commentPayload = gh.parseEventPayload(new StringReader(payload), GHEventPayload.IssueComment.class);

            int issueNumber = commentPayload.getIssue().getNumber();
            return new PullRequestInfo(commentPayload.getRepository().getFullName(), issueNumber);
        }

        case PULL_REQUEST: {
            GHEventPayload.PullRequest pr = gh.parseEventPayload(new StringReader(payload), GHEventPayload.PullRequest.class);

            return new PullRequestInfo(pr.getPullRequest().getRepository().getFullName(), pr.getNumber(), pr.getPullRequest().getBase().getRef());
        }

        default:
            throw new IllegalStateException(format("Did you add event %s in events() method?", event));
    }
}
 
Example #19
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
private static void unused(@Nonnull GitHub hub) {
    synchronized (githubs) {
        Integer count = usage.get(hub);
        if (count == null) {
            // it was untracked, forget about it
            return;
        }
        if (count <= 1) {
            // only remove if it is actually unused now
            // exclusive
            usage.remove(hub);
            // we could use multiple maps, but we expect only a handful of entries and mostly the shared path
            // so we can just walk the forward map
            for (Iterator<Map.Entry<Details, GitHub>> iterator = githubs.entrySet().iterator();
                 iterator.hasNext(); ) {
                Map.Entry<Details, GitHub> entry = iterator.next();
                if (hub == entry.getValue()) {
                    iterator.remove();
                    break;
                }
            }
        }
    }
}
 
Example #20
Source File: GitHubPluginRepoProvider2.java    From github-integration-plugin with MIT License 6 votes vote down vote up
private NullSafePredicate<GitHub> withPermission(final GitHubRepositoryName name, GHPermission permission) {
    return new NullSafePredicate<GitHub>() {
        @Override
        protected boolean applyNullSafe(@Nonnull GitHub gh) {
            try {
                final GHRepository repo = gh.getRepository(name.getUserName() + "/" + name.getRepositoryName());
                if (permission == GHPermission.ADMIN) {
                    return repo.hasAdminAccess();
                } else if (permission == GHPermission.PUSH) {
                    return repo.hasPushAccess();
                } else {
                    return repo.hasPullAccess();
                }
            } catch (IOException e) {
                return false;
            }
        }
    };
}
 
Example #21
Source File: AbstractRepairStep.java    From repairnator with MIT License 6 votes vote down vote up
protected void createPullRequest(String baseBranch,String newBranch) throws IOException, GitAPIException, URISyntaxException {
    GitHub github = RepairnatorConfig.getInstance().getGithub();

    GHRepository originalRepository = github.getRepository(this.getInspector().getRepoSlug());
    GHRepository ghForkedRepo = originalRepository.fork();

    String base = baseBranch;
    String head = ghForkedRepo.getOwnerName() + ":" + newBranch;

    System.out.println("base: " + base + " head:" + head);
    String travisURL = this.getInspector().getBuggyBuild() == null ? "" : Utils.getTravisUrl(this.getInspector().getBuggyBuild().getId(), this.getInspector().getRepoSlug());
    Map<String, String> values = new HashMap<String, String>();
    values.put("travisURL", travisURL);
    values.put("tools", String.join(",", this.getConfig().getRepairTools()));
    values.put("slug", this.getInspector().getRepoSlug());

    if (prText == null) {
        StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
        this.prText = sub.replace(DEFAULT_TEXT_PR);
    }

    GHPullRequest pullRequest = originalRepository.createPullRequest(prTitle, head, base, this.prText);
    String prURL = "https://github.com/" + this.getInspector().getRepoSlug() + "/pull/" + pullRequest.getNumber();
    this.getLogger().info("Pull request created on: " + prURL);
    this.getInspector().getJobStatus().addPRCreated(prURL);
}
 
Example #22
Source File: GitHubSCMFileSystem.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param gitHub the {@link GitHub}
 * @param repo the {@link GHRepository}
 * @param refName the ref name, e.g. {@code heads/branchName}, {@code tags/tagName}, {@code pull/N/head} or the SHA.
 * @param rev the optional revision.
 * @throws IOException if I/O errors occur.
 */
protected GitHubSCMFileSystem(GitHub gitHub, GHRepository repo, String refName, @CheckForNull SCMRevision rev) throws IOException {
    super(rev);
    this.gitHub = gitHub;
    this.open = true;
    this.repo = repo;
    if (rev != null) {
        if (rev.getHead() instanceof PullRequestSCMHead) {
            PullRequestSCMRevision prRev = (PullRequestSCMRevision) rev;
            PullRequestSCMHead pr = (PullRequestSCMHead) prRev.getHead();
            if (pr.isMerge()) {
                this.ref = prRev.getMergeHash();
            } else {
                this.ref = prRev.getPullHash();
            }
        } else if (rev instanceof AbstractGitSCMSource.SCMRevisionImpl) {
            this.ref = ((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash();
        } else {
            this.ref = refName;
        }
    } else {
        this.ref = refName;
    }
}
 
Example #23
Source File: GithubConnector.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Inject
public GithubConnector(ApolloConfiguration apolloConfiguration) {
    try {
        logger.info("Initializing Github Connector");

        // If no user or oauth was provided, attempt to go anonymous
        if (StringUtils.isEmpty(apolloConfiguration.getScm().getGithubLogin()) || StringUtils.isEmpty(apolloConfiguration.getScm().getGithubOauthToken())) {
            logger.info("Trying to connect anonymously to GitHub");
            gitHub = GitHub.connectAnonymously();
            logger.info("Succeeded to connect anonymously to GitHub");
        } else {
            logger.info("Trying to connect to GitHub");
            gitHub = GitHub.connect(apolloConfiguration.getScm().getGithubLogin(), apolloConfiguration.getScm().getGithubOauthToken());
            logger.info("Succeeded to connect to GitHub");
        }
    } catch (IOException e) {
        throw new RuntimeException("Could not open connection to Github!", e);
    }
}
 
Example #24
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 #25
Source File: GitHubSCMNavigator.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
private GHOrganization getGhOrganization(final GitHub github) throws IOException {
    try {
        return github.getOrganization(repoOwner);
    } catch (RateLimitExceededException rle) {
        throw new AbortException(rle.getMessage());
    } catch (FileNotFoundException fnf) {
        // may be an user... ok to ignore
    }
    return null;
}
 
Example #26
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
private static GHRepository getRepoIfValid(String credentialsId, String gitApiUrl, String account, String repo, Item context) throws IOException {
    GitHub github = getGitHubIfValid(credentialsId, gitApiUrl, context);
    GHRepository repository = github.getUser(account).getRepository(repo);
    if (repository == null) {
        throw new IllegalArgumentException(INVALID_REPO);
    }
    return repository;
}
 
Example #27
Source File: GitHubBuildStatusNotification.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * Returns the GitHub Repository associated to a Job.
 *
 * @param job A {@link Job}
 * @return A {@link GHRepository} or null, either if a scan credentials was not provided, or a GitHubSCMSource was not defined.
 * @throws IOException
 */
@CheckForNull
private static GHRepository lookUpRepo(GitHub github, @NonNull Job<?,?> job) throws IOException {
    if (github == null) {
        return null;
    }
    SCMSource src = SCMSource.SourceByItem.findSource(job);
    if (src instanceof GitHubSCMSource) {
        GitHubSCMSource source = (GitHubSCMSource) src;
        if (source.getScanCredentialsId() != null) {
            return github.getRepository(source.getRepoOwner() + "/" + source.getRepository());
        }
    }
    return null;
}
 
Example #28
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 #29
Source File: GithubCurrentUserService.java    From DotCi with MIT License 5 votes vote down vote up
public GithubCurrentUserService(final GitHub gh) {
    this.gh = gh;
    try {
        this.user = gh.getMyself();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #30
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));
}