failedTests) {
+ this.failedTests = failedTests;
+ }
+}
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/config.jelly b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/config.jelly
index 766d6c9..197750e 100755
--- a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/config.jelly
+++ b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/config.jelly
@@ -1,41 +1,110 @@
+
+ xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form" xmlns:c="/lib/credentials" xmlns:p="/lib/notification">
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+ JSON
+ XML
+
+
+
+
+
+
+
+
+ HTTP
+ TCP
+ UDP
+
+
+
+
+
+
+
+
+ All Events
+ Job Queued
+ Job Started
+ Job Completed
+ Job Finalized
+ Job Failed
+ Job Failed and First Success
+ No Events - Call manually
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-branch.html b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-branch.html
new file mode 100644
index 0000000..c63110a
--- /dev/null
+++ b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-branch.html
@@ -0,0 +1,6 @@
+
+
Only notify if branch matches pattern.
+ Regex rules / pattern definition in
+ JAVA docs .
+
+
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-endpoints.html b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-endpoints.html
new file mode 100644
index 0000000..8f77edd
--- /dev/null
+++ b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-endpoints.html
@@ -0,0 +1,2 @@
+Sends notifications about Job status to the defined endpoints
+using UDP, TCP or HTTP protocols.
\ No newline at end of file
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-name.html b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-name.html
deleted file mode 100755
index 3fe2997..0000000
--- a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-name.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
- Help file for fields are discovered through a file name convention. This file is an line help for
- the "name" field. You can have arbitrary HTML here. You can write this file as a Jelly script
- if you need a dynamic content (but if you do so, change the extension to .jelly)
-
\ No newline at end of file
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-notes.html b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-notes.html
new file mode 100644
index 0000000..c786331
--- /dev/null
+++ b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-notes.html
@@ -0,0 +1,6 @@
+
+
Provides a place to include additional build information in the message.
+ This can contain tokens as defined by the
+ token-macro plugin .
+
+
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-retries.html b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-retries.html
new file mode 100644
index 0000000..f01b397
--- /dev/null
+++ b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-retries.html
@@ -0,0 +1 @@
+Number of retries to before abandoning attempt to contact the endpoint.
\ No newline at end of file
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-timeout.html b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-timeout.html
new file mode 100644
index 0000000..5e8902f
--- /dev/null
+++ b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-timeout.html
@@ -0,0 +1 @@
+Sets connection timeout (in milliseconds) for TCP and HTTP. Default timeout is 30 seconds (30,000 ms)
\ No newline at end of file
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-url.html b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-url.html
new file mode 100644
index 0000000..c8b0c19
--- /dev/null
+++ b/src/main/resources/com/tikal/hudson/plugins/notification/HudsonNotificationProperty/help-url.html
@@ -0,0 +1,8 @@
+
+
+ URL format for UDP and TCP protocols is
+ (hostname|IpAddress):portNumber, e.g. 10.10.10.10:12345
+ URL format for HTTP protocol is any legal http address, e.g.
+ http://[user:password@]myhost.com:8080/monitor
+
+
diff --git a/src/main/resources/com/tikal/hudson/plugins/notification/Messages.properties b/src/main/resources/com/tikal/hudson/plugins/notification/Messages.properties
new file mode 100644
index 0000000..e95c3ee
--- /dev/null
+++ b/src/main/resources/com/tikal/hudson/plugins/notification/Messages.properties
@@ -0,0 +1 @@
+Notify.DisplayName=Notify configured endpoints
diff --git a/src/main/resources/index.jelly b/src/main/resources/index.jelly
index 3a17698..ad9ec4b 100755
--- a/src/main/resources/index.jelly
+++ b/src/main/resources/index.jelly
@@ -1 +1,6 @@
-This plugin allows Hudson to send build notifications.
+
+
+ This plugin from
+
Tikal Knowledge
+ allows sending running Jobs status notifications.
+
diff --git a/src/main/resources/lib/notification/blockWrapper.jelly b/src/main/resources/lib/notification/blockWrapper.jelly
new file mode 100644
index 0000000..d43a2fe
--- /dev/null
+++ b/src/main/resources/lib/notification/blockWrapper.jelly
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/lib/notification/blockWrapperCentered.jelly b/src/main/resources/lib/notification/blockWrapperCentered.jelly
new file mode 100644
index 0000000..0e9d7ed
--- /dev/null
+++ b/src/main/resources/lib/notification/blockWrapperCentered.jelly
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/lib/notification/cellWrapper.jelly b/src/main/resources/lib/notification/cellWrapper.jelly
new file mode 100644
index 0000000..0a30187
--- /dev/null
+++ b/src/main/resources/lib/notification/cellWrapper.jelly
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/lib/notification/rowWrapper.jelly b/src/main/resources/lib/notification/rowWrapper.jelly
new file mode 100644
index 0000000..710190d
--- /dev/null
+++ b/src/main/resources/lib/notification/rowWrapper.jelly
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/lib/notification/taglib b/src/main/resources/lib/notification/taglib
new file mode 100644
index 0000000..e69de29
diff --git a/src/main/webapp/help-globalConfig.html b/src/main/webapp/help-globalConfig.html
index 7b5ebed..f6b7a1f 100755
--- a/src/main/webapp/help-globalConfig.html
+++ b/src/main/webapp/help-globalConfig.html
@@ -1,8 +1,14 @@
-
- This HTML fragment will be injected into the configuration screen
- when the user clicks the 'help' icon. See global.jelly for how the
- form decides which page to load.
- You can have any HTML fragment here.
-
-
+This plugin from Tikal
+Knowledge allows sending Job Status notifications.
+
+{
+ "name":"JobName",
+ "url":"JobUrl",
+ "build":{
+ "number":1,
+ "phase":"STARTED",
+ "status":"FAILED"
+ }
+}
+
diff --git a/src/main/webapp/help-projectConfig.html b/src/main/webapp/help-projectConfig.html
new file mode 100755
index 0000000..f6b7a1f
--- /dev/null
+++ b/src/main/webapp/help-projectConfig.html
@@ -0,0 +1,14 @@
+
+
This plugin from Tikal
+Knowledge allows sending Job Status notifications.
+
+{
+ "name":"JobName",
+ "url":"JobUrl",
+ "build":{
+ "number":1,
+ "phase":"STARTED",
+ "status":"FAILED"
+ }
+}
+
diff --git a/src/test/java/com/tikal/hudson/plugins/notification/PhaseTest.java b/src/test/java/com/tikal/hudson/plugins/notification/PhaseTest.java
new file mode 100644
index 0000000..04f2b41
--- /dev/null
+++ b/src/test/java/com/tikal/hudson/plugins/notification/PhaseTest.java
@@ -0,0 +1,294 @@
+package com.tikal.hudson.plugins.notification;
+
+import static com.tikal.hudson.plugins.notification.UrlType.PUBLIC;
+import static com.tikal.hudson.plugins.notification.UrlType.SECRET;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.isA;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.tikal.hudson.plugins.notification.model.JobState;
+import hudson.EnvVars;
+import hudson.model.Job;
+import hudson.model.Result;
+import hudson.model.Run;
+import hudson.model.TaskListener;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.lang.reflect.Method;
+import java.util.List;
+import jenkins.model.Jenkins;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class PhaseTest {
+ @Mock
+ private Run run;
+
+ @Mock
+ private Job job;
+
+ @Mock
+ private TaskListener listener;
+
+ @Mock
+ private HudsonNotificationProperty property;
+
+ @Mock
+ private Endpoint endpoint;
+
+ @Mock
+ private UrlInfo urlInfo;
+
+ @Mock
+ private EnvVars environment;
+
+ @Mock
+ private PrintStream logger;
+
+ @Mock
+ private Jenkins jenkins;
+
+ @Test
+ public void testIsRun() throws ReflectiveOperationException {
+ Endpoint endPoint = new Endpoint(null);
+ Method isRunMethod = Phase.class.getDeclaredMethod("isRun", Endpoint.class, Result.class, Result.class);
+ isRunMethod.setAccessible(true);
+
+ assertEquals(
+ "returns true for null endpoint event",
+ isRunMethod.invoke(Phase.QUEUED, endPoint, null, null),
+ Boolean.TRUE);
+
+ endPoint.setEvent("all");
+ for (Phase phaseValue : Phase.values()) {
+ assertEquals(
+ "all Event returns true for Phase " + phaseValue.toString(),
+ isRunMethod.invoke(phaseValue, endPoint, null, null),
+ Boolean.TRUE);
+ }
+
+ endPoint.setEvent("queued");
+ assertEquals(
+ "queued Event returns true for Phase Queued",
+ isRunMethod.invoke(Phase.QUEUED, endPoint, null, null),
+ Boolean.TRUE);
+ assertEquals(
+ "queued Event returns false for Phase Started",
+ isRunMethod.invoke(Phase.STARTED, endPoint, null, null),
+ Boolean.FALSE);
+
+ endPoint.setEvent("started");
+ assertEquals(
+ "started Event returns true for Phase Started",
+ isRunMethod.invoke(Phase.STARTED, endPoint, null, null),
+ Boolean.TRUE);
+ assertEquals(
+ "started Event returns false for Phase Completed",
+ isRunMethod.invoke(Phase.COMPLETED, endPoint, null, null),
+ Boolean.FALSE);
+
+ endPoint.setEvent("completed");
+ assertEquals(
+ "completed Event returns true for Phase Completed",
+ isRunMethod.invoke(Phase.COMPLETED, endPoint, null, null),
+ Boolean.TRUE);
+ assertEquals(
+ "completed Event returns false for Phase Finalized",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, null, null),
+ Boolean.FALSE);
+
+ endPoint.setEvent("finalized");
+ assertEquals(
+ "finalized Event returns true for Phase Finalized",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, null, null),
+ Boolean.TRUE);
+ assertEquals(
+ "finalized Event returns true for Phase Queued",
+ isRunMethod.invoke(Phase.QUEUED, endPoint, null, null),
+ Boolean.FALSE);
+
+ endPoint.setEvent("failed");
+ assertEquals(
+ "failed Event returns false for Phase Finalized and no status",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, null, null),
+ Boolean.FALSE);
+ assertEquals(
+ "failed Event returns false for Phase Finalized and success status",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, Result.SUCCESS, null),
+ Boolean.FALSE);
+ assertEquals(
+ "failed Event returns true for Phase Finalized and success failure",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, Result.FAILURE, null),
+ Boolean.TRUE);
+ assertEquals(
+ "failed Event returns false for Phase not Finalized and success failure",
+ isRunMethod.invoke(Phase.COMPLETED, endPoint, Result.FAILURE, null),
+ Boolean.FALSE);
+
+ endPoint.setEvent("failedAndFirstSuccess");
+ assertEquals(
+ "failedAndFirstSuccess Event returns false for Phase Finalized and no status",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, null, null),
+ Boolean.FALSE);
+ assertEquals(
+ "failedAndFirstSuccess Event returns false for Phase Finalized and no previous status",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, Result.SUCCESS, null),
+ Boolean.FALSE);
+ assertEquals(
+ "failedAndFirstSuccess Event returns true for Phase Finalized and no previous status and failed status",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, Result.FAILURE, null),
+ Boolean.TRUE);
+ assertEquals(
+ "failedAndFirstSuccess Event returns true for Phase Finalized and failed status",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, Result.FAILURE, Result.FAILURE),
+ Boolean.TRUE);
+ assertEquals(
+ "failedAndFirstSuccess Event returns true for Phase Finalized and success status with previous status of failure",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, Result.SUCCESS, Result.FAILURE),
+ Boolean.TRUE);
+ assertEquals(
+ "failedAndFirstSuccess Event returns false for Phase Finalized and success status with previous status of success",
+ isRunMethod.invoke(Phase.FINALIZED, endPoint, Result.SUCCESS, Result.SUCCESS),
+ Boolean.FALSE);
+ assertEquals(
+ "failedAndFirstSuccess Event returns false for Phase not Finalized",
+ isRunMethod.invoke(Phase.COMPLETED, endPoint, Result.SUCCESS, Result.FAILURE),
+ Boolean.FALSE);
+ }
+
+ @Test
+ public void testRunNoProperty() {
+ when(run.getParent()).thenReturn(job);
+
+ Phase.STARTED.handle(run, listener, 0L);
+
+ verify(job).getProperty(HudsonNotificationProperty.class);
+ verifyNoInteractions(listener, endpoint, property);
+ }
+
+ @Test
+ public void testRunNoPreviousRunUrlNull() {
+ when(run.getParent()).thenReturn(job);
+ when(job.getProperty(HudsonNotificationProperty.class)).thenReturn(property);
+ when(property.getEndpoints()).thenReturn(List.of(endpoint));
+ when(endpoint.getUrlInfo()).thenReturn(urlInfo);
+
+ Phase.STARTED.handle(run, listener, 0L);
+
+ verify(run).getPreviousCompletedBuild();
+ verifyNoInteractions(listener);
+ }
+
+ @Test
+ public void testRunNoPreviousRunUrlTypePublicUnresolvedUrl() throws IOException, InterruptedException {
+ when(run.getParent()).thenReturn(job);
+ when(job.getProperty(HudsonNotificationProperty.class)).thenReturn(property);
+ when(property.getEndpoints()).thenReturn(List.of(endpoint));
+ when(endpoint.getUrlInfo()).thenReturn(urlInfo);
+ when(run.getEnvironment(listener)).thenReturn(environment);
+ when(urlInfo.getUrlOrId()).thenReturn("$someUrl");
+ when(urlInfo.getUrlType()).thenReturn(PUBLIC);
+ when(environment.expand("$someUrl")).thenReturn("$someUrl");
+ when(listener.getLogger()).thenReturn(logger);
+
+ Phase.STARTED.handle(run, listener, 0L);
+
+ verify(logger).printf("Ignoring sending notification due to unresolved variable: %s%n", "url '$someUrl'");
+ verify(run).getPreviousCompletedBuild();
+ }
+
+ @Test
+ public void testRunPreviousRunUrlTypePublic() throws IOException, InterruptedException {
+ byte[] data = "data".getBytes();
+ try (MockedStatic jenkinsMockedStatic = mockStatic(Jenkins.class)) {
+ jenkinsMockedStatic.when(Jenkins::getInstanceOrNull).thenReturn(jenkins);
+ jenkinsMockedStatic.when(Jenkins::get).thenReturn(jenkins);
+
+ Protocol httpProtocolSpy = spy(Protocol.HTTP);
+ when(endpoint.getProtocol()).thenReturn(httpProtocolSpy);
+ doNothing().when(httpProtocolSpy).send(anyString(), any(byte[].class), anyInt(), anyBoolean());
+
+ Format jsonFormatSpy = spy(Format.JSON);
+ JobState jobState = new JobState();
+ when(endpoint.getFormat()).thenReturn(jsonFormatSpy);
+ doReturn(data).when(jsonFormatSpy).serialize(isA(JobState.class));
+ assertEquals(data, jsonFormatSpy.serialize(jobState));
+
+ when(run.getParent()).thenReturn(job);
+ when(job.getProperty(HudsonNotificationProperty.class)).thenReturn(property);
+ when(property.getEndpoints()).thenReturn(List.of(endpoint));
+ when(endpoint.getUrlInfo()).thenReturn(urlInfo);
+ when(endpoint.getBranch()).thenReturn("branchName");
+ when(run.getEnvironment(listener)).thenReturn(environment);
+ when(urlInfo.getUrlOrId()).thenReturn("$someUrl");
+ when(urlInfo.getUrlType()).thenReturn(PUBLIC);
+ when(environment.expand("$someUrl")).thenReturn("expandedUrl");
+ when(environment.containsKey("BRANCH_NAME")).thenReturn(true);
+ when(environment.get("BRANCH_NAME")).thenReturn("branchName");
+ when(listener.getLogger()).thenReturn(logger);
+ when(endpoint.getTimeout()).thenReturn(42);
+
+ Phase.STARTED.handle(run, listener, 1L);
+
+ verify(logger).printf("Notifying endpoint with %s%n", "url 'expandedUrl'");
+ verify(httpProtocolSpy).send("expandedUrl", data, 42, false);
+ verify(run).getPreviousCompletedBuild();
+ }
+ }
+
+ @Test
+ public void testRunPreviousRunUrlTypeSecret() throws IOException, InterruptedException {
+ byte[] data = "data".getBytes();
+ try (MockedStatic jenkinsMockedStatic = mockStatic(Jenkins.class);
+ MockedStatic utilsMockedStatic = mockStatic(Utils.class)) {
+ jenkinsMockedStatic.when(Jenkins::getInstanceOrNull).thenReturn(jenkins);
+ jenkinsMockedStatic.when(Jenkins::get).thenReturn(jenkins);
+ utilsMockedStatic
+ .when(() -> Utils.getSecretUrl("credentialsId", jenkins))
+ .thenReturn("$secretUrl");
+
+ Protocol httpProtocolSpy = spy(Protocol.HTTP);
+ when(endpoint.getProtocol()).thenReturn(httpProtocolSpy);
+ doNothing().when(httpProtocolSpy).send(anyString(), any(byte[].class), anyInt(), anyBoolean());
+
+ Format jsonFormatSpy = spy(Format.JSON);
+ JobState jobState = new JobState();
+ when(endpoint.getFormat()).thenReturn(jsonFormatSpy);
+ doReturn(data).when(jsonFormatSpy).serialize(isA(JobState.class));
+ assertEquals(data, jsonFormatSpy.serialize(jobState));
+
+ when(run.getParent()).thenReturn(job);
+ when(job.getProperty(HudsonNotificationProperty.class)).thenReturn(property);
+ when(property.getEndpoints()).thenReturn(List.of(endpoint));
+ when(endpoint.getUrlInfo()).thenReturn(urlInfo);
+ when(endpoint.getBranch()).thenReturn(".*");
+ when(run.getEnvironment(listener)).thenReturn(environment);
+ when(job.getParent()).thenReturn(jenkins);
+ when(urlInfo.getUrlOrId()).thenReturn("credentialsId");
+ when(urlInfo.getUrlType()).thenReturn(SECRET);
+ when(environment.expand("$secretUrl")).thenReturn("secretUrl");
+ when(listener.getLogger()).thenReturn(logger);
+ when(endpoint.getTimeout()).thenReturn(42);
+
+ Phase.STARTED.handle(run, listener, 1L);
+
+ verify(logger).printf("Notifying endpoint with %s%n", "credentials id 'credentialsId'");
+ verify(httpProtocolSpy).send("secretUrl", data, 42, false);
+ verify(run).getPreviousCompletedBuild();
+ }
+ }
+}
diff --git a/src/test/java/com/tikal/hudson/plugins/notification/ProtocolTest.java b/src/test/java/com/tikal/hudson/plugins/notification/ProtocolTest.java
new file mode 100644
index 0000000..71dba4c
--- /dev/null
+++ b/src/test/java/com/tikal/hudson/plugins/notification/ProtocolTest.java
@@ -0,0 +1,252 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2011, CloudBees, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.tikal.hudson.plugins.notification;
+
+import com.google.common.base.MoreObjects;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import junit.framework.TestCase;
+
+/**
+ * @author Kohsuke Kawaguchi
+ */
+public class ProtocolTest extends TestCase {
+
+ static class Request {
+ private final String url;
+ private final String method;
+ private final String body;
+ private final String userInfo;
+
+ Request(HttpExchange he) throws IOException {
+ InetSocketAddress address = he.getLocalAddress();
+ this.url = "http://" + address.getHostString() + ":"
+ + address.getPort()
+ + he.getRequestURI().toString();
+ this.method = he.getRequestMethod();
+ this.body = new String(he.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
+ String auth = he.getRequestHeaders().getFirst("Authorization");
+ this.userInfo =
+ (null == auth) ? null : new String(Base64.getDecoder().decode(auth.split(" ")[1])) + "@";
+ }
+
+ Request(String url, String method, String body) {
+ this.url = url;
+ this.method = method;
+ this.body = body;
+ this.userInfo = null;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(url, method, body);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof Request)) {
+ return false;
+ }
+ Request other = (Request) obj;
+ return Objects.equals(url, other.url)
+ && Objects.equals(method, other.method)
+ && Objects.equals(body, other.body);
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("url", url)
+ .add("method", method)
+ .add("body", body)
+ .toString();
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public String getUrlWithAuthority() {
+ if (null == userInfo) {
+ // Detect possible bug: userInfo never moved from URI to Authorization header
+ return null;
+ } else {
+ return url.replaceFirst("^http://", "http://" + userInfo);
+ }
+ }
+ }
+
+ static class RecordingServlet implements HttpHandler {
+ private final BlockingQueue requests;
+
+ public RecordingServlet(BlockingQueue requests) {
+ this.requests = requests;
+ }
+
+ @Override
+ public void handle(HttpExchange he) throws IOException {
+
+ Request request = new Request(he);
+ try {
+ requests.put(request);
+ } catch (InterruptedException e) {
+ throw new IOException("Interrupted while adding request to queue", e);
+ }
+ he.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
+ he.close();
+ }
+ }
+
+ static class RedirectHandler implements HttpHandler {
+ private final BlockingQueue requests;
+ private final String redirectURI;
+
+ public RedirectHandler(BlockingQueue requests, String redirectURI) {
+ this.requests = Objects.requireNonNull(requests);
+ this.redirectURI = Objects.requireNonNull(redirectURI);
+ }
+
+ @Override
+ public void handle(HttpExchange he) throws IOException {
+ Request request = new Request(he);
+ try {
+ requests.put(request);
+ } catch (InterruptedException e) {
+ throw new IOException("Interrupted while adding request to queue", e);
+ }
+ he.getResponseHeaders().set("Location", redirectURI);
+ he.sendResponseHeaders(307, -1);
+ he.close();
+ }
+ }
+
+ private List servers;
+
+ interface UrlFactory {
+ String getUrl(String path);
+ }
+
+ private UrlFactory startServer(HttpHandler handler, String path) throws Exception {
+ return startSecureServer(handler, path, "");
+ }
+
+ private UrlFactory startSecureServer(HttpHandler handler, String path, String authority) throws Exception {
+ HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
+ server.createContext(path, handler);
+
+ server.start();
+ servers.add(server);
+
+ if (!authority.isEmpty()) {
+ authority += "@";
+ }
+
+ InetSocketAddress address = server.getAddress();
+ final URL serverUrl =
+ new URL(String.format("http://%s%s:%d", authority, address.getHostString(), address.getPort()));
+ return new UrlFactory() {
+ @Override
+ public String getUrl(String path) {
+ try {
+ return new URL(serverUrl, path).toExternalForm();
+ } catch (MalformedURLException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+ };
+ }
+
+ @Override
+ public void setUp() {
+ servers = new LinkedList<>();
+ }
+
+ @Override
+ public void tearDown() {
+ for (HttpServer server : servers) {
+ server.stop(1);
+ }
+ }
+
+ public void testHttpPost() throws Exception {
+ BlockingQueue requests = new LinkedBlockingQueue<>();
+
+ UrlFactory urlFactory = startServer(new RecordingServlet(requests), "/realpath");
+
+ assertTrue(requests.isEmpty());
+
+ String uri = urlFactory.getUrl("/realpath");
+ Protocol.HTTP.send(uri, "Hello".getBytes(), 30000, true);
+
+ assertEquals(new Request(uri, "POST", "Hello"), requests.take());
+ assertTrue(requests.isEmpty());
+ }
+
+ public void testHttpPostWithBasicAuth() throws Exception {
+ BlockingQueue requests = new LinkedBlockingQueue<>();
+
+ UrlFactory urlFactory = startSecureServer(new RecordingServlet(requests), "/realpath", "fred:foo");
+
+ assertTrue(requests.isEmpty());
+
+ String uri = urlFactory.getUrl("/realpath");
+ Protocol.HTTP.send(uri, "Hello".getBytes(), 30000, true);
+
+ Request theRequest = requests.take();
+ assertTrue(requests.isEmpty());
+ assertEquals(new Request(uri, "POST", "Hello").getUrl(), theRequest.getUrlWithAuthority());
+ }
+
+ public void testHttpPostWithRedirects() throws Exception {
+ BlockingQueue requests = new LinkedBlockingQueue<>();
+
+ UrlFactory urlFactory = startServer(new RecordingServlet(requests), "/realpath");
+
+ String redirectUri = urlFactory.getUrl("/realpath");
+ UrlFactory redirectorUrlFactory = startServer(new RedirectHandler(requests, redirectUri), "/path");
+
+ assertTrue(requests.isEmpty());
+
+ String uri = redirectorUrlFactory.getUrl("/path");
+ Protocol.HTTP.send(uri, "RedirectMe".getBytes(), 30000, true);
+
+ assertEquals(new Request(uri, "POST", "RedirectMe"), requests.take());
+ assertEquals(new Request(redirectUri, "POST", "RedirectMe"), requests.take());
+ assertTrue(requests.isEmpty());
+ }
+}
diff --git a/src/test/java/com/tikal/hudson/plugins/notification/test/HostnamePortTest.java b/src/test/java/com/tikal/hudson/plugins/notification/test/HostnamePortTest.java
new file mode 100644
index 0000000..c1ed4f2
--- /dev/null
+++ b/src/test/java/com/tikal/hudson/plugins/notification/test/HostnamePortTest.java
@@ -0,0 +1,34 @@
+/**
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.tikal.hudson.plugins.notification.test;
+
+import com.tikal.hudson.plugins.notification.HostnamePort;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class HostnamePortTest {
+
+ @Test
+ public void parseUrlTest() {
+ HostnamePort hnp = HostnamePort.parseUrl("111");
+ Assert.assertNull(hnp);
+ hnp = HostnamePort.parseUrl(null);
+ Assert.assertNull(hnp);
+ hnp = HostnamePort.parseUrl("localhost:123");
+ Assert.assertEquals("localhost", hnp.hostname);
+ Assert.assertEquals(123, hnp.port);
+ hnp = HostnamePort.parseUrl("localhost:123456");
+ Assert.assertEquals(12345, hnp.port);
+ }
+}