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

Simplify and Groovyfy attachment handling #536

Merged
merged 5 commits into from
Mar 15, 2019
Merged
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
21 changes: 10 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,17 @@ Additionally you can pass a JSONArray as a String in order to send complex
messages, as per the example:

```
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
node {
JSONArray attachments = new JSONArray();
JSONObject attachment = new JSONObject();

attachment.put('text','I find your lack of faith disturbing!');
attachment.put('fallback','Hey, Vader seems to be mad at you.');
attachment.put('color','#ff0000');

attachments.add(attachment);
slackSend(color: '#00FF00', channel: '@gustavo.maia', attachments: attachments.toString())
node {
def attachments = [
[
text: 'I find your lack of faith disturbing!',
fallback: 'Hey, Vader seems to be mad at you.',
color: '#ff0000'
]
]

slackSend(color: '#00FF00', channel: '@gustavo.maia', attachments: attachments)
}
```
For more information about slack messages see [Slack Messages Api](https://api.slack.com/docs/messages)
Expand Down
49 changes: 31 additions & 18 deletions src/main/java/jenkins/plugins/slack/workflow/SlackSendStep.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.domains.HostnameRequirement;
import com.google.common.collect.ImmutableSet;
import groovy.json.JsonOutput;
import hudson.AbortException;
import hudson.Extension;
import hudson.Util;
Expand Down Expand Up @@ -54,7 +55,7 @@ public class SlackSendStep extends Step {
private String baseUrl;
private String teamDomain;
private boolean failOnError;
private String attachments;
private Object attachments;
private boolean replyBroadcast;


Expand Down Expand Up @@ -139,11 +140,11 @@ public void setFailOnError(boolean failOnError) {
}

@DataBoundSetter
public void setAttachments(String attachments) {
public void setAttachments(Object attachments) {
this.attachments = attachments;
}

public String getAttachments() {
public Object getAttachments() {
return attachments;
}

Expand Down Expand Up @@ -254,22 +255,9 @@ protected SlackResponse run() throws Exception {
SlackService slackService = getSlackService(
baseUrl, teamDomain, token, tokenCredentialId, botUser, channel, step.replyBroadcast
);
boolean publishSuccess;
final boolean publishSuccess;
if (step.attachments != null) {
JsonSlurper jsonSlurper = new JsonSlurper();
JSON json;
try {
json = jsonSlurper.parseText(step.attachments);
} catch (JSONException e) {
listener.error(Messages.NotificationFailedWithException(e));
return null;
}
if (!(json instanceof JSONArray)) {
listener.error(Messages
.NotificationFailedWithException(new IllegalArgumentException("Attachments must be JSONArray")));
return null;
}
JSONArray jsonArray = (JSONArray) json;
JSONArray jsonArray = getAttachmentsAsJSONArray();
for (Object object : jsonArray) {
if (object instanceof JSONObject) {
JSONObject jsonNode = ((JSONObject) object);
Expand Down Expand Up @@ -310,6 +298,31 @@ protected SlackResponse run() throws Exception {
return response;
}

JSONArray getAttachmentsAsJSONArray() throws Exception {
final TaskListener listener = getContext().get(TaskListener.class);
final String jsonString;
if (step.attachments instanceof String) {
jsonString = (String) step.attachments;
}
else {
jsonString = JsonOutput.toJson(step.attachments);
}

JsonSlurper jsonSlurper = new JsonSlurper();
JSON json = null;
try {
json = jsonSlurper.parseText(jsonString);
} catch (JSONException e) {
listener.error(Messages.NotificationFailedWithException(e));
return null;
}
if(!(json instanceof JSONArray)){
listener.error(Messages.NotificationFailedWithException(new IllegalArgumentException("Attachments must be JSONArray")));
return null;
}
return (JSONArray) json;
}

private String defaultIfEmpty(String value) {
return Util.fixEmpty(value) != null ? value : Messages.SlackSendStepValuesEmptyMessage();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
Expand Down Expand Up @@ -114,6 +117,39 @@ public void testStepWithAttachments() throws Exception {

}

@Test
public void testStepWithAttachmentsAsListOfMap() throws Exception {
SlackSendStep step = new SlackSendStep();
step.setMessage("message");

Map<String, String> attachment1 = new HashMap<>();
attachment1.put("title", "Title of the message");
attachment1.put("author_name", "Name of the author");
attachment1.put("author_icon", "Avatar for author");

step.setAttachments(Arrays.asList(attachment1));
SlackSendStep.SlackSendStepExecution stepExecution = spy(new SlackSendStep.SlackSendStepExecution(step, stepContextMock));

when(Jenkins.get()).thenReturn(jenkins);

when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
doNothing().when(printStreamMock).println();

when(stepExecution.getSlackService(anyString(), anyString(), anyString(), anyString(), anyBoolean(), anyString(), anyBoolean())).thenReturn(slackServiceMock);

stepExecution.run();
verify(slackServiceMock, times(0)).publish("message", "");

JSONArray expectedAttachments = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("title","Title of the message");
jsonObject.put("author_name","Name of the author");
jsonObject.put("author_icon","Avatar for author");
jsonObject.put("fallback","message");
expectedAttachments.add(jsonObject);
verify(slackServiceMock, times(1)).publish("message", expectedAttachments, "");
}

@Test
public void testValuesForGlobalConfig() throws Exception {
SlackSendStep step = new SlackSendStep();
Expand Down