private void handlePullRequestEvent(String payload) throws IOException {

    GitHub gitHub = createGitHub(JSONObject.fromObject(payload));

    if (gitHub == null) {
      return;
    }

    GHEventPayload.PullRequest pullRequest =
        gitHub.parseEventPayload(new StringReader(payload), GHEventPayload.PullRequest.class);

    if (SUPPORTED_EVENTS.contains(pullRequest.getAction())) {
      Authentication old = SecurityContextHolder.getContext().getAuthentication();
      SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
      try {
        for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
          PullRequestBuildTrigger trigger = job.getTrigger(PullRequestBuildTrigger.class);
          if (trigger != null && trigger.getBuildHandler() instanceof PullRequestBuildHandler) {
            ((PullRequestBuildHandler) trigger.getBuildHandler()).handle(pullRequest, gitHub);
          }
        }
      } finally {
        SecurityContextHolder.getContext().setAuthentication(old);
      }
    } else {
      LOGGER.warning(
          MessageFormat.format(
              "Unsupported pull request action: ''{0}''", pullRequest.getAction()));
    }
  }
  private void handleIssueCommentEvent(String payload) throws IOException {

    GitHub gitHub = createGitHub(JSONObject.fromObject(payload));

    if (gitHub == null) {
      return;
    }

    GHEventPayload.IssueComment issueComment =
        gitHub.parseEventPayload(new StringReader(payload), GHEventPayload.IssueComment.class);

    if (LOGGER.isLoggable(Level.FINER)) {
      LOGGER.finer(
          MessageFormat.format(
              "Comment on {0} from {1}: {2}",
              issueComment.getIssue().getUrl(),
              issueComment.getComment().getUser(),
              issueComment.getComment().getBody()));
    }

    if (!"created".equals(issueComment.getAction())) {
      if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.finer("Unsupported issue_comment action: " + issueComment.getAction());
      }
      return;
    }

    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {
      for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
        PullRequestBuildTrigger trigger = job.getTrigger(PullRequestBuildTrigger.class);
        if (trigger != null && trigger.getBuildHandler() instanceof PullRequestBuildHandler) {
          ((PullRequestBuildHandler) trigger.getBuildHandler()).handle(issueComment, gitHub);
        }
      }
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
  }
  private void configureGit(GitHubRepositoryName gitHubRepoName, PullRequestBuildTrigger trigger)
      throws IOException {

    if (project.getScm() instanceof GitSCM) {
      GitSCM git = (GitSCM) project.getScm();
      List<UserRemoteConfig> userRemoteConfigs = new ArrayList<UserRemoteConfig>();

      if (git.getUserRemoteConfigs().isEmpty()
          || (git.getUserRemoteConfigs().size() == 1
              && StringUtils.isBlank(git.getUserRemoteConfigs().get(0).getUrl()))) {

        LOGGER.info(
            MessageFormat.format(
                "Git is selected as SCM of project {0} but not yet configured, configuring it",
                project.getFullName()));

        String url =
            MessageFormat.format(
                "https://{0}/{1}/{2}.git",
                gitHubRepoName.getHost(),
                gitHubRepoName.getUserName(),
                gitHubRepoName.getRepositoryName());

        userRemoteConfigs.add(
            new UserRemoteConfig(url, "origin", "+refs/pull/*:refs/remotes/origin/pr/*", null));

        List<BranchSpec> branches = new ArrayList<BranchSpec>();

        branches.add(new BranchSpec("${PR_COMMIT}"));
        GitSCM updatedGit =
            new GitSCM(
                userRemoteConfigs,
                branches,
                git.isDoGenerateSubmoduleConfigurations(),
                git.getSubmoduleCfg(),
                git.getBrowser(),
                git.getGitTool(),
                git.getExtensions());

        project.setScm(updatedGit);

        LOGGER.info(
            MessageFormat.format(
                "Git is configured to work with {0}", trigger.getDescriptor().getDisplayName()));
      }
    }
  }
  public PullRequestBuildHandler(AbstractProject<?, ?> project, boolean newTrigger)
      throws IOException {
    this.project = project;

    final GithubProjectProperty property = project.getProperty(GithubProjectProperty.class);

    if (property == null
        || property.getProjectUrl() == null
        || StringUtils.isBlank(property.getProjectUrl().baseUrl())) {

      throw new IOException(
          MessageFormat.format(
              "GitHub project URL must be specified for project {0}", project.getFullName()));
    }

    String gitHubProjectUrl = property.getProjectUrl().baseUrl().trim();
    GitHubRepositoryName gitHubRepoName = GitHubRepositoryName.create(gitHubProjectUrl);
    if (gitHubRepoName == null) {
      throw new IOException(
          MessageFormat.format("Invalid GitHub project URL specified: {0}", gitHubProjectUrl));
    }

    GHRepository repo = gitHubRepoName.resolveOne();
    if (repo == null) {
      LOGGER.severe(
          MessageFormat.format(
              "Cannot connect to {0}. Please check your registered GitHub credentials",
              gitHubRepoName));

      gitHubRepositoryUrl = gitHubProjectUrl;
    } else {
      gitHubRepositoryUrl = repo.getHtmlUrl().toString();
    }
    if (!gitHubRepositoryUrl.endsWith("/")) {
      gitHubRepositoryUrl += '/';
    }

    PullRequestBuildTrigger trigger = project.getTrigger(PullRequestBuildTrigger.class);
    triggerPhrasePattern = Pattern.compile(trigger.getTriggerPhrase(), Pattern.CASE_INSENSITIVE);
    if (StringUtils.isNotBlank(trigger.getWhitelist())) {
      Set<String> entries = new HashSet<String>();
      for (String entry : trigger.getWhitelist().split(",")) {
        if (StringUtils.isNotBlank(entry)) {
          entries.add(entry);
        }
      }
      if (!entries.isEmpty()) {
        whitelist = entries;
      }
    }

    if (newTrigger) {
      configureGit(gitHubRepoName, trigger);

      // The construction of webhook URL requires Jenkins root URL which might be null if it is not
      // manually
      // configured and it is retrieved in a separate thread without request context. So the webhook
      // URL is first
      // retrieved here.
      PullRequestBuildTrigger.DescriptorImpl descriptor =
          (PullRequestBuildTrigger.DescriptorImpl)
              Jenkins.getInstance().getDescriptor(PullRequestBuildTrigger.class);

      final String webhookUrl =
          StringUtils.isBlank(descriptor.getWebHookExternalUrl())
              ? descriptor.getWebHookUrl()
              : descriptor.getWebHookExternalUrl();

      if (webhookUrl == null) {
        LOGGER.warning(
            MessageFormat.format(
                "Cannot add webhook to GitHub repository {0}. "
                    + "Please configure Jenkins URL or Webhook External URL for {1}",
                gitHubRepositoryUrl, descriptor.getDisplayName()));

      } else {
        LOGGER.info(
            MessageFormat.format(
                "Adding webhook {0} to GitHub repository {1}", webhookUrl, gitHubRepositoryUrl));

        sequentialExecutionQueue.execute(
            new Runnable() {

              public void run() {
                try {
                  createWebHook(webhookUrl);
                } catch (Throwable ex) {
                  LOGGER.log(
                      Level.SEVERE,
                      MessageFormat.format(
                          "Error adding webhook to GitHub repository {0}", gitHubRepositoryUrl),
                      ex);
                }
              }
            });
      }
    }
  }
  void handle(GHEventPayload.IssueComment issueComment, GitHub gitHub) throws IOException {
    // check the trigger phrase
    PullRequestBuildTrigger trigger = project.getTrigger(PullRequestBuildTrigger.class);
    if (StringUtils.isBlank(trigger.getTriggerPhrase())) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("No trigger phrase configured for project: " + project.getDisplayName());
      }
      return;
    }

    String issueUrl = issueComment.getIssue().getHtmlUrl().toString();
    if (!issueUrl.startsWith(gitHubRepositoryUrl)) {
      LOGGER.finest(
          MessageFormat.format(
              "GitHub issue {0} is not related to project {1}. "
                  + "GitHub project URL configured for project {1}: {2}",
              issueUrl, project.getFullName(), gitHubRepositoryUrl));

      return;
    }

    String commentBody = issueComment.getComment().getBody();
    if (!triggerPhrasePattern.matcher(commentBody).find()) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("No trigger phrase matching on comment: " + commentBody);
      }
      return;
    }

    GHUser buildRequester = issueComment.getComment().getUser();
    if (!isWhitelisted(buildRequester, gitHub)) {
      LOGGER.info(
          MessageFormat.format(
              "GitHub user {0} is not in the whitelist of project {1}",
              buildRequester.getLogin(), project.getFullName()));

      return;
    }

    final int prNumber = issueComment.getIssue().getNumber();

    GHPullRequest pullRequest = issueComment.getRepository().getPullRequest(prNumber);
    // Updating PR to force the cache (if present) to refresh:
    pullRequest.setTitle(pullRequest.getTitle());

    pullRequest = issueComment.getRepository().getPullRequest(prNumber);

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("ghPullRequest = " + getPullRequestAsString(pullRequest));
    }

    if (pullRequest.getState() == GHIssueState.OPEN) {
      PullRequestData pullRequestData =
          PullRequestManager.getInstance().addPullRequestData(pullRequest, project);

      cancelBuilds(pullRequestData);
      build(pullRequest, buildRequester, new TriggerCause(pullRequest, buildRequester));
    } else if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine(
          MessageFormat.format(
              "Pull request {0} is not opened, no build is triggered",
              pullRequest.getHtmlUrl().toString()));
    }
  }