-
Notifications
You must be signed in to change notification settings - Fork 3
/
RestfulReviewboardClient.java
423 lines (353 loc) · 16.3 KB
/
RestfulReviewboardClient.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
418
419
420
421
422
423
/*******************************************************************************
* Copyright (c) 2004 - 2009 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mylyn project committers, Atlassian, Sven Krzyzak
*******************************************************************************/
/*******************************************************************************
* Copyright (c) 2009 Markus Knittig
* 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.
*
* Contributors:
* Markus Knittig - adapted Trac, Redmine & Atlassian implementations for
* Review Board
*******************************************************************************/
package org.review_board.ereviewboard.core.client;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.mylyn.commons.net.AbstractWebLocation;
import org.eclipse.mylyn.commons.net.AuthenticationCredentials;
import org.eclipse.mylyn.commons.net.AuthenticationType;
import org.eclipse.mylyn.tasks.core.IRepositoryQuery;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskDataCollector;
import org.json.JSONObject;
import org.review_board.ereviewboard.core.ReviewboardCorePlugin;
import org.review_board.ereviewboard.core.ReviewboardTaskMapper;
import org.review_board.ereviewboard.core.exception.ReviewboardException;
import org.review_board.ereviewboard.core.model.Comment;
import org.review_board.ereviewboard.core.model.Repository;
import org.review_board.ereviewboard.core.model.Review;
import org.review_board.ereviewboard.core.model.ReviewGroup;
import org.review_board.ereviewboard.core.model.ReviewRequest;
import org.review_board.ereviewboard.core.model.User;
import org.review_board.ereviewboard.core.util.ReviewboardUtil;
/**
* @author Markus Knittig
*
*/
public class RestfulReviewboardClient implements ReviewboardClient {
private final HttpClient httpClient;
private final RestfulReviewboardReader reviewboardReader;
private AbstractWebLocation location;
private ReviewboardClientData clientData;
private String cookie = "";
private String characterEncoding;
public RestfulReviewboardClient(AbstractWebLocation location, ReviewboardClientData clientData,
TaskRepository repository) {
if (Boolean.valueOf(repository.getProperty("selfSignedSSL"))) {
Protocol.registerProtocol("https",
new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
}
this.location = location;
this.clientData = clientData;
this.httpClient = new HttpClient();
this.reviewboardReader = new RestfulReviewboardReader();
this.characterEncoding = repository.getCharacterEncoding();
this.httpClient.getParams().setContentCharset(characterEncoding);
refreshRepositorySettings(repository);
}
public ReviewboardClientData getClientData() {
return clientData;
}
public void refreshRepositorySettings(TaskRepository repository) {
// Nothing to do yet
}
public TaskData getTaskData(TaskRepository taskRepository, final String taskId,
IProgressMonitor monitor) {
// TODO Get review request
TaskData taskData = new TaskData(new TaskAttributeMapper(taskRepository),
ReviewboardCorePlugin.REPOSITORY_KIND, location.getUrl(), taskId);
return taskData;
}
public void login() /* throws ReviewboardException */{
PostMethod loginRequest = new PostMethod(location.getUrl() + "/api/json/accounts/login/");
AuthenticationCredentials credentials = location
.getCredentials(AuthenticationType.REPOSITORY);
loginRequest.setParameter("username", credentials.getUserName());
loginRequest.setParameter("password", credentials.getPassword());
try {
if (httpClient.executeMethod(loginRequest) == 200) {
if (reviewboardReader.isStatOK(loginRequest.getResponseBodyAsString())) {
cookie = loginRequest.getResponseHeader("Set-Cookie").getValue();
} else {
//TODO Use a custom exception for error handling
throw new RuntimeException(reviewboardReader.getErrorMessage(
loginRequest.getResponseBodyAsString()));
}
} else {
//TODO Use a custom exception for error handling
throw new RuntimeException("Review Board site is not up!");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
loginRequest.releaseConnection();
}
}
private String getCookie() {
if (cookie.equals("")) {
login();
}
return cookie;
}
private GetMethod createGetMethod(String url) {
GetMethod getMethod = new GetMethod(stripSlash(location.getUrl()) + url);
getMethod.getParams().setParameter("Set-Cookie", getCookie());
return getMethod;
}
private PostMethod createPostMethod(String url) {
PostMethod postMethod = new PostMethod(stripSlash(location.getUrl()) + url);
postMethod.getParams().setParameter("Set-Cookie", getCookie());
return postMethod;
}
private String stripSlash(String url) {
if (url.endsWith("/")) {
return url.substring(0, url.lastIndexOf("/"));
}
return url;
}
private String executeGet(String url) {
GetMethod get = createGetMethod(url);
try {
httpClient.executeMethod(get);
return get.getResponseBodyAsString();
} catch (IOException e) {
new RuntimeException(e);
} finally {
get.releaseConnection();
}
return "";
}
private String executePost(String url, JSONObject body) {
return executePost(url, body, new HashMap<String, String>());
}
private String executePost(String url) {
return executePost(url, new HashMap<String, String>());
}
private String executePost(String url, Map<String, String> parameters) {
PostMethod post = createPostMethod(url);
for (String key : parameters.keySet()) {
post.setParameter(key, parameters.get(key));
}
try {
httpClient.executeMethod(post);
return post.getResponseBodyAsString();
} catch (IOException e) {
new RuntimeException(e);
} finally {
post.releaseConnection();
}
return "";
}
private String executePost(String url, JSONObject body, Map<String, String> parameters) {
PostMethod post = createPostMethod(url);
for (String key : parameters.keySet()) {
post.setParameter(key, parameters.get(key));
}
try {
post.setRequestEntity(new StringRequestEntity(body.toString(), "application/json",
characterEncoding));
httpClient.executeMethod(post);
return post.getResponseBodyAsString();
} catch (IOException e) {
new RuntimeException(e);
}
return "";
}
public List<Repository> getRepositories() throws ReviewboardException {
return reviewboardReader.readRepositories(executeGet("/api/json/repositories/"));
}
public List<User> getUsers() throws ReviewboardException {
return reviewboardReader.readUsers(executeGet("/api/json/users/"));
}
public List<ReviewGroup> getReviewGroups() throws ReviewboardException {
return reviewboardReader.readGroups(executeGet("/api/json/groups/"));
}
public List<ReviewRequest> getReviewRequests(String query) throws ReviewboardException {
return reviewboardReader.readReviewRequests(
executeGet("/api/json/reviewrequests/" + query));
}
public ReviewRequest newReviewRequest(ReviewRequest reviewRequest) throws ReviewboardException {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("repository_id", String.valueOf(reviewRequest.getRepository().getId()));
if (reviewRequest.getChangeNumber() != null) {
parameters.put("changenum", String.valueOf(reviewRequest.getChangeNumber()));
}
ReviewRequest newReviewRequest = reviewboardReader.readReviewRequest(executePost(
"/api/json/reviewrequests/new/", parameters));
reviewRequest.setId(newReviewRequest.getId());
reviewRequest.setTimeAdded(newReviewRequest.getTimeAdded());
reviewRequest.setLastUpdated(newReviewRequest.getLastUpdated());
reviewRequest.setSubmitter(newReviewRequest.getSubmitter());
// TODO
// reviewRequest.getTargetPeople().add(newReviewRequest.getSubmitter());
// reviewRequest.setSummary("Test");
// reviewRequest.setDescription("Test");
// updateReviewRequest(reviewRequest);
return reviewRequest;
}
public ReviewRequest getReviewRequest(int reviewRequestId) throws ReviewboardException {
return reviewboardReader.readReviewRequest(executeGet("/api/json/reviewrequests/"
+ reviewRequestId + "/"));
}
public List<Review> getReviews(int reviewRequestId) throws ReviewboardException {
List<Review> result = reviewboardReader.readReviews(
executeGet("/api/json/reviewrequests/" + reviewRequestId + "/reviews/"));
for (Review review : result) {
sortCommentsByLine(review);
}
return result;
}
private void sortCommentsByLine(Review review) {
Collections.sort(review.getComments(), new Comparator<Comment>() {
public int compare(Comment comment1, Comment comment2) {
return ((Integer) comment1.getFirstLine()).compareTo(comment2.getFirstLine());
}
});
}
public void updateReviewRequest(ReviewRequest reviewRequest) throws ReviewboardException {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("status", reviewRequest.getStatus().toString());
// parameters.put("public", reviewRequest.getPublicReviewRequest());
parameters.put("summary", reviewRequest.getSummary());
parameters.put("description", reviewRequest.getDescription());
parameters.put("testing_done", reviewRequest.getTestingDone());
parameters.put("branch", reviewRequest.getBranch());
parameters.put("bugs_closed", ReviewboardUtil.joinList(reviewRequest.getBugsClosed()));
parameters.put("target_groups", ReviewboardUtil.joinList(reviewRequest.getTargetGroups()));
parameters.put("target_people", ReviewboardUtil.joinList(reviewRequest.getTargetPeople()));
executePost("/api/json/reviewrequests/" + reviewRequest.getId() + "/draft/set/",
parameters);
executePost("/api/json/reviewrequests/" + reviewRequest.getId() + "/draft/save/");
executePost("/api/json/reviewrequests/" + reviewRequest.getId() + "/publish/");
}
public boolean hasRepositoryData() {
return (clientData.lastupdate != 0);
}
public void updateRepositoryData(boolean force, IProgressMonitor monitor) {
if (hasRepositoryData() && !force) {
return;
}
try {
monitor.subTask("Retrieving Reviewboard groups");
clientData.setGroups(getReviewGroups());
monitorWorked(monitor);
monitor.subTask("Retrieving Reviewboard users");
clientData.setUsers(getUsers());
monitorWorked(monitor);
monitor.subTask("Retrieving Reviewboard repositories");
clientData.setRepositories(getRepositories());
monitorWorked(monitor);
clientData.lastupdate = new Date().getTime();
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e);
}
}
private void monitorWorked(IProgressMonitor monitor) {
monitor.worked(1);
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
}
public void performQuery(TaskRepository repository, IRepositoryQuery query,
TaskDataCollector collector, IProgressMonitor monitor) throws CoreException {
try {
List<ReviewRequest> reviewRequests = getReviewRequests(query.getUrl());
for (ReviewRequest reviewRequest : reviewRequests) {
TaskData taskData = getTaskDataForReviewRequest(repository, reviewRequest);
collector.accept(taskData);
}
} catch (ReviewboardException e) {
throw new CoreException(Status.CANCEL_STATUS);
}
}
private TaskData getTaskDataForReviewRequest(TaskRepository taskRepository,
ReviewRequest reviewRequest) {
String summary = reviewRequest.getSummary();
String id = String.valueOf(reviewRequest.getId());
String owner = reviewRequest.getSubmitter().getUsername();
Date creationDate = reviewRequest.getTimeAdded();
Date dateModified = reviewRequest.getLastUpdated();
String description = reviewRequest.getDescription();
TaskData taskData = new TaskData(new TaskAttributeMapper(taskRepository),
ReviewboardCorePlugin.REPOSITORY_KIND, location.getUrl(), id);
taskData.setPartial(true);
ReviewboardTaskMapper mapper = new ReviewboardTaskMapper(taskData, true);
mapper.setTaskKey(id);
mapper.setCreationDate(creationDate);
mapper.setModificationDate(dateModified);
mapper.setSummary(summary);
mapper.setOwner(owner);
mapper.setDescription(description);
mapper.setTaskUrl(ReviewboardUtil.getReviewRequestUrl(taskRepository.getUrl(), id));
return taskData;
}
public List<String> getRawDiffs(int reviewRequestId) throws ReviewboardException {
List<String> diffs = new ArrayList<String>();
int iter = 1;
// XXX Ugly hack, there should ba an API call for this function
while (true) {
try {
diffs.add(executeGet(String.format("/r/%d/diff/%d/raw/", reviewRequestId, iter)));
iter++;
} catch (Exception e) {
break;
}
}
return diffs;
}
}