What functionality of Chrome shows a parse error as a popup? - google-chrome

I have no clue where this is coming from: here is it, in Java I created a servlet that runs Javascript files in Nashorn and then writes the result in a response. My Javascript code returns an object like:
function root(){
return {
"hello": 1
};
}
while my servlet returns the object (it was just a test):
Object result = invocable.invokeFunction("root", req);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream());
outputStreamWriter.write(result.toString());
outputStreamWriter.close();
the response raw body is:
[object Object]
and chrome will do the following:
That red popup cross even closes it on click.
Is this done by an extension that I forgot about? Or is it some kind of integration with that syntax? I've really no idea.

#gotch4
Result you're observing is expected. You're retuning string representation of JavaScript object (technically you're calling Object.protorype.toString which returns [object Object]).
I think what you really want is to invoke JSON.stringify before returning response to the browser.
Object JSON = e.eval("JSON");
Object result = invocable.invokeMethod(JSON, "stringify", invocable.invokeFunction("root", req));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream());
outputStreamWriter.write(result.toString());
outputStreamWriter.close();
p.s. Code should work, but I didn't test it - writing from phone.

Related

API Response returns Mappable Object in iOS but Json on Android

I'm a newbie on mobile development and React-Native, this might come across as a very mundane thing to some of you, but I'm making an Api call and then mapping the results to create the same component but with different data.
This works fine on Iphone but on Android it does not.
The response from the req is an Object for both devices but on Android, it seems to be a json object that I simply cannot map with or use on a Flatlist.
I've tried JSON.parse to get the json object to a js object but it simply doesn't, like it. It throws out an unexpected token error.
I've attached a log for the Android object first and the same object for iPhone (Already mappable and a JS object).
Can someone tell me why this happens? I'd very much appreciate it!
enter image description here
____________________ After Changing to Fetch _______________________
Hey, I changed from Axios to fetch and now I get an unhandled promise warning saying 'Unhandled promise rejection: SyntaxError: JSON Parse error: Unrecognized token '' '.
Don't think I'm doing anything wrong here...
Well ... your response-object gets truncated due to memory issues on your real-device ... most likely your response object is kinda large ...
And that's just the way axios fetch response-data ... through chunks, you just get a slice of the response...
I came across this issue before ... and the solution was to switch to fetch
Edit
try {
const rawResponse = await fetch(...);
const text = await rawResponse.text();
console.log(text);
const parsedRes = JSON.parse(text);
console.log('parsedRes', parsedRes);
} catch(error) {
console.log('fetch error', error);
}

Angular2 HTTP Providers, get a string from JSON for Amcharts

This is a slightly messy questions. Although it appears I'm asking question about amCharts, I really just trying to figure how to extract an array from HTTP request and then turn it into a variable and place it in to 3-party javacript.
It all starts here, with this question, which was kindly answered by AmCharts support.
As one can see from the plnker. The chart is working. Data for the chart is hard coded:
`var chartData = [{date: new Date(2015,2,31,0,0,0, 0),value:372.10,volume:2506100},{date: new Date(2015,3,1,0, 0, 0, 0),value:370.26,volume:2458100},{date: new Date(2015,3,2,0, 0, 0, 0),value:372.25,volume:1875300},{date: new Date(2015,3,6,0, 0, 0, 0),value:377.04,volume:3050700}];`
So we know the amCharts part works. Know where the problem is changing hard coded data to a json request so it can be dynamic. I don't think this should be tremendously difficult, but for the life of me I can't seem figure it out.
The first issue is I can't find any documentation on .map, .subscribe, or .observable.
So here is a plunker that looks very similar to the first one, however it has an http providers and injectable. It's broken, because I can't figure out how to pull the data from the service an place it into the AmCharts function. I know how pull data from a http provider and display it in template using NgFor, but I don't need it in the template (view). As you can see, I'm successful in transferring the data from the service, with the getTitle() function.
this.chart_data =_dataService.getEntries();
console.log('Does this work? '+this.chart_data);
this.title = _dataService.getTitle();
console.log('This works '+this.title);
// Transfer the http request to chartData to it can go into Amcharts
// I think this should be string?
var chartData = this.chart_data;
So the ultimate question is why can't I use a service to get data, turn that data into a variable and place it into a chart. I suspect a few clues might be in options.json as the json might not be formatted correctly? Am I declaring the correct variables? Finally, it might have something to do with observable / map?
You have a few things here. First this is a class, keep it that way. By that I mean to move the functions you have inside your constructor out of it and make them methods of your class.
Second, you have this piece of code
this.chart_data =_dataService.getEntries().subscribe((data) => {
this.chart_data = data;
});
What happens inside subscribe runs asynchronously therefore this.chart_data won't exist out of it. What you're doing here is assigning the object itself, in this case what subscribe returns, not the http response. So you can simply put your library initialization inside of the subscribe and that'll work.
_dataService.getEntries().subscribe((data) => {
if (AmCharts.isReady) {
this.createStockChart(data);
} else {
AmCharts.ready(() => this.createStockChart(data));
}
});
Now, finally you have an interesting thing. In your JSON you have your date properties contain a string with new Date inside, that's nothing but a string and your library requires (for what I tested) a Date object, so you need to parse it. The problem here is that you can't parse nor stringify by default a Date object. We need to convert that string to a Date object.
Look at this snippet code, I used eval (PLEASE DON'T DO IT YOURSELF, IS JUST FOR SHOWING PURPOSES!)
let chartData = [];
for(let i = 0; i < data[0].chart_data.length; i++) {
chartData.push({
// FOR SHOWING PURPOSES ONLY, DON'T TRY IT AT HOME
// This will parse the string to an actual Date object
date : eval(data[0].chart_data[i].date);
value : data[0].chart_data[i].value;
volume : data[0].chart_data[i].volume;
});
}
Here what I'm doing is reconstructing the array so the values are as required.
For the latter case you'll have to construct your json using (new Date('YOUR DATE')).toJSON() and you can parse it to a Date object using new Date(yourJSON) (referece Date.prototype.toJSON() - MDN). This is something you should resolve in your server side. Assuming you already solved that, your code should look as follows
// The date property in your json file should be stringified using new Date(...).toJSON()
date : new Date(data[0].chart_data[i].date);
Here's a plnkr with the evil eval. Remember, you have to send the date as a JSON from the server to your client and in your client you have to parse it to a Date.
I hope this helps you a little bit.
If the getEntries method of DataService returns an observable, you need to subscribe on it to get data:
_dataService.getEntries().subscribe(
(data) => {
this.chart_data = data;
});
Don't forget that data are received asynchronously from an HTTP call. The http.get method returns an observable (something "similar" to promise) will receive the data in the future. But when the getEntries method returns the data aren't there yet...
The getTitle is a synchronous method so you can call it the way you did.

Am I using the wrong standard for JSON response?

I am new to Angular and I am trying to build a simple todo application using it. I have designed a module called TodoServices in which I am creating a User service using the factory method. The code looks something like:
angular.module('TodoServices', ["ngResource"])
.factory('User', function($resource){
return $resource('http://todoapi.rohanchhabra.in/users/:id');
});
The code in my app.js looks like:
var angularApp = angular.module('angularApp', ['TodoServices']);
angularApp.controller('UsersController', function(User){
this.users = {};
this.users = User.query();
});
When I run my application, I get this error: Error link
I think this is because my web service is returning an object which not only has the data but also has a few other things such as a status and messages. Now Is it a wrong way of doing it? Should I just return the array from the back end? What is the actual problem here and how to solve this?
As your error link says:
By default, all resource actions expect objects, except query which expects arrays.
You should use an other function like User.Get() when you're not expecting an array but just a single object.

WCF JSON returned as null

Following this tutorial: I have created a WP8 Mobile Application and trying to call my WCF web service. When calling the WCF service in the browser, I can see the JSON returned with no problems at all. However, when I call the WCF service in my mobile application, I don't get anything back. I have no clue where I am going wrong.
This is the code that call the WCF:
string ServiceUri = "urlgoeshere";
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(ServiceUri));
And the event handler:
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<SightingType>));
var result = obj.ReadObject(stream) as List<SightingType>;
What am I doing wrong? I've obviously changed the ServiceUri to "urlgoeshere" but rest assured, the actual URL works perfectly, 100% A-OK when I run it in my browser. When running it in this mobile app however, it doesn't work. Can anyone see the obvious problem?
Update
If I do:
var result = obj.ReadObject(stream);, and if I step into stream, I can see a:
ReadTimeout = 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

Primefaces callback with JSON as callback parameter

I am trying to pass Json as callback parameter. Can anyone correct the javascript to get the values from the json object?
javascript
function renderTopic(xhr,status,args){
alert("iam In renderTopic");
var topicObject = $.parseJSON(args.topicJSON);
for(var x in topicObject){
alert(x.topicBody);
};
}
Server side
jGenerator.writeFieldName("topicBody");
jGenerator.writeStartArray();
...............
jGenerator.close();
context = RequestContext.getCurrentInstance();
System.out.println("JSON output in string "+out.toString())
xhtml
<p:commandLink action="#{topicController.listAllTopics}"
id="topicListAllCmdLink" value="" oncomplete="javascript:renderTopic(xhr, status,args)"/>
http response
<partial-response><changes><update id="javax.faces.ViewState"><![CDATA[4091946826703479326:-2361306414195161728]]></update><extension ln="primefaces" type="args">{"topicJSON":"{\"topicBody\":[\"Test10\",\"Test22\",\"Test4\",\"Test11\"]}"}</extension></changes></partial-response>
Every thing seems to be ok. Do you see any error? or any output that you can tell us about.
See this link to get a better description:
Best method for passing Data from Java/JSF2 bean to Javascript/jQuery Components as return values