Im working on a MapReduce (Map only task) which reads the JSON file and extracts the elements from JSON input. Input data:
{"type":"cloud_monitor","format":"default","version":"1.0","id":"71101cb85441995d11a43bb","start":"1413585245.921","cp":"254623","message":{"proto":"http","protoVer":"1.1","status":"403","cliIP":"23.79.231.14","reqPort":"80","reqHost":"ksd.metareactor.com","reqMethod":"GET","reqPath":"%2findex.php","reqQuery":"path%3d57%26product_id%3d49%26route%3d%255Cwinnt%255Cwin.ini%2500.","respCT":"text/html","respLen":"286","bytes":"286","UA":"mozilla-saturn","fwdHost":"origin-demo2-akamaized.scoe-sil.net"},"reqHdr":{"accEnc":"gzip,%20deflate","cookie":"PHPSESSID%3dkkqoodvfe0rt9l7lbvqghk6e15%3bcurrency%3dUSD%3blanguage%3den"}}
I've declared String variables for the JSON Arrays: Message & reqHdr and you can see them in the context.write() method
Map Class:
public class JsonMapper extends Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String type;
String format;
String version;
String id;
String start;
String cp;
// variables for message and reqHdr
String[] line = value.toString().split("\\n");
if (line.length > 0) {
for(int i=0; i<line.length; i++) {
try {
JSONObject jsonobj = new JSONObject(line[i]);
type = (String) jsonobj.get("type");
format = (String) jsonobj.get("format");
version = (String) jsonobj.get("version");
id = (String) jsonobj.get("id");
start = (String) jsonobj.get("start");
cp = (String) jsonobj.get("cp");
// Message Variable array
JSONArray messageArray = (JSONArray) jsonobj.get("message");
for(int j=0; j<messageArray.length(); j++) {
JSONObject jsonmessageobject = messageArray.getJSONObject(j);
proto = jsonmessageobject.getString("proto");
protoVer = jsonmessageobject.getString("protoVer");
cliIP = jsonmessageobject.getString("cliIP");
reqPort = jsonmessageobject.getString("reqPort");
reqHost = jsonmessageobject.getString("reqHost");
reqMethod = jsonmessageobject.getString("reqMethod");
reqPath = jsonmessageobject.getString("reqPath");
reqQuery = jsonmessageobject.getString("reqQuery");
reqCT = jsonmessageobject.getString("reqCT");
reqLen = jsonmessageobject.getString("reqLen");
sslVer = jsonmessageobject.getString("sslVer");
status = jsonmessageobject.getString("status");
redirURL = jsonmessageobject.getString("redirURL");
respCT = jsonmessageobject.getString("respCT");
respLen = jsonmessageobject.getString("respLen");
bytes = jsonmessageobject.getString("bytes");
UA = jsonmessageobject.getString("UA");
fwdHost = jsonmessageobject.getString("fwdHost");
}
// reqHdr variable array
JSONArray reqHdrArray = (JSONArray) jsonobj.get("reqHdr");
for(int k=0; k<reqHdrArray.length(); k++) {
JSONObject jsonreqHdrobject = reqHdrArray.getJSONObject(i);
accEnc = jsonreqHdrobject.getString("accEnc");
accLang = jsonreqHdrobject.getString("accLang");
auth = jsonreqHdrobject.getString("auth");
reqHdr_cacheCtl = jsonreqHdrobject.getString("cacheCtl");
reqHdr_conn = jsonreqHdrobject.getString("conn");
reqHdr_contMD5 = jsonreqHdrobject.getString("contMD5");
cookie = jsonreqHdrobject.getString("cookie");
DNT = jsonreqHdrobject.getString("DNT");
expect = jsonreqHdrobject.getString("expect");
ifMatch = jsonreqHdrobject.getString("ifMatch");
ifMod = jsonreqHdrobject.getString("ifMod");
ifNone = jsonreqHdrobject.getString("ifNone");
ifRange = jsonreqHdrobject.getString("ifRange");
ifUnmod = jsonreqHdrobject.getString("ifUnmod");
range = jsonreqHdrobject.getString("range");
referer = jsonreqHdrobject.getString("referer");
te = jsonreqHdrobject.getString("te");
upgrade = jsonreqHdrobject.getString("upgrade");
reqHdr_via = jsonreqHdrobject.getString("via");
xFrwdFor = jsonreqHdrobject.getString("xFrwdFor");
xReqWith = jsonreqHdrobject.getString("xReqWith");
}
context.write(new Text("cloud_monitor"), new Text(type + format + version + id + start + cp + proto + protoVer + cliIP + reqPort +
reqHost + reqMethod + reqPath + reqQuery + reqCT + reqLen + sslVer + status + redirURL + respCT + respLen + bytes + UA + fwdHost + accEnc + accLang + auth +
reqHdr_cacheCtl + reqHdr_conn + reqHdr_contMD5 + cookie + DNT + expect + ifMatch + ifMod + ifNone + ifRange + ifUnmod + range + referer + te +
upgrade + reqHdr_via + xFrwdFor + xReqWith ));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
I'm getting the following error message:
Error: java.lang.ClassNotFoundException: org.json.JSONException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.Class.forName(Class.java:270)
at org.apache.hadoop.conf.Configuration.getClassByNameOrNull(Configuration.java:2138)
at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2103)
at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2197)
at org.apache.hadoop.mapreduce.task.JobContextImpl.getMapperClass(JobContextImpl.java:196)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:745)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1693)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
Could anyone tell me if I am doing the JSON Parsing correctly, especially the JSON Arrays (message, reqHdr) part or how I can fix the bug ?
You have to download the org.json far file, and then add it to your project.
You can download the jar : here
Related
I'm trying to take the JSON from BITTREX and parse it and present it to the screen in Android Studio. This works for me with test JSON I made myself plus other requests i have made using the same API. However, when i go to use the actual request I need i get the following error :
JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
This is the request used: https://bittrex.com/api/v1.1/public/getmarketsummaries
API Documentation
Here is the Code :
public class fetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
JSONArray myJsonArray = new JSONArray(data); //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("Timestamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
MainActivity.data.setText(this.dataParsed);
}
}
Any thoughts would be greatly appreciated. Thanks :)
**UPDATE - SOLVED **
I added the following line before the loop and it solved the issue.
//target the "result" Array of objects(BTC,LTC,ETH) and map them to a JsonArray for parsing
JSONArray myJsonArray = myJsonObj.getJSONArray("result");
The exception is perfectly valid. Your trying to convert json object into json array. Try below code
remove "\n" character at the end.
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n")
add below logs
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
Log.debug("api_response","api-response->"+data);
and try below code
if(data!= null){ // add this if condition too.
JSONObject jsonObj = new JSONObject(data);
JSONArray myJsonArray = jsonObj.getJSONArray("result"); ; //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
The json data returned by the API is in the following format:
{
"success": true,
"message": "",
"result": [
{
},
{
}
]
}
So you need to get the whole data as JSONObject first, then from it you can extract the JSONArray with the "result" key.
The code is something like this:
// get the JSONObject from the data
JSONObject jsonObject = new JSONObject(data);
// then you get the array with result key
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
// now you can process the item here.
}
UPDATE
The above code is working. The remaining problem is there is a typo in your key. You're using "Timestamp" but the existing key is "TimeStamp". Here is the working code:
public class FetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
Log.d("DATA", "line = " + line);
}
Log.d("DATA", "construct data = " + data);
JSONObject jsonObject = new JSONObject(data);
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("TimeStamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
//MainActivity.data.setText(this.dataParsed);
Log.d("DATA", "data = " + this.dataParsed);
}
}
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();
}
}
}
}
How can I split a flat string based on 0102**? string tokenizer is working for only **. Is there any way to split based on 0102**? Please suggest
Here is my complete method
private String handleCibil(InterfaceRequestVO ifmReqDto, String szExtIntType) throws MalformedURLException, org.apache.axis.AxisFault, RemoteException {
/* Declaration and initiliazation */
ConfVO confvo = ifmReqDto.getExtConfVo();
String szResponse = null;
String cibilResponse = null;
String errorResponse = null;
String endpointURL = null;
long timeOut = confvo.getBurMgr().getBurInfo(szExtIntType).getTimeOut();
endpointURL = formWebServiceURL(confvo, szExtIntType);
URL url = new URL(endpointURL);
log.debug("Input xml for cibil "+ifmReqDto.getIfmReqXML());
BasicHttpStub stub= new BasicHttpStub(url,new org.apache.axis.client.Service());
szResponse = stub.executeXMLString(ifmReqDto.getIfmReqXML());
//szResponse=szResponse.replaceAll("&", "&");
log.debug("szResponse "+szResponse);
/* Validate if the obtained response is as expected by IFM */
try {
extDao = new ExtInterfaceXMLTransDAO(ifmReqDto.getSemCallNo(), ifmReqDto.getIdService());
extDao.updateRqstRespXML10g(ifmReqDto.getInterfaceReqNum(), szResponse, GGIConstants.IFM_RESPONSE);
//log.debug("CIBIL_RESPONSE_XPATH " + GGIConstants.CIBIL_RESPONSE_XPATH);
Document xmlDocument = DocumentHelper.parseText(szResponse);
String xPath = GGIConstants.RESPONSE_XPATH;
List<Node> nodes = xmlDocument.selectNodes(xPath);
for (Node node : nodes) {
String keyValue = node.valueOf(GGIConstants.RESPONSE_XPATH_KEY);
// log.debug("keyValue : " + keyValue);
if (keyValue.equalsIgnoreCase(GGIConstants.RESPONSE_XPATH_KEY_VALUE)) {
// log.debug("node value : " + node.getText());
cibilResponse = node.getText();
}
}
log.debug("cibilResponse " + cibilResponse);
String errorResponseXPATH = GGIConstants.CIBIL_ERROR_RESPONSE_XPATH;
List<Node> errorResponseNode = xmlDocument.selectNodes(errorResponseXPATH);
for (Node node : errorResponseNode) {
errorResponse = node.getText();
}
log.debug("errorResponse " + errorResponse);
if(cibilResponse!=null && cibilResponse.length()>0)
{
StringTokenizer cibilResponseResults = new StringTokenizer(cibilResponse,"**");
String tempResponse="";
ArrayList probableMatchList = new ArrayList();
while (cibilResponseResults.hasMoreElements()) {
tempResponse = (String) cibilResponseResults.nextElement();
if(tempResponse.length()>=80)
{
String memberRefNo = tempResponse.substring(69, 80).replaceAll(" ", "");
log.debug("memberRefNo " + memberRefNo);
if (memberRefNo.length() > 0) {
if (Integer.parseInt(memberRefNo) > 0) {
cibilResponse = tempResponse;
cibilResponse = cibilResponse+"**";
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
cibilResponse = tempResponse+"**";
}
}
log.debug("After finding the Member reference number cibilResponse " + cibilResponse);
log.debug("After finding the Probable reference list " + probableMatchList);
// TKN 008
cibilResponse=StringEscapeUtils.unescapeXml(cibilResponse).replaceAll("[^\\x20-\\x7e]","");
ifmReqDto.setIfmTransformedResult(cibilResponse);
ifmReqDto.setProbableMatchList(probableMatchList);
}
if (errorResponse!=null && errorResponse.length()>0) {
throw new GenericInterfaceException(errorResponse
+ " for the seq_request " + ifmReqDto.getSeqRequest() + " Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.CIBIL_ERROR_CODE);
}
else if (cibilResponse==null || StringUtils.isEmpty(cibilResponse) ) {
throw new GenericInterfaceException("Cibil TUEF response is empty >> cibil Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.INTERFACE_ERROR_RESPONSE);
}
/* Setting Instinct response to ifmReqDto object */
} catch (SQLException e) {
log.error("SQLException while connecting to DataBase. Exception message is ", e);
throw new GenericInterfaceException("SQLException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.DB_OPERATION_ERROR);
} catch (GenericInterfaceException exp) {
log.error("Exception occured while valid:", exp);
throw exp;
} catch (Exception exp) {
log.error("Exception occured while valid:", exp);
throw new GenericInterfaceException("GeneralException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.UNKNOWN_ERROR);
}
return szResponse;
}
I recommend checking out the Java documentation, it provides a really good reference to start with. The .split method uses a regex to split up a string based on a delimiter.
String[] tokens = myString.split("0102\\*\\*");
For now I suspect that you forgot to escape * in split regex.
Try maybe
String[] resutl = yourString.split("0102\\*\\*");
In case you want * to represent any character then use . instead of *
String[] resutl = yourString.split("0102..");
In case you want * to represent any digit use \\d instead
String[] resutl = yourString.split("0102\\d\\d");
String string = "blabla0102**dada";
String[] parts = string.split("0102\\*\\*");
String part1 = parts[0]; // blabla
String part2 = parts[1]; // dada
Here we have a String: "blabla0102**dada", we call it string. Every String object has a method split(), using this we can split a string on anything we desire.
Do you mean literally split by "0102**"? Couldn't you use regex for that?
String[] tokens = "My text 0102** hello!".split("0102\\*\\*");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
I created a button that allows to create a zip file., the function that zips the file works correctly, but when I call her via the button (in the JS file) it crashes and it gives a blank page (I think I do not manage the output stream)
would please an idea
here is my code:
Button
isc.ToolStripButton.create({
ID: "BooksApp_GetXmlImage_Button"
,autoDraw:false
,icon: getUIIcon("icon_xml_16")
,prompt: getUIMsg("book_report_get_xml",4)
,showHover:true
,hoverStyle:"book_hover_style"
,click : function () {
BooksApp_Action_loadFile("objx");
// isc.say("test");
}
});
function to call the zipfile() method:
function BooksApp_Action_loadFile(p_UsedFormat) {
var tmpBookID = BooksApp_Application.FP_BookID;
var tmpIDs = BooksApp_Application.FP_fct_getSelectedPOVIDs();
var tmpUsr_ID = FPIUser.FP_fct_getID();
var tmpFormat = p_UsedFormat;
var showInWindow=false;
books_objects.exportData(
{
r_book_idnum : tmpBookID
,sBook_ID : tmpBookID
,sPOV_IDs : tmpIDs
,sUser_ID : tmpUsr_ID
,sFormat : tmpFormat
}
,{ operationId: "customExport"
,exportDisplay: (showInWindow ? "window" : "download") }
,function (dsResponse, data, dsRequest) {
//Never called
BooksApp_Action_Log("BooksApp_Action_loadFile:"+data);
}
);
}
customExport() function
public static String customExport(RPCManager rpc,
HttpServletResponse response) throws Exception {
String sReturn = _Return_OK;
try {
// setting doCustomResponse() notifies the RPCManager that we'll
// bypass RPCManager.send
// and instead write directly to the servletResponse output stream
rpc.doCustomResponse();
RequestContext.setNoCacheHeaders(response);
writeServerDebug("customExport : start");
DSRequest req = rpc.getDSRequest();
List<?> results = req.execute().getDataList();
String sReqData = (String) req.getParameter("exportDisplay");
String sReqData_sBook_ID = "" + req.getCriteriaValue("sBook_ID");
String sReqData_sPOV_IDs = "" + req.getCriteriaValue("sPOV_IDs");
String sReqData_sUser_ID = "" + req.getCriteriaValue("sUser_ID");
String sReqData_sFormat = "" + req.getCriteriaValue("sFormat");
StringBuilder content = new StringBuilder("get (sReqData:"
+ sReqData + ",sBook_ID:" + sReqData_sBook_ID
+ ",sPOV_IDs:" + sReqData_sPOV_IDs + ",sUser_ID:"
+ sReqData_sUser_ID + ",sFormat:" + sReqData_sFormat + ")"
+ results.size() + " line(s):");
for (Iterator<?> i = results.iterator(); i.hasNext();) {
Map<?, ?> record = (Map<?, ?>) i.next();
content.append("\n" + Books.Column_IDNum + ":"
+ record.get(Books.Column_IDNum));
content.append("\n" + Books.Column_Name + ":"
+ record.get(Books.Column_Name));
}
writeServerDebug("The content is \n" + content.toString());
// Create the new Office Engine
OfficeEngine myOfficeEngine = new OfficeEngine();
boolean bIsConnected = myOfficeEngine._RepositoryBridge
.connectSourceDataBase(false);
if (bIsConnected) {
//Connected to the repository, so get the files
if (sReqData_sFormat.equalsIgnoreCase("pdf") || sReqData_sFormat.equalsIgnoreCase("pptx")) {
//The book end user format
String sReturnPptx = myOfficeEngine.performGeneratePptx(
req.getHttpServletRequest(), response,
sReqData_sBook_ID, sReqData_sPOV_IDs,
sReqData_sUser_ID, sReqData_sFormat);
writeServerDebug("customExport call performGeneratePptx, return is "
+ sReturnPptx);
}
else {
AppZip appZip = new AppZip();
appZip.ZipFile(" ", " ");
String r = "sReturn_OK";;
return r;
}
//Free the connection to repository
myOfficeEngine._RepositoryBridge.freeConnectionSource();
} else {
response.setContentType("text/plain");
response.addHeader("content-disposition",
"attachment; filename=book.txt");
ServletOutputStream os = response.getOutputStream();
os.print(content.toString());
os.flush();
}
} catch (Exception e) {
writeServerDebug("ERROR:" + e.getLocalizedMessage());
sReturn = Repository._Return_KO;
}
return sReturn;
}
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());
}
}