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()));
    }
  }
  public void doIndex(StaplerRequest req, StaplerResponse resp) {
    String event = req.getHeader("X-GitHub-Event");
    String payload = req.getParameter("payload");
    if (payload == null) {
      logger.log(Level.SEVERE, "Request doesn't contain payload.");
      return;
    }

    GhprbGitHub gh = GhprbTrigger.getDscp().getGitHub();

    logger.log(Level.INFO, "Got payload event: {0}", event);
    try {
      if ("issue_comment".equals(event)) {
        GHEventPayload.IssueComment issueComment =
            gh.get()
                .parseEventPayload(new StringReader(payload), GHEventPayload.IssueComment.class);
        for (GhprbRepository repo : getRepos(issueComment.getRepository())) {
          repo.onIssueCommentHook(issueComment);
        }
      } else if ("pull_request".equals(event)) {
        GHEventPayload.PullRequest pr =
            gh.get().parseEventPayload(new StringReader(payload), GHEventPayload.PullRequest.class);
        for (GhprbRepository repo : getRepos(pr.getPullRequest().getRepository())) {
          repo.onPullRequestHook(pr);
        }
      } else {
        logger.log(Level.WARNING, "Request not known");
      }
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Failed to parse github hook payload.", ex);
    }
  }
  void handle(GHEventPayload.PullRequest prEventPayload, GitHub gitHub) throws IOException {
    GHPullRequest pullRequest = prEventPayload.getPullRequest();
    String pullRequestUrl = pullRequest.getHtmlUrl().toString();
    if (!pullRequestUrl.startsWith(gitHubRepositoryUrl)) {
      LOGGER.config(
          MessageFormat.format(
              "Pull request {0} is not related to project {1}. "
                  + "GitHub project URL configured for project {1}: {2}",
              pullRequestUrl, project.getFullName(), gitHubRepositoryUrl));
      return;
    }

    LOGGER.info(
        MessageFormat.format(
            "Handling event ''{0}'' of pull request {1} for project {2}",
            prEventPayload.getAction(), pullRequestUrl, project.getFullName()));

    PullRequestManager pullRequestManager = PullRequestManager.getInstance();
    PullRequestData pullRequestData =
        pullRequestManager.getPullRequestData(pullRequestUrl, project);

    if (PullRequestManager.PullRequestAction.CLOSED.equals(prEventPayload.getAction())) {
      if (pullRequestData != null) {
        cancelBuilds(pullRequestData);
        deleteInstances(pullRequest);
      } else {
        LOGGER.warning(
            "No previous data available for received Pull Request 'close' event: "
                + pullRequestUrl);
      }
      return;
    }

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

      return;
    }

    boolean startBuild = false;

    if (pullRequestData == null) {
      if (PullRequestManager.PullRequestAction.SYNCHRONIZE.equals(prEventPayload.getAction())) {
        LOGGER.info(
            MessageFormat.format(
                "Updated pull request {0} was not built previously", pullRequestUrl));
      }
      pullRequestData = pullRequestManager.addPullRequestData(pullRequest, project);
      startBuild = pullRequestData.getLastUpdated().equals(pullRequest.getUpdatedAt());

    } else if (pullRequestData.update(pullRequest)) {
      pullRequestData.save();
      startBuild = true;
    }

    if (LOGGER.isLoggable(Level.FINEST)) {
      LOGGER.finest("Received event payload: " + prEventPayload);
    }

    if (startBuild) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(
            "Cancelling previous running builds and starting new build for Pull request: "
                + pullRequestData);
      }
      cancelBuilds(pullRequestData);
      build(pullRequest, null, new TriggerCause(prEventPayload));

    } else if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("No new build has been triggered for Pull request: " + pullRequestData);
    }
  }