RallyApi in Java - Trying to return project hierarchy for a feature - rally

Given a Feature result set passed into this function, I am trying to traverse up the project hierarchy up to the subscription. I can't I get a null pointer on the projResponse =... No even sure of the approach for this.
private static void getProjHierarchyForFeature(RallyRestApi restApi, QueryResponse featureSet,
Time2Market time2market, Integer featureInSet) {
String tempHierarchy = "";
JsonArray tempFeatures = featureSet.getResults();
//time2market.setProjectName(projectName);
try {
JsonObject obj1 = tempFeatures.get(featureInSet).getAsJsonObject();
JsonObject proj = obj1.get("Project").getAsJsonObject();
String url = proj.get("_ref").getAsString();
QueryRequest projQuery = new QueryRequest(url);
projQuery.setFetch(new Fetch("_ref", "_refObjectUUID", "_refObjectName"));
QueryResponse projResponse = restApi.query(projQuery);
if (projResponse.wasSuccessful()) {
JsonArray tempProj = projResponse.getResults();
// Here we have the project object, now process Parents...
Boolean moreParents = true;
while (moreParents) {
QueryRequest parentQuery = new QueryRequest(url);
//projQuery.setFetch(new Fetch("_ref", "_refObjectUUID", "_refObjectName"));
QueryResponse parentResponse = restApi.query(parentQuery);
if (parentResponse.wasSuccessful()) {
System.out.println ("proj Response... " + parentResponse.toString());
JsonArray projParent = parentResponse.getResults();
tempHierarchy.concat(projParent.get(0).getAsString());
JsonArray tempParent = parentResponse.getResults();
proj = tempParent.getAsJsonObject();
} else {
moreParents = false;
}
}
} else {
System.err.println("The following errors occurred: ");
for (String err : projResponse.getErrors()) {
System.err.println("\t" + err);
}
throw new java.lang.Error("Rally API Call Error Occurred");
}
} catch (Exception e) {
e.printStackTrace();
}
}

You probably want to use a GetRequest instead of a QueryRequest since you're just reading a single object. Also, include Parent in your fetch. Then you should have the data to be able to determine whether there is a parent and to continue looping or not.

Related

Object reference not set to an instance of an object while connecting Microsoft Dynamics GP 2018 with eConnect 18 using .net Framework 4.6.1

I have tried many solutions for this simple error but I couldn't find bug what actually cause it.
Here is some code for reference.
GPController
[HttpPost("testConnection")]
public bool TestConnection()
{
try
{
var data = eConn.GetEntity();
if (data)
{
return true;
}
return false;
}
catch(Exception ex)
{
throw ex;
}
}
eConn.cs
public static bool GetEntity()
{
try
{
string connString = DataAccess.ConnectionString;
eConnectOut myRequest = new eConnectOut();
myRequest.DOCTYPE = "Customer";
myRequest.OUTPUTTYPE = 1;
myRequest.INDEX1FROM = "Customer001";
myRequest.INDEX1TO = "Customer001";
myRequest.FORLIST = 1;
// Create the eConnect requester XML document object
RQeConnectOutType[] eConnectOutType =
new RQeConnectOutType[1] { new RQeConnectOutType()};
eConnectOutType[0].eConnectOut = myRequest;
eConnectType eConnectDoc = new eConnectType();
eConnectDoc.RQeConnectOutType = eConnectOutType;
// Serialize the object to produce an XML document
MemoryStream memStream = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
serializer.Serialize(memStream, eConnectDoc);
memStream.Position = 0;
XmlDocument myDoc = new XmlDocument();
myDoc.Load(memStream);
eConnectMethods eConnCall = new eConnectMethods();
eConnCall.RequireProxyService = false;
// Retrieve the specified customer document
string myCustomer = eConnCall.GetEntity(connString, myDoc.OuterXml);
return true;
}
catch(Exception ex)
{
throw ex;
}
}
In eConn.cs calling GetEntity method I am getting this error.
{System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Dynamics.GP.eConnect.EventLogHelper.AddExceptionHeader(String action, Object[] inputParameters, StringBuilder errorString)
at Microsoft.Dynamics.GP.eConnect.EventLogHelper.CreateEventLogEntry(Exception exception, String action, Object[] inputParameters)
at Microsoft.Dynamics.GP.eConnect.eConnectMethods.GetEntity(String connectionString, String sXML)
at AP.GPServices.Helper.eConn.GetEntity() in D:\projects\APSystem SM\Source Code\AP.GPServices\Helper\eConn.cs:line 46}
I am referring this Programmer guide.
http://www.mypurelogic.com/files/purelogic/files/manuals/econnectprogrammersguide.pdf

org.apache.fop.fo.flow.ExternalGraphic catches and logs ImageException I want to handle myself

I am transforming an Image into pdf for test purposes.
To ensure that the Image is compatible with the printing process later on, I'm running a quick test print during the upload.
I'm creating a simple Test-PDF with a transformer. When I try to print an image with an incompatible format, the ImageManager of the transformer throws an ImageException, starting in the preloadImage() function:
public ImageInfo preloadImage(String uri, Source src)
throws ImageException, IOException {
Iterator iter = registry.getPreloaderIterator();
while (iter.hasNext()) {
ImagePreloader preloader = (ImagePreloader)iter.next();
ImageInfo info = preloader.preloadImage(uri, src, imageContext);
if (info != null) {
return info;
}
}
throw new ImageException("The file format is not supported. No ImagePreloader found for "
+ uri);
}
throwing it to:
public ImageInfo needImageInfo(String uri, ImageSessionContext session, ImageManager manager)
throws ImageException, IOException {
//Fetch unique version of the URI and use it for synchronization so we have some sort of
//"row-level" locking instead of "table-level" locking (to use a database analogy).
//The fine locking strategy is necessary since preloading an image is a potentially long
//operation.
if (isInvalidURI(uri)) {
throw new FileNotFoundException("Image not found: " + uri);
}
String lockURI = uri.intern();
synchronized (lockURI) {
ImageInfo info = getImageInfo(uri);
if (info == null) {
try {
Source src = session.needSource(uri);
if (src == null) {
registerInvalidURI(uri);
throw new FileNotFoundException("Image not found: " + uri);
}
info = manager.preloadImage(uri, src);
session.returnSource(uri, src);
} catch (IOException ioe) {
registerInvalidURI(uri);
throw ioe;
} catch (ImageException e) {
registerInvalidURI(uri);
throw e;
}
putImageInfo(info);
}
return info;
}
}
throwing it to :
public ImageInfo getImageInfo(String uri, ImageSessionContext session)
throws ImageException, IOException {
if (getCache() != null) {
return getCache().needImageInfo(uri, session, this);
} else {
return preloadImage(uri, session);
}
}
Finally it gets caught and logged in the ExternalGraphic.class:
/** {#inheritDoc} */
public void bind(PropertyList pList) throws FOPException {
super.bind(pList);
src = pList.get(PR_SRC).getString();
//Additional processing: obtain the image's intrinsic size and baseline information
url = URISpecification.getURL(src);
FOUserAgent userAgent = getUserAgent();
ImageManager manager = userAgent.getFactory().getImageManager();
ImageInfo info = null;
try {
info = manager.getImageInfo(url, userAgent.getImageSessionContext());
} catch (ImageException e) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageError(this, url, e, getLocator());
} catch (FileNotFoundException fnfe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageNotFound(this, url, fnfe, getLocator());
} catch (IOException ioe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageIOError(this, url, ioe, getLocator());
}
if (info != null) {
this.intrinsicWidth = info.getSize().getWidthMpt();
this.intrinsicHeight = info.getSize().getHeightMpt();
int baseline = info.getSize().getBaselinePositionFromBottom();
if (baseline != 0) {
this.intrinsicAlignmentAdjust
= FixedLength.getInstance(-baseline);
}
}
}
That way it isn't accessible for me in my code that uses the transformer.
I tried to use a custom ErrorListener, but the transformer only registers fatalErrors to the ErrorListener.
Is there any way to access the Exception and handle it myself without changing the code of the library?
It was easier than I thought. Before I call the transformation I register a costum EventListener to the User Agent of the Fop I'm using. This Listener just stores the Information what kind of Event was triggered, so I can throw an Exception if it's an ImageError.
My Listener:
import org.apache.fop.events.Event;
import org.apache.fop.events.EventListener;
public class ImageErrorListener implements EventListener
{
private String eventKey = "";
private boolean imageError = false;
#Override
public void processEvent(Event event)
{
eventKey = event.getEventKey();
if(eventKey.equals("imageError")) {
imageError = true;
}
}
public String getEventKey()
{
return eventKey;
}
public void setEventKey(String eventKey)
{
this.eventKey = eventKey;
}
public boolean isImageError()
{
return imageError;
}
public void setImageError(boolean imageError)
{
this.imageError = imageError;
}
}
Use of the Listener:
// Start XSLT transformation and FOP processing
ImageErrorListener imageListener = new ImageErrorListener();
fop.getUserAgent().getEventBroadcaster().addEventListener(imageListener);
if (res != null)
{
transformer.transform(xmlDomStreamSource, res);
}
if(imageListener.isImageError()) {
throw new ImageException("");
}
fop is of the type Fop ,xmlDomStreamSource ist the xml-Source I want to transform and res is my SAXResult.

AsyncTask doInBackground() does not execute correctly on run, but works on debugger

#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
ArrayList<HashMap<String, String>> PLIST = new ArrayList<>();
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(jsonUrl);
ArrayList<String> URLList = new ArrayList<>();
if (jsonStr != null) {
placesList.clear();
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray placesJsonArray = jsonObj.getJSONArray("results");
String pToken = "";
// looping through All Places
for (int i = 0; i < placesJsonArray.length(); i++) {
JSONObject placesJSONObject = placesJsonArray.getJSONObject(i);
String id = placesJSONObject.getString("id");
String name = placesJSONObject.getString("name");
HashMap<String, String> places = new HashMap<>();
// adding each child node to HashMap key => value
places.put("id", id);
places.put("name", name);
PLIST.add(places);
}
//TODO: fix this...
if (SEARCH_RADIUS == 1500) {
Log.e(TAG, "did it get to 1500?");
try {
for (int k = 0; k < 2; k++) {
//error is no value for next_page_token... this
ERROR HERE
pToken = jsonObj.getString("next_page_token"); //if I place breakpoint here, debugger runs correctly, and returns more than 20 results if there is a next_page_token.
String newjsonUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
+ midpointLocation.getLatitude() + "," + midpointLocation.getLongitude()
+ "&radius=" + SEARCH_RADIUS + "&key=AIzaSyCiK0Gnape_SW-53Fnva09IjEGvn55pQ8I&pagetoken=" + pToken;
URLList.add(newjsonUrl);
jsonObj = new JSONObject(new HttpHandler().makeServiceCall(newjsonUrl)); //moved
Log.e(TAG, "page does this try catch");
}
}
catch (Exception e ) {
Log.e(TAG, "page token not found: " + e.toString());
}
for (String url : URLList){
Log.e(TAG, "url is : " + url);
}
I made an ArrayList of URLS after many attempts to debug this code, I planned on unpacking the ArrayList after all the urls with next_page_tokens were added, and then parsing through each of them later. When running the debugger with the breakpoint on pToken = getString("next_page_token") i get the first url from the Logger, and then the second url correctly. When I run as is, I get the first url, and then the following error: JSONException: No value for next_page_token
Things I've tried
Invalidating Caches and restarting
Clean Build
Run on different SDK versions
Made sure that the if statement is hitting (SEARCH_RADIUS == 1500)
Any help would be much appreciated, thanks!
Function is called in a listener function like this.
new GetPlaces(new AsyncResponse() {
#Override
public void processFinish(ArrayList<HashMap<String, String>> output) {
Log.e(TAG, "outputasync:" );
placesList = output;
}
}).execute();
My onPostExecute method.
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
delegate.processFinish(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
It turns out that the google places api takes a few milliseconds to validate the next_page_token after it is generated. As such, I have used the wait() function to pause before creating the newly generated url based on the next_page_token. This fixed my problem. Thanks for the help.

Converting a JSON object to an equivalent in JAVA

I am massively stuck with converting a PHP server request into an equivalent Java Request. This is the code that contains the JSON object that I need to replicate in JAVA and send from an Android device:
$(".unableprocess").click(function() {
if (!confirm("Confirm not able to process...!")) {
return false;
} else {
var item_id = $(this).attr('data-id');
var table_id = $(this).attr('table-id');
var data = {
BookOrders: {
item_id: item_id,
table_id: table_id
}
};
$.ajax({
url: //MY URL HERE ,
type: "POST",
data: data,
success: function(evt, responseText) {
location.reload();
}
});
}
});
And here is my Java class that attempts to perform the same functionality. The class extends AsyncTask and all network interactions occur in the doInBackground() method. Here is my code:
#Override
protected Boolean doInBackground(String... arg0) {
try{
HashMap<String, String> hashMap = new HashMap<String,String>();
JSONObject jsonObject = new JSONObject();
int statusCode;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(tableMateCannotProcessURL);
// JSON object creation begins here:
jsonObject.accumulate("item_id",this.itemId);
jsonObject.accumulate("table_id",this.tableId);
JSONObject jObject = new JSONObject();
jObject.accumulate("BookOrders", jsonObject);
// JSON object ends here
Log.v("ATOMIC BLAST",jObject.toString());
String json = jObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
Integer statusCodeInt = new Integer(statusCode);
Log.v("HTTPResponse",statusCodeInt.toString());
String result= "";
StringBuilder builder = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}
else {
Log.e("==>", "Failed to download file");
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
The JSON object that I created looks like this after printing it out to the console:
{"BookOrders":{"table_id":"1","item_id":"2"}}
After POSTing this object to the server I do not get the expected response. What is the proper method for converting the JSON object into an equivalent JSON object in JAVA? Any guidance, direction or a solution would be most appreciated.
Update php to version 5.4 helped me.
In this version json_encode($x, JSON_PRETTY_PRINT) works just as needed.
Your JSON seems to be correct but it's an Object in an Object.
JSONObject json = new JSONObject(yourdata);
JSONObject jsonTable = new JSONObject(json.getString("BookOrders"));
Log.d("JsonDebug", "json:" + jsonTable.toString());
If you are not sure if you have a JSONObject or an Array you can validate it by using
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array

Having Trouble with ObjectInputStream/OutputStream

I am having trouble with my programs ability to save my Maps to a file. Here are my two methods for writing and reading my maps and arraylist.
Here is my read method:
private void getData() throws IOException, ClassNotFoundException {
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
if (f_Instructors.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Instructors)))) {
//Add theList back in
if (in.readObject() != null) {
TreeMap<Instructor, Set<Student>> read = null;
while(in.available() > 0) {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
}
if (read != null) {
for (Instructor key : read.keySet()) {
System.out.println(key);
Set<Student> values = read.get(key);
PSLTrackerInfo.addInstructor(key, values);
}
System.out.println("Instructors Found! Reading...");
} else {
System.out.println("No instructor data saved.1");
}
} else {
System.out.println("No instructor data saved.2");
}
in.close();
}
}
//Add times back in
if (f_Times.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Times)))) {
if (in.readObject() != null) {
TreeMap<Student, ArrayList<Date>> readTimes = null;
while(in.available() > 0) {
readTimes = (TreeMap<Student, ArrayList<Date>>) in.readObject();
}
if (readTimes != null) {
for (Student key : readTimes.keySet()) {
System.out.println(key);
ArrayList<Date> values = readTimes.get(key);
PSLTrackerInfo.addTimes(key, values);
}
System.out.println("Dates Found! Reading...");
} else {
System.out.println("No dates saved.");
}
} else {
System.out.println("No dates saved.");
}
in.close();
}
}
//Add newStudents back in
if (f_Students.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Students)))) {
if (in.readObject() != null) {
ArrayList<Student> readStudents = null;
while (in.available() > 0) {
readStudents = (ArrayList<Student>) in.readObject();
}
if (readStudents != null) {
PSLTrackerInfo.setTheList(readStudents);
}
System.out.println("New students found! Reading...");
} else {
System.out.println("No new students data saved.");
}
in.close();
}
}
}
And Here is my Writing method:
private void saveData() {
System.out.println("Saving Data...");
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
ObjectOutputStream out_Instructors = null;
ObjectOutputStream out_Students = null;
ObjectOutputStream out_Times = null;
try {
out_Instructors = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Instructors)));
out_Students = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Students)));
out_Times = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Times)));
out_Instructors.writeObject(PSLTrackerInfo.getMap());
out_Times.writeObject(PSLTrackerInfo.getTimes());
out_Students.writeObject(PSLTrackerInfo.getList());
out_Instructors.flush();
out_Students.flush();
out_Times.flush();
out_Instructors.close();
out_Students.close();
out_Times.close();
} catch (IOException ex) {
Logger.getLogger(PrivateLessonsTrackerGUI.class.getName())
.log(Level.SEVERE, null, ex);
}
System.exit(0);
}
Sorry if it is a little confusing I have 3 files to save 3 different objects, if there is a way to save it into one file let me know but I just was getting a lot of errors that I couldn't figure out how to solve so this is what I ended up doing. Thanks for any help given.
To EJP: I tried this
TreeMap<Instructor, Set<Student>> read = null;
try {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
} catch (EOFException e) {
System.out.println("Caught EOFException!");
}
And even when there was data in it when it was written to the file, I got an EOFException everytime.
readObject() doesn't return null unless you wrote a null. If you're using that as a test for end of stream, it is invalid. The correct technique is to catch EOFException.
You are calling it and throwing away the result if it isn't null, and then calling it again. The second call will throw EOFException if there isn't another object in the file. It won't give you the same result as the first call. It's a stream.
available() is also not a valid test for end of stream. That's not what it's for. See the Javadoc. Again, the correct technique with readObject() is to catch EOFException.