Skip to content

Commit

Permalink
Introduce #createRequest(URI, JSONObject, UsernamePasswordCredentials)
Browse files Browse the repository at this point in the history
Goal is to create a simpler contract for alternative clients to
implement.
  • Loading branch information
sghill committed Oct 21, 2021
1 parent 6433af5 commit df02f57
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.jenkinsci.plugins.stashNotifier;

import org.apache.commons.lang.StringUtils;

import java.net.URI;

public class BuildStatusUriFactory {
private BuildStatusUriFactory() {
}

public static URI create(String baseUri, String commit) {
String tidyBase = StringUtils.removeEnd(baseUri.toString(), "/");
String uri = String.join("/", tidyBase, "rest/build-status/1.0/commits", commit);
return URI.create(uri);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
Expand Down Expand Up @@ -774,13 +775,16 @@ protected NotificationResult notifyStash(
final StashBuildState state) throws Exception {
StashBuildState buildStatus = getPushedBuildStatus(state);
JSONObject payload = createNotificationPayload(run, buildStatus, listener);
HttpEntity stashBuildNotificationEntity = new StringEntity(payload.toString(), "UTF-8");

String stashURL = expandStashURL(run, listener);

logger.println("Notifying Bitbucket at \"" + stashURL + "\"");

HttpPost req = createRequest(stashBuildNotificationEntity, run.getParent(), commitSha1, stashURL);
UsernamePasswordCredentials usernamePasswordCredentials
= getCredentials(UsernamePasswordCredentials.class, run.getParent());

URI uri = BuildStatusUriFactory.create(stashURL, commitSha1);
HttpPost req = createRequest(uri, payload, usernamePasswordCredentials);
try (CloseableHttpClient client = getHttpClient(logger, run, stashURL)) {
HttpResponse res = client.execute(req);
if (res.getStatusLine().getStatusCode() != 204) {
Expand Down Expand Up @@ -848,6 +852,8 @@ protected StashBuildState getPushedBuildStatus(StashBuildState currentBuildStatu
* Returns the HTTP POST request ready to be sent to the Bitbucket build API for
* the given run and change set.
*
* @see #createRequest(URI, JSONObject, UsernamePasswordCredentials)
* @deprecated in favor of method overload
* @param stashBuildNotificationEntity a entity containing the parameters for Bitbucket
* @param commitSha1 the SHA1 of the commit that was built
* @param url
Expand Down Expand Up @@ -884,6 +890,37 @@ protected HttpPost createRequest(
return req;
}

/**
* Returns the HTTP POST request ready to be sent to the Bitbucket build API for
* the given run and change set.
*
* @param uri uri for the POST request
* @param payload a entity containing the parameters for Bitbucket
* @param credentials the SHA1 of the commit that was built
* @return the HTTP POST request to the Bitbucket build API
*/
protected HttpPost createRequest(
final URI uri,
final JSONObject payload,
final UsernamePasswordCredentials credentials) throws AuthenticationException {

HttpPost req = new HttpPost(uri.toString());

if (credentials != null) {
req.addHeader(new BasicScheme().authenticate(
new org.apache.http.auth.UsernamePasswordCredentials(
credentials.getUsername(),
credentials.getPassword().getPlainText()),
req,
null));
}

req.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
req.setEntity(new StringEntity(payload.toString(), "UTF-8"));

return req;
}

private String expandStashURL(Run<?, ?> run, final TaskListener listener) {
String url = stashServerBaseUrl;
DescriptorImpl descriptor = getDescriptor();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package org.jenkinsci.plugins.stashNotifier;

import org.junit.Test;

import java.net.URI;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.*;

public class BuildStatusUriFactoryTest {

@Test
public void shouldHandleTrailingSlash() {
String baseUri = "http://localhost:12345/";
URI expected = URI.create("http://localhost:12345/rest/build-status/1.0/commits/25a4b3c9b494fc7ac65b80e3b0ecce63f235f20d");
URI actual = BuildStatusUriFactory.create(baseUri, "25a4b3c9b494fc7ac65b80e3b0ecce63f235f20d");
assertThat(actual, equalTo(expected));
}

@Test
public void shouldHandleNoTrailingSlash() {
String baseUri = "http://localhost:12345";
URI expected = URI.create("http://localhost:12345/rest/build-status/1.0/commits/25a4b3c9b494fc7ac65b80e3b0ecce63f235f20d");
URI actual = BuildStatusUriFactory.create(baseUri, "25a4b3c9b494fc7ac65b80e3b0ecce63f235f20d");
assertThat(actual, equalTo(expected));
}

@Test
public void shouldHandleBasePathTrailingSlash() {
String baseUri = "http://localhost:12345/some-path/";
URI expected = URI.create("http://localhost:12345/some-path/rest/build-status/1.0/commits/25a4b3c9b494fc7ac65b80e3b0ecce63f235f20d");
URI actual = BuildStatusUriFactory.create(baseUri, "25a4b3c9b494fc7ac65b80e3b0ecce63f235f20d");
assertThat(actual, equalTo(expected));
}

@Test
public void shouldHandleBasePathNoTrailingSlash() {
String baseUri = "http://localhost:12345/some-path";
URI expected = URI.create("http://localhost:12345/some-path/rest/build-status/1.0/commits/25a4b3c9b494fc7ac65b80e3b0ecce63f235f20d");
URI actual = BuildStatusUriFactory.create(baseUri, "25a4b3c9b494fc7ac65b80e3b0ecce63f235f20d");
assertThat(actual, equalTo(expected));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
import hudson.util.Secret;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import net.sf.json.JSONObject;
import org.acegisecurity.Authentication;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
Expand Down Expand Up @@ -46,6 +46,7 @@
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -579,7 +580,7 @@ public void test_createRequest() throws Exception {
when(CredentialsMatchers.firstOrNull(anyCollection(), any(CredentialsMatcher.class))).thenReturn(credential);

//when
HttpPost request = sn.createRequest(mock(HttpEntity.class), mock(Item.class), sha1, "http://localhost");
HttpPost request = sn.createRequest(URI.create("http://localhost"), new JSONObject(), credential);

//then
assertThat(request, is(not(nullValue())));
Expand Down Expand Up @@ -880,7 +881,7 @@ private NotificationResult notifyStash(int statusCode) throws Exception {
when(buildListener.getLogger()).thenReturn(logger);
doReturn("someKey1").when(sn).getBuildKey(eq(build), eq(buildListener));
HttpPost httpPost = mock(HttpPost.class);
doReturn(httpPost).when(sn).createRequest(any(HttpEntity.class), any(Item.class), anyString(), anyString());
doReturn(httpPost).when(sn).createRequest(any(URI.class), any(JSONObject.class), eq(null));
CloseableHttpResponse resp = mock(CloseableHttpResponse.class);
StatusLine sl = mock(StatusLine.class);
when(sl.getStatusCode()).thenReturn(statusCode);
Expand Down

0 comments on commit df02f57

Please sign in to comment.