This repository has been archived by the owner on Aug 18, 2020. It is now read-only.
/
PodioBuildNotifier.java
417 lines (347 loc) · 12.2 KB
/
PodioBuildNotifier.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package com.podio.hudson;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Run;
import hudson.model.User;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import hudson.tasks.Mailer;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.FormValidation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import com.podio.BaseAPI;
import com.podio.common.Reference;
import com.podio.common.ReferenceType;
import com.podio.contact.ContactAPI;
import com.podio.contact.ProfileField;
import com.podio.contact.ProfileType;
import com.podio.item.FieldValues;
import com.podio.item.ItemAPI;
import com.podio.item.ItemCreate;
import com.podio.item.ItemsResponse;
import com.podio.oauth.OAuthClientCredentials;
import com.podio.oauth.OAuthUsernameCredentials;
import com.podio.root.RootAPI;
import com.podio.root.SystemStatus;
import com.podio.space.SpaceAPI;
import com.podio.space.SpaceWithOrganization;
import com.podio.task.Task;
import com.podio.task.TaskAPI;
import com.podio.task.TaskCreate;
import com.podio.task.TaskStatus;
import com.podio.user.UserMini;
import com.sun.jersey.api.client.UniformInterfaceException;
public class PodioBuildNotifier extends Notifier {
private static final int FAILED_TESTS_FIELD_ID = 74282;
private static final int TOTAL_TESTS_FIELD_ID = 74281;
private static final int USERS_FIELD_ID = 74280;
private static final int URL_FIELD_ID = 74670;
private static final int RESULT_FIELD_ID = 74279;
private static final int BUILD_NUMBER_FIELD_ID = 74278;
private static final int DURATION_FIELD_ID = 74671;
private static final int APP_ID = 13658;
protected static final Logger LOGGER = Logger
.getLogger(PodioBuildNotifier.class.getName());
private final String username;
private final String password;
private final String clientId;
private final String clientSecret;
private final String spaceURL;
@DataBoundConstructor
public PodioBuildNotifier(String username, String password,
String clientId, String clientSecret, String spaceURL) {
this.username = username;
this.password = password;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.spaceURL = spaceURL;
LOGGER.info(username);
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getClientId() {
return clientId;
}
public String getClientSecret() {
return clientSecret;
}
public String getSpaceURL() {
return spaceURL;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.BUILD;
}
private BaseAPI getBaseAPI() {
DescriptorImpl descriptor = (DescriptorImpl) getDescriptor();
return new BaseAPI(descriptor.hostname, descriptor.hostname,
descriptor.port, descriptor.ssl, false,
new OAuthClientCredentials(clientId, clientSecret),
new OAuthUsernameCredentials(username, password));
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
LOGGER.info("Build complete");
BaseAPI baseAPI = getBaseAPI();
String result = StringUtils.capitalize(build.getResult().toString()
.toLowerCase());
result = result.replace('_', ' ');
SpaceWithOrganization space = getSpace(baseAPI);
String url = Mailer.descriptor().getUrl() + build.getParent().getUrl()
+ build.getNumber();
List<Integer> userIds = getUserIds(baseAPI, space.getId(), build);
Integer totalTestCases = null;
Integer failedTestCases = null;
AbstractTestResultAction testResult = build.getTestResultAction();
if (testResult != null) {
totalTestCases = testResult.getTotalCount();
failedTestCases = testResult.getFailCount();
}
int itemId = postBuild(baseAPI, build.getNumber(), result, url,
userIds, totalTestCases, failedTestCases,
build.getDurationString());
AbstractBuild previousBuild = build.getPreviousBuild();
boolean oldFailed = previousBuild != null
&& previousBuild.getResult() != Result.SUCCESS;
TaskAPI taskAPI = new TaskAPI(baseAPI);
if (oldFailed && build.getResult() == Result.SUCCESS) {
Run firstFailed = getFirstFailure(previousBuild);
Integer firstFailedItemId = getItemId(baseAPI,
firstFailed.getNumber());
if (firstFailedItemId != null) {
List<Task> tasks = taskAPI.getTasksWithReference(new Reference(
ReferenceType.ITEM, firstFailedItemId));
for (Task task : tasks) {
if (task.getStatus() == TaskStatus.ACTIVE) {
taskAPI.completeTask(task.getId());
}
}
}
} else if (!oldFailed && build.getResult() != Result.SUCCESS) {
for (Integer userId : userIds) {
taskAPI.createTaskWithReference(new TaskCreate(
"Fix broken build", false, new LocalDate(), userId),
new Reference(ReferenceType.ITEM, itemId));
}
}
return true;
}
private Run getFirstFailure(Run build) {
Run previousBuild = build.getPreviousBuild();
if (previousBuild != null) {
if (previousBuild.getResult() == Result.SUCCESS) {
return build;
}
return getFirstFailure(previousBuild);
} else {
return build;
}
}
private Integer getItemId(BaseAPI baseAPI, int buildNumber) {
ItemsResponse response = new ItemAPI(baseAPI).getItemsByExternalId(
APP_ID, Integer.toString(buildNumber));
if (response.getFiltered() != 1) {
return null;
}
return response.getItems().get(0).getId();
}
private int postBuild(BaseAPI baseAPI, int buildNumber, String result,
String url, List<Integer> userIds, Integer totalTestCases,
Integer failedTestCases, String duration) {
List<FieldValues> fields = new ArrayList<FieldValues>();
fields.add(new FieldValues(BUILD_NUMBER_FIELD_ID, "value", "Build "
+ buildNumber));
fields.add(new FieldValues(RESULT_FIELD_ID, "value", result));
fields.add(new FieldValues(URL_FIELD_ID, "value", url));
List<Map<String, Object>> subValues = new ArrayList<Map<String, Object>>();
for (Integer userId : userIds) {
subValues.add(Collections.<String, Object> singletonMap("value",
userId));
}
fields.add(new FieldValues(USERS_FIELD_ID, subValues));
if (totalTestCases != null) {
fields.add(new FieldValues(TOTAL_TESTS_FIELD_ID, "value",
totalTestCases));
}
if (failedTestCases != null) {
fields.add(new FieldValues(FAILED_TESTS_FIELD_ID, "value",
failedTestCases));
}
fields.add(new FieldValues(DURATION_FIELD_ID, "value", duration));
ItemCreate create = new ItemCreate(Integer.toString(buildNumber),
fields, Collections.<Integer> emptyList(),
Collections.<String> emptyList());
ItemAPI itemAPI = new ItemAPI(baseAPI);
int itemId = itemAPI.addItem(APP_ID, create, true).getItemId();
return itemId;
}
private SpaceWithOrganization getSpace(BaseAPI baseAPI) {
return new SpaceAPI(baseAPI).getByURL(spaceURL);
}
private List<Integer> getUserIds(BaseAPI baseAPI, int spaceId,
AbstractBuild<?, ?> build) {
List<Integer> userIds = new ArrayList<Integer>();
Set<User> culprits = build.getCulprits();
ChangeLogSet<? extends Entry> changeSet = build.getChangeSet();
if (culprits.size() > 0) {
for (User culprit : culprits) {
LOGGER.info("Looking for user " + culprit);
Integer userId = getUserId(baseAPI, spaceId, culprit);
LOGGER.info("Found " + userId);
if (userId != null) {
userIds.add(userId);
}
}
}
if (changeSet != null) {
for (Entry entry : changeSet) {
LOGGER.info("Looking for user " + entry.getAuthor());
Integer userId = getUserId(baseAPI, spaceId, entry.getAuthor());
LOGGER.info("Found " + userId);
if (userId != null) {
userIds.add(userId);
}
}
}
LOGGER.info(userIds.toString());
return userIds;
}
private Integer getUserId(BaseAPI baseAPI, int spaceId, User user) {
String mail = user.getProperty(Mailer.UserProperty.class).getAddress();
List<UserMini> contacts = new ContactAPI(baseAPI).getSpaceContacts(
spaceId, ProfileField.MAIL, mail, 1, null, ProfileType.MINI,
null);
if (contacts.isEmpty()) {
return null;
}
return contacts.get(0).getId();
}
@Extension
public static final class DescriptorImpl extends
BuildStepDescriptor<Publisher> {
private String hostname = "localhost";
private int port = 9090;
private boolean ssl = false;
public DescriptorImpl() {
super(PodioBuildNotifier.class);
load();
}
@Override
public String getDisplayName() {
return "Podio Build Poster";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData)
throws FormException {
req.bindParameters(this);
this.hostname = formData.getString("hostname");
this.port = formData.getInt("port");
this.ssl = formData.getBoolean("ssl");
save();
return super.configure(req, formData);
}
public FormValidation doValidateAuth(
@QueryParameter("username") final String username,
@QueryParameter("password") final String password,
@QueryParameter("clientId") final String clientId,
@QueryParameter("clientSecret") final String clientSecret,
@QueryParameter("spaceURL") final String spaceURL)
throws IOException, ServletException {
BaseAPI baseAPI = new BaseAPI(hostname, hostname, port, ssl, false,
new OAuthClientCredentials(clientId, clientSecret),
new OAuthUsernameCredentials(username, password));
try {
SpaceWithOrganization space = new SpaceAPI(baseAPI)
.getByURL(spaceURL);
return FormValidation.ok("Connection ok, using space "
+ space.getName() + " in organization "
+ space.getOrganization().getName());
} catch (UniformInterfaceException e) {
if (e.getResponse().getStatus() == 404) {
return FormValidation.error("No space found with the URL "
+ spaceURL);
} else {
return FormValidation.error("Invalid username or password");
}
} catch (Exception e) {
e.printStackTrace();
return FormValidation.error("Invalid username or password");
}
}
public FormValidation doValidateAPI(
@QueryParameter("hostname") final String hostname,
@QueryParameter("port") final String port,
@QueryParameter("ssl") final boolean ssl) throws IOException,
ServletException {
int portInt;
try {
portInt = Integer.parseInt(port);
} catch (NumberFormatException e) {
return FormValidation.error("Port must be an integer");
}
BaseAPI baseAPI = new BaseAPI(hostname, hostname, portInt, ssl,
false, null, null);
try {
SystemStatus status = new RootAPI(baseAPI).getStatus();
return FormValidation
.ok("Connection validated, running API version "
+ status.getVersion());
} catch (Exception e) {
e.printStackTrace();
return FormValidation.error("Invalid hostname, port or ssl");
}
}
@Override
public Publisher newInstance(StaplerRequest req, JSONObject formData)
throws FormException {
return super.newInstance(req, formData);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
}
}