|
| 1 | +/* |
| 2 | + * Licensed under MIT License |
| 3 | + * Copyright (c) 2017 Bernhard Grünewaldt |
| 4 | + */ |
| 5 | +package io.codeclou.jenkins.github.webhook.notifier.plugin; |
| 6 | + |
| 7 | +import com.google.gson.Gson; |
| 8 | +import com.google.gson.JsonSyntaxException; |
| 9 | +import hudson.Plugin; |
| 10 | +import hudson.util.HttpResponses; |
| 11 | +import jenkins.model.Jenkins; |
| 12 | +import org.apache.commons.httpclient.HttpClient; |
| 13 | +import org.apache.commons.httpclient.HttpMethod; |
| 14 | +import org.apache.commons.httpclient.methods.GetMethod; |
| 15 | +import org.kohsuke.stapler.HttpResponse; |
| 16 | +import org.kohsuke.stapler.StaplerRequest; |
| 17 | +import org.kohsuke.stapler.interceptor.RequirePOST; |
| 18 | + |
| 19 | +import javax.servlet.ServletException; |
| 20 | +import javax.servlet.http.HttpServletRequest; |
| 21 | +import java.io.BufferedReader; |
| 22 | +import java.io.IOException; |
| 23 | + |
| 24 | + |
| 25 | +public class GithubWebhookNotifierPlugin extends Plugin { |
| 26 | + |
| 27 | + /* |
| 28 | + * http://jenkins.foo/plugin/github-webhook-notifier-plugin/receive |
| 29 | + */ |
| 30 | + @RequirePOST |
| 31 | + public HttpResponse doReceive(HttpServletRequest request, StaplerRequest staplerRequest) throws IOException, ServletException { |
| 32 | + String jeninsRootUrl = Jenkins.getInstance().getRootUrl(); // will return something like: http://localhost:8080/jenkins/ |
| 33 | + BufferedReader reader = request.getReader(); |
| 34 | + Gson gson = new Gson(); |
| 35 | + try { |
| 36 | + GithubWebhookPayload githubWebhookPayload = gson.fromJson(reader, GithubWebhookPayload.class); |
| 37 | + String gitPluginNotifyUrl = jeninsRootUrl + |
| 38 | + "git/notifyCommit?" + |
| 39 | + githubWebhookPayload.getRepository().getClone_url() + |
| 40 | + "&branches=" + |
| 41 | + githubWebhookPayload.getRef() + |
| 42 | + "&sha1=" + |
| 43 | + githubWebhookPayload.getAfter(); |
| 44 | + HttpClient client = new HttpClient(); |
| 45 | + HttpMethod method = new GetMethod(gitPluginNotifyUrl); |
| 46 | + int statusCode = client.executeMethod(method); |
| 47 | + String responseText = "triggered: " + gitPluginNotifyUrl + "\nstatus: " + statusCode; |
| 48 | + if (statusCode != 200) { |
| 49 | + return HttpResponses.error(400, responseText); |
| 50 | + } |
| 51 | + return HttpResponses.plainText(responseText); |
| 52 | + } catch (JsonSyntaxException ex) { |
| 53 | + return HttpResponses.error(500, "json invalid"); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments