Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the option to notify culprits by looking them up in the Hipchat user API #19

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion README.markdown
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
## HipChat plugin for Jenkins

Started with a fork of the Campfire plugin:

https://github.com/jgp/hudson_campfire_plugin
10 changes: 10 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
Expand All @@ -77,6 +83,10 @@
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
76 changes: 59 additions & 17 deletions src/main/java/jenkins/plugins/hipchat/ActiveNotifier.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
package jenkins.plugins.hipchat;

import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.CauseAction;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.*;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.AffectedFile;
import hudson.scm.ChangeLogSet.Entry;
import hudson.tasks.Mailer;

import org.apache.commons.lang.StringUtils;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import jenkins.model.Jenkins;

@SuppressWarnings("rawtypes")
Expand All @@ -31,7 +26,7 @@ public ActiveNotifier(HipChatNotifier notifier) {
this.notifier = notifier;
}

private HipChatService getHipChat(AbstractBuild r) {
private HipChatService getHipChat() {
return notifier.newHipChatService();
}

Expand All @@ -49,12 +44,12 @@ public void started(AbstractBuild build) {
message.append(cause.getShortDescription());
notifyStart(build, message.appendOpenLink().toString());
} else {
notifyStart(build, getBuildStatusMessage(build));
notifyStart(build, getBuildStatusMessage(build, null));
}
}

private void notifyStart(AbstractBuild build, String message) {
getHipChat(build).publish(message, "green");
getHipChat().publish(message, "green");
}

public void finalized(AbstractBuild r) {
Expand All @@ -71,7 +66,39 @@ public void completed(AbstractBuild r) {
|| (result == Result.SUCCESS && previousResult == Result.FAILURE && notifier.isNotifyBackToNormal())
|| (result == Result.SUCCESS && notifier.isNotifySuccess())
|| (result == Result.UNSTABLE && notifier.isNotifyUnstable())) {
getHipChat(r).publish(getBuildStatusMessage(r), getBuildColor(r));
getHipChat().publish(getBuildStatusMessage(r, fetchCulpritsIfWanted(r)), getBuildColor(r));
}
}

private List<String> fetchCulpritsIfWanted(AbstractBuild r) {
if (notifier.isIncludeCulprits()) {
return getCulpritsInHipchat(r);
} else {
return null;
}
}

private List<String> getCulpritsInHipchat(AbstractBuild r) {
List<String> hipchatUsernames = new ArrayList<String>();
for(Object userObj : r.getCulprits()) {
User user = (User)userObj;
logger.log(Level.FINE, "Looking up mention name for user {0}", user);
Mailer.UserProperty mailProperty = (user).getProperty(Mailer.UserProperty.class);
if(mailProperty != null && !StringUtils.isEmpty(mailProperty.getAddress())) {
hipchatUsernames.add(buildMentionNameFromEmail(mailProperty));
}else{
hipchatUsernames.add(user.getFullName());
}
}
return hipchatUsernames;
}

private String buildMentionNameFromEmail(Mailer.UserProperty mailProperty) {
String mentionName = getHipChat().getMentionNameForEmail(mailProperty.getAddress());
if (mentionName != null) {
return "@" + mentionName;
} else {
return mailProperty.getAddress();
}
}

Expand Down Expand Up @@ -122,10 +149,11 @@ static String getBuildColor(AbstractBuild r) {
}
}

String getBuildStatusMessage(AbstractBuild r) {
String getBuildStatusMessage(AbstractBuild r, List<String> culpritsInHipchat) {
MessageBuilder message = new MessageBuilder(r);
message.appendStatusMessage();
message.appendDuration();
message.appendCulprits(culpritsInHipchat);
return message.appendOpenLink().toString();
}

Expand Down Expand Up @@ -179,8 +207,11 @@ private MessageBuilder startMessage() {
}

public MessageBuilder appendOpenLink() {
String url = Jenkins.getInstance().getRootUrl() + build.getUrl();
message.append(" (<a href='").append(url).append("'>Open</a>)");
message.append(" (<a href='");
if (Jenkins.getInstance() != null) {
message.append(Jenkins.getInstance().getRootUrl());
}
message.append(build.getUrl()).append("'>Open</a>)");
return this;
}

Expand All @@ -190,6 +221,17 @@ public MessageBuilder appendDuration() {
return this;
}

public MessageBuilder appendCulprits(List<String> culprits) {
if(culprits != null && culprits.size()>0) {
message.append(" Committers: ");
for (String hipchatUsername : culprits) {
message.append(hipchatUsername);
message.append(" ");
}
}
return this;
}

@Override
public String toString() {
return message.toString();
Expand Down
17 changes: 14 additions & 3 deletions src/main/java/jenkins/plugins/hipchat/HipChatNotifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,12 @@ public class HipChatNotifier extends Notifier {
private boolean notifyUnstable;
private boolean notifyFailure;
private boolean notifyBackToNormal;
private boolean includeCulprits;

@DataBoundConstructor
public HipChatNotifier(String room, boolean startNotification, boolean notifySuccess, boolean notifyAborted,
boolean notifyNotBuilt, boolean notifyUnstable, boolean notifyFailure, boolean notifyBackToNormal) {
boolean notifyNotBuilt, boolean notifyUnstable, boolean notifyFailure, boolean notifyBackToNormal,
boolean includeCulprits) {
this.room = room;
this.startNotification = startNotification;
this.notifySuccess = notifySuccess;
Expand All @@ -49,6 +51,7 @@ public HipChatNotifier(String room, boolean startNotification, boolean notifySuc
this.notifyUnstable = notifyUnstable;
this.notifyFailure = notifyFailure;
this.notifyBackToNormal = notifyBackToNormal;
this.includeCulprits = includeCulprits;
}

public boolean isStartNotification() {
Expand Down Expand Up @@ -107,6 +110,14 @@ public void setNotifyBackToNormal(boolean notifyBackToNormal) {
this.notifyBackToNormal = notifyBackToNormal;
}

public boolean isIncludeCulprits() {
return includeCulprits;
}

public void setIncludeCulprits(boolean includeCulprits) {
this.includeCulprits = includeCulprits;
}

public String getRoom() {
return StringUtils.isBlank(room) ? getDescriptor().getRoom() : room;
}
Expand Down Expand Up @@ -151,15 +162,15 @@ public boolean prebuild(AbstractBuild<?, ?> build, BuildListener listener) {
logger.info("Invoking Started...");
new ActiveNotifier(this).started(build);
}
return super.prebuild(build, listener);
return true;
}

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
logger.info("Invoking Completed...");
new ActiveNotifier(this).completed(build);
return super.perform(build, launcher, listener);
return true;
}

@Extension
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/jenkins/plugins/hipchat/HipChatService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ public interface HipChatService {
void publish(String message);

void publish(String message, String color);

String getMentionNameForEmail(String email);
}
63 changes: 53 additions & 10 deletions src/main/java/jenkins/plugins/hipchat/StandardHipChatService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

import hudson.ProxyConfiguration;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import java.util.logging.Level;
Expand All @@ -14,19 +18,25 @@ public class StandardHipChatService implements HipChatService {
private static final Logger logger = Logger.getLogger(StandardHipChatService.class.getName());
private static final String[] DEFAULT_ROOMS = new String[0];

private final HttpClient httpClient;
private final String server;
private final String token;
private final String[] roomIds;
private final String sendAs;

public StandardHipChatService(String server, String token, String roomIds, String sendAs) {
StandardHipChatService(HttpClient httpClient, String server, String token, String roomIds, String sendAs) {
super();
this.httpClient = httpClient;
this.server = server;
this.token = token;
this.roomIds = roomIds == null ? DEFAULT_ROOMS : roomIds.split("\\s*,\\s*");
this.sendAs = sendAs;
}

public StandardHipChatService(String server, String token, String roomIds, String sendAs) {
this(null, server, token, roomIds, sendAs);
}

public void publish(String message) {
publish(message, "yellow");
}
Expand Down Expand Up @@ -58,24 +68,57 @@ public void publish(String message, String color) {
}
}

private HttpClient getHttpClient() {
HttpClient client = new HttpClient();

if (Jenkins.getInstance() != null) {
ProxyConfiguration proxy = Jenkins.getInstance().proxy;

if (proxy != null) {
client.getHostConfiguration().setProxy(proxy.name, proxy.port);
public String getMentionNameForEmail(String email) {
HttpClient client = getHttpClient();
String url = "https://" + server + "/v1/users/show";
GetMethod get = new GetMethod(url);
get.setQueryString(new NameValuePair[] {
new NameValuePair("user_id", email),
new NameValuePair("auth_token", token)
});

try {
int responseCode = client.executeMethod(get);
if (responseCode == HttpStatus.SC_OK) {
return parseMentionNameFromUserResponse(get.getResponseBodyAsString());
} else {
logger.log(Level.WARNING, "HipChat user lookup has failed with error: {0}", get.getResponseBodyAsString());
return null;
}
} catch (Exception e) {
logger.log(Level.WARNING, "Error looking up user from HipChat", e);
return null;
} finally {
get.releaseConnection();
}
}

return client;
private HttpClient getHttpClient() {
if (httpClient != null) {
return httpClient;
} else {
HttpClient client = new HttpClient();

if (Jenkins.getInstance() != null) {
ProxyConfiguration proxy = Jenkins.getInstance().proxy;

if (proxy != null) {
client.getHostConfiguration().setProxy(proxy.name, proxy.port);
}
}

return client;
}
}

private String shouldNotify(String color) {
return color.equalsIgnoreCase("green") ? "0" : "1";
}

private String parseMentionNameFromUserResponse(String response) {
return JSONObject.fromObject(response).getJSONObject("user").getString("mention_name");
}

public String getServer() {
return server;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,9 @@
<f:entry title="${%Notify Back To Normal}">
<f:checkbox name="hipchat.notifyBackToNormal" checked="${instance.notifyBackToNormal}" />
</f:entry>

<f:entry title="${%Notification to Include Culprits}">
<f:checkbox name="hipchat.includeCulprits" checked="${instance.includeCulprits}" />
</f:entry>
</f:section>
</j:jelly>
Loading