Skip to content

Commit

Permalink
Handle response codes
Browse files Browse the repository at this point in the history
Handle the response code recieved from Graphql API

Correct the message thrown in Exception
  • Loading branch information
kasunsiyambalapitiya committed Mar 21, 2017
1 parent 772a100 commit d28a361
Show file tree
Hide file tree
Showing 5 changed files with 114 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ public void readBlameReceivedForAFile(JSONObject rootJsonObject, ArrayList<Strin
}
break;
} else {
continue;
continue; // to skip to the next JSON Object in the rangeJSONArray
}
}
startingLineNo++; // to check for other line numbers
Expand All @@ -350,7 +350,7 @@ public void readBlameReceivedForAFile(JSONObject rootJsonObject, ArrayList<Strin
JSONObject nodeJSONObject = (JSONObject) edgeJSONObject.get(GITHUB_GRAPHQL_API_NODE_KEY_STRING);
String urlOfTheParentCommit = (String) nodeJSONObject.get(GITHUB_GRAPHQL_API_URL_KEY_STRING); // this contain the URL of the parent commit
String commitHash = (String) StringUtils.substringAfter(urlOfTheParentCommit, "commit/");
commitHashesOfTheParent.add(commitHash);
commitHashesOfTheParent.add(commitHash); // commitHashesof the parent for the selected file

});
logger.info("Parent Commits hashes of the lines which are being fixed by the patch are saved to commitHashesOfTheParent SET successfully ");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,50 +56,58 @@ public Object callGraphQlApi(JSONObject queryObject, String gitHubToken) throws

CloseableHttpClient client = null;
CloseableHttpResponse response = null;
client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://api.github.com/graphql");
httpPost.addHeader("Authorization", "Bearer " + gitHubToken);
httpPost.addHeader("Accept", "application/json");
BufferedReader bufferedReader = null;

Object returnedObject = null;

try {
client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://api.github.com/graphql");
httpPost.addHeader("Authorization", "Bearer " + gitHubToken);
httpPost.addHeader("Accept", "application/json");
StringEntity entity = new StringEntity(queryObject.toString());
httpPost.setEntity(entity);
response = client.execute(httpPost);
} catch (UnsupportedEncodingException e) {
throw new CodeQualityMatricesException("Encoding error occured before calling the github graphQL API", e);
} catch (ClientProtocolException e) {
throw new CodeQualityMatricesException("Client protocol exception occurred when calling the github graphQL API", e);
} catch (IOException e) {
throw new CodeQualityMatricesException("IO Exception occured when calling the github graphQL API", e);
}
int responseCode = response.getStatusLine().getStatusCode();

BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
switch (responseCode) {
case 200:

String jsonText = stringBuilder.toString();
logger.info("The response received from the Github GraphQL converted to a JSON text successfully");
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}

Object json = new JSONTokener(jsonText).nextValue(); // gives an object http://stackoverflow.com/questions/14685777/how-to-check-if-response-from-server-is-jsonaobject-or-jsonarray
String jsonText = stringBuilder.toString();
logger.info("The response received from the Github GraphQL converted to a JSON text successfully");

if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
returnedObject = jsonObject;
logger.info("JSONObject was returned successfully after calling the GraphQL API");
} else if (json instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) json;
returnedObject = jsonArray;
logger.info("JSONArray was returned successfully after calling the GraphQL API");
Object json = new JSONTokener(jsonText).nextValue(); // gives an object http://stackoverflow.com/questions/14685777/how-to-check-if-response-from-server-is-jsonaobject-or-jsonarray

}
if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
returnedObject = jsonObject;
logger.info("JSONObject was returned successfully after calling the GraphQL API");
} else if (json instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) json;
returnedObject = jsonArray;
logger.info("JSONArray was returned successfully after calling the GraphQL API");
}
break;

// System.out.println(stringBuilder.toString());
case 401:
// to handle Response code 401: Unauthorized
throw new CodeQualityMatricesException("Response code 401 : Git hub access token is invalid");
default:
returnedObject = null;
}
} catch (UnsupportedEncodingException e) {
throw new CodeQualityMatricesException("Encoding error occured before calling the github graphQL API", e);
} catch (ClientProtocolException e) {
throw new CodeQualityMatricesException("Client protocol exception occurred when calling the github graphQL API", e);
} catch (IOException e) {
throw new CodeQualityMatricesException("IO Exception occured when calling the github graphQL API", e);
} catch (Exception e) {
throw new CodeQualityMatricesException("Exception occurred when reading the response received from github graphQL API", e);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,47 +26,53 @@
/**
* This is the class having the main method of this application
* PMT Access token, patch id and github access token
* should be passed as command line arguments when running the application
* should be passed in order as command line arguments when running the application
*/
public class MainClass {
private final static Logger logger = Logger.getLogger(MainClass.class);

public static void main(String[] args) {
logger.info(" Main method got executed");
if (args.length==3) {

String pmtToken = args[0];
String patchId = args[1];
String pmtToken = args[0];
String patchId = args[1];

String pmtUrl = "http://umt.private.wso2.com:8765/codequalitymatricesapi/1.0.0//properties?path=/_system/governance/patchs/" + patchId;
String pmtUrl = "http://umt.private.wso2.com:9765/codequalitymatricesapi/1.0.0//properties?path=/_system/governance/patchs/" + patchId;

RestApiCaller restApiCaller = new RestApiCaller();
JSONArray jsonArray = null;
try {
jsonArray = (JSONArray) restApiCaller.callApi(pmtUrl, pmtToken, false, false);
} catch (CodeQualityMatricesException e) {
logger.error(e.getMessage(), e.getCause());
System.exit(1);
}
logger.info("JSON response is received successfully from WSO2 PMT for the given patch " + args[1]);
RestApiCaller restApiCaller = new RestApiCaller();
JSONArray jsonArray = null;
try {
jsonArray = (JSONArray) restApiCaller.callApi(pmtUrl, pmtToken, false, false);
} catch (CodeQualityMatricesException e) {
logger.error(e.getMessage(), e.getCause());
System.exit(1);
}
logger.info("JSON response is received successfully from WSO2 PMT for the given patch " + args[1]);

Pmt pmt = new Pmt();
String[] commitsInTheGivenPatch = null;
if (jsonArray != null) {
commitsInTheGivenPatch = pmt.getPublicGitCommitHashes(jsonArray);
}
logger.info("Commits received from WSO2 PMT are saved in an array successfully");
Pmt pmt = new Pmt();
String[] commitsInTheGivenPatch = null;
if (jsonArray != null) {
commitsInTheGivenPatch = pmt.getPublicGitCommitHashes(jsonArray);
}
logger.info("Commits received from WSO2 PMT are saved in an array successfully");

String gitHubToken = args[2];
ChangesFinder changesFinder = new ChangesFinder();
Set<String> commitHashObtainedForPRReview = null;
if (commitsInTheGivenPatch != null) {
commitHashObtainedForPRReview = changesFinder.obtainRepoNamesForCommitHashes(gitHubToken, commitsInTheGivenPatch, restApiCaller);
}
logger.info("Author commits that introduce bug lines of code to the repository are saved in commitHashObtainedForPRReview SET successfully");
String gitHubToken = args[2];
ChangesFinder changesFinder = new ChangesFinder();
Set<String> commitHashObtainedForPRReview = null;
if (commitsInTheGivenPatch != null) {
commitHashObtainedForPRReview = changesFinder.obtainRepoNamesForCommitHashes(gitHubToken, commitsInTheGivenPatch, restApiCaller);
}
logger.info("Author commits that introduce bug lines of code to the repository are saved in commitHashObtainedForPRReview SET successfully");

Reviewer reviewer = new Reviewer();
if (commitHashObtainedForPRReview != null) {
reviewer.findReviewers(commitHashObtainedForPRReview, gitHubToken, restApiCaller);
Reviewer reviewer = new Reviewer();
if (commitHashObtainedForPRReview != null) {
reviewer.findReviewers(commitHashObtainedForPRReview, gitHubToken, restApiCaller);
}
}
else{
logger.error("at least one of the command line arguments are null.");
System.exit(4);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,41 +76,57 @@ public Object callApi(String URL, String accessToken, boolean requireCommitHeade
}

httpResponse = httpclient.execute(httpGet);
bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
int responseCode = httpResponse.getStatusLine().getStatusCode(); // to get the response code

switch (responseCode) {
case 200:
//success
bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}

// creating a JSON object from the response
String JSONText = stringBuilder.toString();
Object json = new JSONTokener(JSONText).nextValue(); // gives an object http://stackoverflow.com/questions/14685777/how-to-check-if-response-from-server-is-jsonaobject-or-jsonarray

if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
returnedObject = jsonObject;
} else if (json instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) json;
returnedObject = jsonArray;
}
logger.info("JSON response is passed after calling the given REST API");
break;
case 401:
// to handle Response code 401: Unauthorized
throw new CodeQualityMatricesException("Response code 401 : Git hub access token is invalid");
case 403:
// to handle invalid credentials
throw new CodeQualityMatricesException("Response Code:403 Invalid Credentials, insert a correct token for PMT");
case 404:
// to handle invalid patch
throw new CodeQualityMatricesException("Response Code 404: Patch not found, enter a valid patch");
default:
returnedObject = null;
}

// creating a JSON object from the response
String JSONText = stringBuilder.toString();
Object json = new JSONTokener(JSONText).nextValue(); // gives an object http://stackoverflow.com/questions/14685777/how-to-check-if-response-from-server-is-jsonaobject-or-jsonarray

if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
returnedObject = jsonObject;
} else if (json instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) json;
returnedObject = jsonArray;
}
logger.info("JSON response is passed after calling the given REST API");

} catch (ClientProtocolException e) {
throw new CodeQualityMatricesException("ClientProtocolException when calling the REST API", e);

} catch (IOException e) {
throw new CodeQualityMatricesException("IOException occurred when calling the REST API", e);
} finally {

if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
throw new CodeQualityMatricesException("IOException occurred when closing the BufferedReader", e);
}
}

if (httpResponse != null) {
try {
httpResponse.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public Map<String, ArrayList<String>> getFilesChanged(String repositoryName, Str
logger.info("for" + commitHash + " on the " + repositoryName + " repository, files changed and their relevant changed line ranges added to the arraylists successfully");
mapWithFileNamesAndPatches.put("fileNames", fileNames);
mapWithFileNamesAndPatches.put("patchString", patchString);
logger.info("map with the modified file names with their relevant modified line ranges are saved successfully");
} catch (IOException e) {
throw new CodeQualityMatricesException("IO Exception occurred when getting the commit with the given SHA form the given repository ", e);
}
Expand Down

0 comments on commit d28a361

Please sign in to comment.