I tried to run provided code for jar 2.0.2 and now for 2.0.4 Both times received an error at line: int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size();
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array. at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106) at GetTCofTS.main(GetTCofTS.java:50)
I can overcome this error (since it is really not an array that is coming back) , but it won't resolve my problem, that I am trying to get not only the number of TestCases associated with the current TestSet, but list of TestCases - at least their formatted ID. Is it a bag in Rally?
public class GetTCofTS {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String applicationName = "RESTExampleFindTestCasesOfTestSet";
String workspaceRef = "/workspace/1111";
String projectRef = "/project/2222";
String wsapiVersion = "1.43";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
QueryRequest testSetRequest = new QueryRequest("TestSet");
testSetRequest.setWorkspace(workspaceRef);
restApi.setWsapiVersion(wsapiVersion);
testSetRequest.setFetch(new Fetch(new String[] {"Name", "TestCases", "FormattedID"}));
testSetRequest.setQueryFilter(new QueryFilter("Name", "=", "someTS"));
QueryResponse testSetQueryResponse = restApi.query(testSetRequest);
System.out.println("Successful: " + testSetQueryResponse.wasSuccessful());
System.out.println("Size: " + testSetQueryResponse.getTotalResultCount());
for (int i=0; i<testSetQueryResponse.getResults().size();i++){
JsonObject testSetJsonObject = testSetQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + testSetJsonObject.get("Name") + " ref: " + testSetJsonObject.get("_ref").getAsString() + " Test Cases: " + testSetJsonObject.get("TestCases"));
int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size();
System.out.println(numberOfTestCases);
if(numberOfTestCases>0){
for (int j=0;j<numberOfTestCases;j++){
System.out.println(testSetJsonObject.get("TestCases").getAsJsonArray().get(j).getAsJsonObject().get("FormattedID"));
}
}
}
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}
v2.0 is the preferred version going forward. The following small tweaks should get you up and going.
Instead of this (which works in 1.43 because the collection is returned):
int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size();
if(numberOfTestCases>0) {
for (int j=0;j<numberOfTestCases;j++) {
System.out.println(testSetJsonObject.get("TestCases").getAsJsonArray().get(j).getAsJsonObject().get("FormattedID"));
}
}
Do this:
//TestCases is an object with a Count and a ref to load the collection
int numberOfTestCases = testSetJsonObject.getAsJsonObject("TestCases").get("Count").getAsInt();
if(numberOfTestCases > 0) {
QueryRequest testCaseRequest = new QueryRequest(testSetJsonObject.getAsJsonObject("TestCases"));
testCaseRequest.setFetch(new Fetch("FormattedID"));
//load the collection
JsonArray testCases = restApi.query(testCaseRequest).getResults();
for (int j=0;j<numberOfTestCases;j++){
System.out.println(testCases.get(j).getAsJsonObject().get("FormattedID").getAsString());
}
}
Related
I have the following code:
#Controller
public class GatesController {
#RequestMapping ("/gates")
public static String qualityGates(String x) throws IOException {
try {
System.out.println("\n------QualityGates------");
URL toConnect = new URL(x);
HttpURLConnection con = (HttpURLConnection) toConnect.openConnection();
System.out.println("Sending 'GET' request to URL : " + x);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//Cast the JSON-File to a JSONObject
JSONObject res = new JSONObject(response.toString());
JSONArray gates = new JSONArray(res.getJSONObject("projectStatus").getJSONArray("conditions").toString());
JSONObject test = new JSONObject(res.getJSONObject("projectStatus").toString());
String a = ("\nThe current Project-Status is: " + test.get("status") + "\n");
String b = "";
for (int i = 0; i < gates.length(); i++) {
String status = gates.getJSONObject(i).getString("status");
String metric = gates.getJSONObject(i).getString("metricKey");
b = b + ("<\b>Status: " + status + " | Metric: " + metric);
}
System.out.println(a+b);
return a + b;
} catch (Exception e) {
System.out.println(e);
return String.format("Error");
}
}
#SpringBootApplication
#RestController
public class SonarQualityGatesApplication {
public static void main(String[] args) throws IOException {
ConfigurableApplicationContext context=SpringApplication.run(SonarQualityGatesApplication.class, args);
TestController b = context.getBean(TestController.class);
}
#GetMapping("/hello")
public String hello(#RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
#GetMapping("/gates")
public String gates() throws IOException {
String temp = qualityGates("http://localhost:9000/api/qualitygates/project_status?projectKey={PROJECT_KEY}");
return temp;
}
}
The problem is currently the website looks like this:
Website_Curr
But I want a new line for every metric not in one row.
As you see I tried to add <\b> at the string connotation
Do you have an idea how to fix this? It is my first web application I am a bit stuck.
I appreciate every help!
Your "<\b>" breaks it. If you remove it and add a newLine "\n" it should work.
Like this:
String a = ("\nThe current Project-Status is: " + test.get("status") + "\n");
String b = "";
for (int i = 0; i < gates.length(); i++) {
status = gates.getJSONObject(i).getString("status");
String metric = gates.getJSONObject(i).getString("metricKey");
b = b + ("Status: " + status + " | Metric: " + metric + "\n");
}
Also you are returning plain text. So, to display it correctly add "produces = "text/plain" to return the formatted String.
#GetMapping(value = "/gates", produces = "text/plain")
Then your output will be displayed with line breaks. This way u can apply further formatting.
I am new to Rally API. I have been assigned task to get result of TestCase in java using Rally API. Can someone please help me with a sample program. Also please tell me how to get Workspace name in rally.
Here is a code example based in Rally API Toolkit for Java. Also see WS API documentation for details of TestCase and TestCaseResult objects.
public class GetTestCaseResults {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String applicationName = "Example: get Results of TestCase";
String projectRef = "/project/12345"; //user your own project OID
String apiKey = "_abc123";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setProject(projectRef);
testCaseRequest.setFetch(new Fetch(new String[] {"FormattedID","Results","LastVerdict"}));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "TC3"));
//testCaseRequest.setLimit(25000);
testCaseRequest.setScopedDown(false);
testCaseRequest.setScopedUp(false);
QueryResponse testCaseResponse = restApi.query(testCaseRequest);
System.out.println("Successful: " + testCaseResponse.wasSuccessful());
System.out.println("Size: " + testCaseResponse.getTotalResultCount());
int totalResults = 0;
for (int i=0; i<testCaseResponse.getResults().size();i++){
JsonObject testCaseJsonObject = testCaseResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + testCaseJsonObject.get("Name") + " FormattedID: " + testCaseJsonObject.get("FormattedID") + " LastVerdict: " + testCaseJsonObject.get("LastVerdict"));
int numberOfResults = testCaseJsonObject.getAsJsonObject("Results").get("Count").getAsInt();
if(numberOfResults > 0) {
totalResults += numberOfResults;
QueryRequest resultsRequest = new QueryRequest(testCaseJsonObject.getAsJsonObject("Results"));
resultsRequest.setFetch(new Fetch("Verdict","Date"));
//load the collection
JsonArray results = restApi.query(resultsRequest).getResults();
for (int j=0;j<numberOfResults;j++){
System.out.println("Name: " + results.get(j).getAsJsonObject().get("Verdict") + results.get(j).getAsJsonObject().get("Date").getAsString());
}
}
}
System.out.println("Total number of results: " + totalResults);
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}
I'm not an expert at JSON so I'm not sure if I'm missing something obviously. But, what I'm trying to do is to parse this:
[{"name":"Djinnibone"},{"name":"Djinnibutt","changedToAt":1413217187000},{"name":"Djinnibone","changedToAt":1413217202000},{"name":"TEsty123","changedToAt":1423048173000},{"name":"Djinnibone","changedToAt":1423048202000}]
I don't want to get Djinnibone only the rest of the names following it. What I've managed to create is this. It give the right number of names. but they are all null. In this case null,null,null,null .
public String getHistory(UUID uuid) throws Exception {
String history = "";
HttpURLConnection connection = (HttpURLConnection) new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names").openConnection();
JSONArray response = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = new JSONObject();
for(int index = 1; index < response.size(); index++) {
jsonObject.get(response.get(index));
String name = (String) jsonObject.get("name");
if(index < response.size()) {
history = history + name + ",";
} else {
history = history + name + ".";
}
}
return history == "" ? history = "none." : history;
}
Thanks for any help!
You're almost there, you're getting each JSONObject from the array but you're not using it correctly. You simply need to change your code like this in order to extract each object and use it directly, no need for an intermediate JSONObject creation:
public String getHistory(UUID uuid) throws Exception {
String history = "";
HttpURLConnection connection = (HttpURLConnection) new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names").openConnection();
JSONArray response = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for(int index = 1; index < response.size(); index++) {
JSONObject jsonObject = response.get(index);
String name = (String) jsonObject.get("name");
if(index < response.size()) {
history = history + name + ",";
} else {
history = history + name + ".";
}
}
return history == "" ? history = "none." : history;
}
I tried to request a large amount of data from freebase. But I got error message "HTTP response code: 403". Did anyone have similar problem before?
Here is my code
private static final String service_url = "https://www.googleapis.com/freebase/v1/mqlread";
public static void main(String[] args)
{
try
{
String cursor = "";
String urlStr_initial = service_url + "?query=" + URLEncoder.encode(getQuery(), "UTF-8") + "&cursor";
URL url = new URL(urlStr_initial);
List<Freebase> list = new ArrayList<Freebase>();
Freebase f_b;
do
{
HttpURLConnection url_con = (HttpURLConnection)url.openConnection();
url_con.addRequestProperty("User-Agent", "Mozilla/4.76");
StringBuilder str_builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(url_con.getInputStream()));
String line;
while((line = reader.readLine()) != null)
{
str_builder.append(line);
}
String response = str_builder.toString();
JSONObject j_object = new JSONObject(response);
if(j_object.has("result"))
{
JSONArray j_array = j_object.getJSONArray("result");
for(int i = 0; i < j_array.length(); i++)
{
JSONObject j_o = j_array.getJSONObject(i);
if(j_o.has("id") == true && j_o.has("name"))
{
String id = j_o.getString("id");
String name = j_o.getString("name");
System.out.println("ID: " + id + " / Name:" + name);
f_b = new Freebase(id, name);
if(f_b != null)
{
list.add(f_b);
}
else
{
System.out.println("Null value in Freebase");
}
}
}
}
else
{
System.out.println("There is no \"result\" key in JASON object");
}
if(j_object.has("cursor"))
{
cursor = j_object.get("cursor").toString();
}
else
{
cursor = "false";
}
String urlStr = urlStr_initial + "=" + cursor;
url = new URL(urlStr);
}while( !cursor.equalsIgnoreCase("false"));
if(list != null)
{
TextFile tf = new TextFile();
tf.writeToFile(list);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static String getQuery()
{
return "[{"
+ "\"name\": null,"
+ "\"id\": null,"
+ "\"type\":\"/people/person\","
+ "\"limit\": 500"
+ "}]";
}
You don't say what "large" is, but the API isn't designed for bulk downloads. You should be using the data dumps for that.
There's usually more detailed error message included with the HTTP response code. If, for example, it says 403 - Forbidden - API key required, it means you didn't include your API key (I don't see where you include it in your code). If it says 403 - Forbidden - quota exceeded it means you've exceeded your request quota (you can look on the API console to see how much quota you have remaining).
I want to use WikipediaTokenizer in lucene project - http://lucene.apache.org/java/3_0_2/api/contrib-wikipedia/org/apache/lucene/wikipedia/analysis/WikipediaTokenizer.html But I never used lucene. I just want to convert a wikipedia string into a list of tokens. But, I see that there are only four methods available in this class, end, incrementToken, reset, reset(reader). Can someone point me to an example to use it.
Thank you.
In Lucene 3.0, next() method is removed. Now you should use incrementToken to iterate through the tokens and it returns false when you reach the end of the input stream. To obtain the each token, you should use the methods of the AttributeSource class. Depending on the attributes that you want to obtain (term, type, payload etc), you need to add the class type of the corresponding attribute to your tokenizer using addAttribute method.
Following partial code sample is from the test class of the WikipediaTokenizer which you can find if you download the source code of the Lucene.
...
WikipediaTokenizer tf = new WikipediaTokenizer(new StringReader(test));
int count = 0;
int numItalics = 0;
int numBoldItalics = 0;
int numCategory = 0;
int numCitation = 0;
TermAttribute termAtt = tf.addAttribute(TermAttribute.class);
TypeAttribute typeAtt = tf.addAttribute(TypeAttribute.class);
while (tf.incrementToken()) {
String tokText = termAtt.term();
//System.out.println("Text: " + tokText + " Type: " + token.type());
String expectedType = (String) tcm.get(tokText);
assertTrue("expectedType is null and it shouldn't be for: " + tf.toString(), expectedType != null);
assertTrue(typeAtt.type() + " is not equal to " + expectedType + " for " + tf.toString(), typeAtt.type().equals(expectedType) == true);
count++;
if (typeAtt.type().equals(WikipediaTokenizer.ITALICS) == true){
numItalics++;
} else if (typeAtt.type().equals(WikipediaTokenizer.BOLD_ITALICS) == true){
numBoldItalics++;
} else if (typeAtt.type().equals(WikipediaTokenizer.CATEGORY) == true){
numCategory++;
}
else if (typeAtt.type().equals(WikipediaTokenizer.CITATION) == true){
numCitation++;
}
}
...
WikipediaTokenizer tf = new WikipediaTokenizer(new StringReader(test));
Token token = new Token();
token = tf.next(token);
http://www.javadocexamples.com/java_source/org/apache/lucene/wikipedia/analysis/WikipediaTokenizerTest.java.html
Regards
public class WikipediaTokenizerTest {
static Logger logger = Logger.getLogger(WikipediaTokenizerTest.class);
protected static final String LINK_PHRASES = "click [[link here again]] click [http://lucene.apache.org here again] [[Category:a b c d]]";
public WikipediaTokenizer testSimple() throws Exception {
String text = "This is a [[Category:foo]]";
return new WikipediaTokenizer(new StringReader(text));
}
public static void main(String[] args){
WikipediaTokenizerTest wtt = new WikipediaTokenizerTest();
try {
WikipediaTokenizer x = wtt.testSimple();
logger.info(x.hasAttributes());
Token token = new Token();
int count = 0;
int numItalics = 0;
int numBoldItalics = 0;
int numCategory = 0;
int numCitation = 0;
while (x.incrementToken() == true) {
logger.info("seen something");
}
} catch(Exception e){
logger.error("Exception while tokenizing Wiki Text: " + e.getMessage());
}
}