Skip to content
This repository has been archived by the owner on Jan 7, 2021. It is now read-only.

Upgrade json simple & fix big overview comment issue #118

Open
wants to merge 9 commits into
base: coverage_split_sensor
Choose a base branch
from
Open
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
10 changes: 8 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<groupId>com.github.cliftonlabs</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>org.asynchttpclient</groupId>
Expand Down Expand Up @@ -116,6 +116,12 @@
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
Expand Down
18 changes: 12 additions & 6 deletions src/main/java/org/sonar/plugins/stash/StashProjectBuilder.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
package org.sonar.plugins.stash;

import org.sonar.api.batch.bootstrap.ProjectBuilder;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.bootstrap.ProjectBuilder;

public class StashProjectBuilder extends ProjectBuilder {
private File projectBaseDir;

private static final Logger LOGGER = LoggerFactory.getLogger(StashProjectBuilder.class);

private File workingDir;

@Override
public void build(Context context) {
projectBaseDir = context.projectReactor().getRoot().getBaseDir();
workingDir = new File(System.getProperty("user.dir"));
LOGGER.debug("Current working directory {}", workingDir);
}

public File getProjectBaseDir() {
return projectBaseDir;
public File getWorkingDir() {
return workingDir;
}

}
6 changes: 3 additions & 3 deletions src/main/java/org/sonar/plugins/stash/StashRequestFacade.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ public class StashRequestFacade implements BatchComponent, IssuePathResolver {
private static final String STACK_TRACE = "Exception stack trace";

private StashPluginConfiguration config;
private File projectBaseDir;
private File workingDir;
private final InputFileCache inputFileCache;
private CoverageProjectStore coverageProjectStore;

public StashRequestFacade(StashPluginConfiguration stashPluginConfiguration, InputFileCache inputFileCache, StashProjectBuilder projectBuilder, CoverageProjectStore coverageProjectStore) {
this.config = stashPluginConfiguration;
this.inputFileCache = inputFileCache;
this.projectBaseDir = projectBuilder.getProjectBaseDir();
this.workingDir = projectBuilder.getWorkingDir();
this.coverageProjectStore = coverageProjectStore;
}

Expand Down Expand Up @@ -422,6 +422,6 @@ public String getIssuePath(Issue issue) {
return null;
}

return new PathResolver().relativePath(projectBaseDir, inputFile.file());
return new PathResolver().relativePath(workingDir, inputFile.file());
}
}
102 changes: 55 additions & 47 deletions src/main/java/org/sonar/plugins/stash/client/StashClient.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
package org.sonar.plugins.stash.client;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.commons.lang3.StringUtils;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.BoundRequestBuilder;
Expand All @@ -8,10 +17,12 @@
import org.asynchttpclient.Realm;
import org.asynchttpclient.Response;
import org.asynchttpclient.config.AsyncHttpClientConfigDefaults;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.DeserializationException;
import org.json.simple.JsonArray;
import org.json.simple.JsonObject;
import org.json.simple.Jsoner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.plugins.stash.PluginInfo;
import org.sonar.plugins.stash.PluginUtils;
import org.sonar.plugins.stash.PullRequestRef;
Expand All @@ -26,16 +37,9 @@
import org.sonar.plugins.stash.issue.StashUser;
import org.sonar.plugins.stash.issue.collector.StashCollector;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class StashClient implements AutoCloseable {

private static final Logger LOGGER = LoggerFactory.getLogger(StashClient.class);

private final String baseUrl;
private final StashCredentials credentials;
Expand Down Expand Up @@ -67,7 +71,7 @@ public class StashClient implements AutoCloseable {
private static final String TASK_POST_ERROR_MESSAGE = "Unable to post a task on comment {0,number,#}.";
private static final String TASK_DELETION_ERROR_MESSAGE = "Unable to delete task {0,number,#}.";

private static final ContentType JSON = new ContentType("application", "json", null);
private static final ContentType JSON_CONTENT_TYPE = new ContentType("application", "json", null);

public StashClient(String url, StashCredentials credentials, int stashTimeout, String sonarQubeVersion) {
this.baseUrl = url;
Expand All @@ -88,7 +92,7 @@ public void postCommentOnPullRequest(PullRequestRef pr, String report)
throws StashClientException {

String request = MessageFormat.format(API_ONE_PR_ALL_COMMENTS, baseUrl, pr.project(), pr.repository(), pr.pullRequestId());
JSONObject json = new JSONObject();
JsonObject json = new JsonObject();
json.put("text", report);

postCreate(request, json, MessageFormat.format(COMMENT_POST_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));
Expand All @@ -104,7 +108,8 @@ public StashCommentReport getPullRequestComments(PullRequestRef pr, String path)
while (! isLastPage){
try {
String request = MessageFormat.format(API_ONE_PR_COMMENT_PATH, baseUrl, pr.project(), pr.repository(), pr.pullRequestId(), path, start);
JSONObject jsonComments = get(request, MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));
JsonObject jsonComments = get(request,
MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));
result.add(StashCollector.extractComments(jsonComments));

// Stash pagination: check if you get all comments linked to the pull-request
Expand Down Expand Up @@ -133,7 +138,7 @@ public StashDiffReport getPullRequestDiffs(PullRequestRef pr)

try {
String request = MessageFormat.format(API_ONE_PR_DIFF, baseUrl, pr.project(), pr.repository(), pr.pullRequestId());
JSONObject jsonDiffs = get(request, MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));
JsonObject jsonDiffs = get(request, MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));
result = StashCollector.extractDiffs(jsonDiffs);
} catch (StashReportExtractionException e) {
throw new StashClientException(e);
Expand All @@ -146,7 +151,7 @@ public StashComment postCommentLineOnPullRequest(PullRequestRef pr, String messa
throws StashClientException {
String request = MessageFormat.format(API_ONE_PR_ALL_COMMENTS, baseUrl, pr.project(), pr.repository(), pr.pullRequestId());

JSONObject anchor = new JSONObject();
JsonObject anchor = new JsonObject();
if (line != 0L) {
anchor.put("line", line);
anchor.put("lineType", type);
Expand All @@ -160,11 +165,11 @@ public StashComment postCommentLineOnPullRequest(PullRequestRef pr, String messa

anchor.put("path", path);

JSONObject json = new JSONObject();
JsonObject json = new JsonObject();
json.put("text", message);
json.put("anchor", anchor);

JSONObject response = postCreate(request, json,
JsonObject response = postCreate(request, json,
MessageFormat.format(COMMENT_POST_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));

return StashCollector.extractComment(response, path, line);
Expand All @@ -173,15 +178,15 @@ public StashComment postCommentLineOnPullRequest(PullRequestRef pr, String messa
public StashUser getUser(String userSlug) throws StashClientException {

String request = MessageFormat.format(USER_API, baseUrl, userSlug);
JSONObject response = get(request, MessageFormat.format(USER_GET_ERROR_MESSAGE, userSlug));
JsonObject response = get(request, MessageFormat.format(USER_GET_ERROR_MESSAGE, userSlug));

return StashCollector.extractUser(response);
}

public StashPullRequest getPullRequest(PullRequestRef pr)
throws StashClientException {
String request = MessageFormat.format(API_ONE_PR, baseUrl, pr.project(), pr.repository(), pr.pullRequestId());
JSONObject response = get(request, MessageFormat.format(PULL_REQUEST_GET_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));
JsonObject response = get(request, MessageFormat.format(PULL_REQUEST_GET_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));

return StashCollector.extractPullRequest(pr, response);
}
Expand All @@ -190,14 +195,14 @@ public void addPullRequestReviewer(PullRequestRef pr, long pullRequestVersion, A
throws StashClientException {
String request = MessageFormat.format(API_ONE_PR, baseUrl, pr.project(), pr.repository(), pr.pullRequestId());

JSONObject json = new JSONObject();
JsonObject json = new JsonObject();

JSONArray jsonReviewers = new JSONArray();
JsonArray jsonReviewers = new JsonArray();
for (StashUser reviewer: reviewers) {
JSONObject reviewerName = new JSONObject();
JsonObject reviewerName = new JsonObject();
reviewerName.put("name", reviewer.getName());

JSONObject user = new JSONObject();
JsonObject user = new JsonObject();
user.put("user", reviewerName);

jsonReviewers.add(user);
Expand All @@ -223,11 +228,11 @@ public void resetPullRequestApproval(PullRequestRef pr) throws StashClientExcept
public void postTaskOnComment(String message, Long commentId) throws StashClientException {
String request = baseUrl + TASKS_API;

JSONObject anchor = new JSONObject();
JsonObject anchor = new JsonObject();
anchor.put("id", commentId);
anchor.put("type", "COMMENT");

JSONObject json = new JSONObject();
JsonObject json = new JsonObject();
json.put("anchor", anchor);
json.put("text", message);

Expand All @@ -246,34 +251,35 @@ public void close() {
} catch (IOException ignored) { }
}

private JSONObject get(String url, String errorMessage) throws StashClientException {
private JsonObject get(String url, String errorMessage) throws StashClientException {
return performRequest(httpClient.prepareGet(url), null, HttpURLConnection.HTTP_OK, errorMessage);
}

private JSONObject post(String url, JSONObject body, String errorMessage) throws StashClientException {
private JsonObject post(String url, JsonObject body, String errorMessage) throws StashClientException {
return performRequest(httpClient.preparePost(url), body, HttpURLConnection.HTTP_OK, errorMessage);
}

private JSONObject postCreate(String url, JSONObject body, String errorMessage) throws StashClientException {
private JsonObject postCreate(String url, JsonObject body, String errorMessage) throws StashClientException {
return performRequest(httpClient.preparePost(url), body, HttpURLConnection.HTTP_CREATED, errorMessage);
}

private JSONObject delete(String url, int expectedStatusCode, String errorMessage) throws StashClientException {
private JsonObject delete(String url, int expectedStatusCode, String errorMessage) throws StashClientException {
return performRequest(httpClient.prepareDelete(url), null, expectedStatusCode, errorMessage);
}

private JSONObject delete(String url, String errorMessage) throws StashClientException {
private JsonObject delete(String url, String errorMessage) throws StashClientException {
return delete(url, HttpURLConnection.HTTP_NO_CONTENT, errorMessage);
}

private JSONObject put(String url, JSONObject body, String errorMessage) throws StashClientException {
private JsonObject put(String url, JsonObject body, String errorMessage) throws StashClientException {
return performRequest(httpClient.preparePut(url), body, HttpURLConnection.HTTP_OK, errorMessage);
}

private JSONObject performRequest(BoundRequestBuilder requestBuilder, JSONObject body, int expectedStatusCode, String errorMessage)
private JsonObject performRequest(BoundRequestBuilder requestBuilder, JsonObject body, int expectedStatusCode,
String errorMessage)
throws StashClientException {
if (body != null) {
requestBuilder.setBody(body.toString());
requestBuilder.setBody(body.toJson());
}
Realm realm = new Realm.Builder(credentials.getLogin(), credentials.getPassword())
.setUsePreemptiveAuth(true).setScheme(Realm.AuthScheme.BASIC).build();
Expand All @@ -285,21 +291,23 @@ private JSONObject performRequest(BoundRequestBuilder requestBuilder, JSONObject
try {
Response response = requestBuilder.execute().get(stashTimeout, TimeUnit.MILLISECONDS);

validateResponse(response, expectedStatusCode, errorMessage);
validateResponse(body, response, expectedStatusCode, errorMessage);
return extractResponse(response);
} catch (ExecutionException | TimeoutException | InterruptedException e) {
throw new StashClientException(e);
}
}

private static void validateResponse(Response response, int expectedStatusCode, String message) throws StashClientException {
private static void validateResponse(JsonObject body, Response response, int expectedStatusCode, String message) throws StashClientException {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure about this parameter.
If we keep it it should be named requestBody.
OTOH it seems weird to pass the body only for logging.
How about removing the exception from validateResponse(), making it return a bool instead and throwing the exception/logging from performRequest directly

int responseCode = response.getStatusCode();
if (responseCode != expectedStatusCode) {
LOGGER.debug("Request body {}", (body == null) ? null : body.toJson());
LOGGER.debug("Response {}", response);
throw new StashClientException(message + " Received " + responseCode + ": " + formatStashApiError(response));
}
}

private static JSONObject extractResponse(Response response) throws StashClientException {
private static JsonObject extractResponse(Response response) throws StashClientException {
String body = null;
body = response.getResponseBody();

Expand All @@ -308,22 +316,22 @@ private static JSONObject extractResponse(Response response) throws StashClientE
}

String contentType = response.getHeader("Content-Type");
if (!JSON.match(StringUtils.strip(contentType))) {
if (!JSON_CONTENT_TYPE.match(StringUtils.strip(contentType))) {
throw new StashClientException("Received response with type " + contentType + " instead of JSON");
}
try {
Object obj = new JSONParser().parse(body);
return (JSONObject)obj;
} catch (ParseException | ClassCastException e) {
Object obj = Jsoner.deserialize(body);
return (JsonObject) obj;
} catch (ClassCastException | DeserializationException e) {
throw new StashClientException("Could not parse JSON response " + e + "('" + body + "')", e);
}
}

private static String formatStashApiError(Response response) throws StashClientException {
JSONArray errors;
JSONObject responseJson = extractResponse(response);
JsonArray errors;
JsonObject responseJson = extractResponse(response);

errors = (JSONArray)responseJson.get("errors");
errors = (JsonArray) responseJson.get("errors");

if (errors == null) {
throw new StashClientException("Error response did not contain an errors object '" + responseJson + "'");
Expand All @@ -333,7 +341,7 @@ private static String formatStashApiError(Response response) throws StashClientE

for (Object o : errors) {
try {
JSONObject error = (JSONObject)o;
JsonObject error = (JsonObject) o;
errorParts.add((String)error.get("exceptionName") + ": " + (String)error.get("message"));
} catch (ClassCastException e) {
throw new StashClientException("Error response contained invalid error", e);
Expand Down
Loading