Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
samrocketman authored Mar 11, 2017
2 parents 6fd550a + cf4adc0 commit dc50d4e
Show file tree
Hide file tree
Showing 7 changed files with 297 additions and 77 deletions.
6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
Expand Down
78 changes: 49 additions & 29 deletions src/main/java/jenkins/plugins/slack/StandardSlackService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,46 @@

import hudson.security.ACL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;

import org.jenkinsci.plugins.plaincredentials.StringCredentials;

import com.cloudbees.plugins.credentials.CredentialsMatcher;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;

import jenkins.model.Jenkins;
import hudson.ProxyConfiguration;

import org.apache.commons.lang.StringUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;

public class StandardSlackService implements SlackService {

Expand Down Expand Up @@ -76,23 +89,23 @@ public boolean publish(String message, String color) {
JSONArray attachments = new JSONArray();
attachments.put(attachment);

PostMethod post;
HttpPost post;
String url;
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//prepare post methods for both requests types
if (!botUser || !StringUtils.isEmpty(baseUrl)) {
url = "https://" + teamDomain + "." + host + "/services/hooks/jenkins-ci?token=" + getTokenToUse();
if (!StringUtils.isEmpty(baseUrl)) {
url = baseUrl + getTokenToUse();
}
post = new PostMethod(url);
post = new HttpPost(url);
JSONObject json = new JSONObject();

json.put("channel", roomId);
json.put("attachments", attachments);
json.put("link_names", "1");

post.addParameter("payload", json.toString());

nvps.add(new BasicNameValuePair("payload", json.toString()));
} else {
url = "https://slack.com/api/chat.postMessage?token=" + getTokenToUse() +
"&channel=" + roomId +
Expand All @@ -103,18 +116,22 @@ public boolean publish(String message, String color) {
} catch (UnsupportedEncodingException e) {
logger.log(Level.ALL, "Error while encoding attachments: " + e.getMessage());
}
post = new PostMethod(url);
post = new HttpPost(url);
}
logger.fine("Posting: to " + roomId + " on " + teamDomain + " using " + url + ": " + message + " " + color);
HttpClient client = getHttpClient();
post.getParams().setContentCharset("UTF-8");
CloseableHttpClient client = getHttpClient();

try {
int responseCode = client.executeMethod(post);
String response = post.getResponseBodyAsString();
if (responseCode != HttpStatus.SC_OK) {
logger.log(Level.WARNING, "Slack post may have failed. Response: " + response);
result = false;
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
CloseableHttpResponse response = client.execute(post);

int responseCode = response.getStatusLine().getStatusCode();
if(responseCode != HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
logger.log(Level.WARNING, "Slack post may have failed. Response: " + responseString);
logger.log(Level.WARNING, "Response Code: " + responseCode);
result = false;
} else {
logger.info("Posting succeeded");
}
Expand Down Expand Up @@ -143,31 +160,34 @@ private String getTokenToUse() {
}

private StringCredentials lookupCredentials(String credentialId) {
List<StringCredentials> credentials = CredentialsProvider.lookupCredentials(StringCredentials.class, Jenkins.getInstance(), ACL.SYSTEM, Collections.<DomainRequirement>emptyList());
List<StringCredentials> credentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(StringCredentials.class, Jenkins.getInstance(), ACL.SYSTEM, Collections.<DomainRequirement>emptyList());
CredentialsMatcher matcher = CredentialsMatchers.withId(credentialId);
return CredentialsMatchers.firstOrNull(credentials, matcher);
}

protected HttpClient getHttpClient() {
HttpClient client = new HttpClient();
protected CloseableHttpClient getHttpClient() {
final HttpClientBuilder clientBuilder = HttpClients.custom();
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
clientBuilder.setDefaultCredentialsProvider(credentialsProvider);

if (Jenkins.getInstance() != null) {
ProxyConfiguration proxy = Jenkins.getInstance().proxy;
if (proxy != null) {
client.getHostConfiguration().setProxy(proxy.name, proxy.port);
final HttpHost proxyHost = new HttpHost(proxy.name, proxy.port);
final HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
clientBuilder.setRoutePlanner(routePlanner);

String username = proxy.getUserName();
String password = proxy.getPassword();
// Consider it to be passed if username specified. Sufficient?
if (username != null && !"".equals(username.trim())) {
logger.info("Using proxy authentication (user=" + username + ")");
// http://hc.apache.org/httpclient-3.x/authentication.html#Proxy_Authentication
// and
// http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/BasicAuthenticationExample.java?view=markup
client.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
credentialsProvider.setCredentials(new AuthScope(proxyHost),
new UsernamePasswordCredentials(username, password));
}
}
}
return client;
return clientBuilder.build();
}

void setHost(String host) {
Expand Down
62 changes: 62 additions & 0 deletions src/test/java/jenkins/plugins/slack/CloseableHttpClientStub.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package jenkins.plugins.slack;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;

public class CloseableHttpClientStub extends CloseableHttpClient {

private int numberOfCallsToExecuteMethod;
private int httpStatus;
private boolean failAlternateResponses = false;

public CloseableHttpResponse execute(HttpUriRequest post) {
numberOfCallsToExecuteMethod++;
if (failAlternateResponses && (numberOfCallsToExecuteMethod % 2 == 0)) {
return new CloseableHttpResponseStub(HttpStatus.SC_NOT_FOUND);
} else {
return new CloseableHttpResponseStub(httpStatus);
}
}

@Override
public ClientConnectionManager getConnectionManager() {
return null;
}

@Override
public void close() throws IOException {

}

@Override
public HttpParams getParams() {
return null;
}

@Override
protected CloseableHttpResponse doExecute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException, ClientProtocolException {
return null;
}

public int getNumberOfCallsToExecuteMethod() {
return numberOfCallsToExecuteMethod;
}

public void setHttpStatus(int httpStatus) {
this.httpStatus = httpStatus;
}

public void setFailAlternateResponses(boolean failAlternateResponses) {
this.failAlternateResponses = failAlternateResponses;
}
}
Loading

0 comments on commit dc50d4e

Please sign in to comment.