Pass data from Bean to javascript on jsf page. Google api directions - java

I need to pass waypoints to google maps javascript directions api from ManagedBean to jsf page.
I'm trying to make JSONArray and pass it to jsf:
private JSONArray routesJSON;
with getters and setters.
Than im creating JSON : in loop im adding Strings with LatLang of waypoints to List<String>
routes.add("new google.maps.LatLng(" + o.getLatitude() + "," + o.getLongitude()+")");
And im getting JSON :
[{"location":"new google.maps.LatLng(50.495121,22.1705)"},{"location":"new google.maps.LatLng(50.57082,22.06813)"},{"location":"new google.maps.LatLng(50.570549,22.047871)"},{"location":"new google.maps.LatLng(50.521389,21.912695)"},{"location":"new google.maps.LatLng(50.495121,22.1705)"}]
from:
for()
array.put(obj);
}
System.out.println(array);
in JSF function for displaying route : (it works with hardcoded data)
function calcRoute() {
var waypts = [];
var start = new google.maps.LatLng(#{someBean.startLatitude}, #{someBean.startLongitude});
var end = new google.maps.LatLng(49.712112, 21.50667);
var way = #{someBean.routesJSON};
var request = {
origin:start,
destination:end,
optimizeWaypoints: true,
waypoints:way;
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
But when im displaying that page map doesnt appear. I know it's probably because of " in JSON but i dont know how to remove it. Or may there are easiest ways to pass waypoint data from Bean to jsf page?

Instead of returning a JSON data packet that contains javascript statements like "new google.maps.LatLng(50.495121,22.1705)", it's more sensible to return just the coordinates.
So if you had a JSON packet that looks like this in your javascript (I don't know how to pass data between your Java and Javascript):
var routes = [
{"lat":"50.495121", "lng":"22.1705"},
{"lat":"50.57082", "lng":"22.06813"},
{"lat":"50.570549", "lng":"22.047871"},
{"lat":"50.521389", "lng":"21.912695"},
{"lat":"50.495121", "lng":"22.1705"}
]
You can turn this into an array like so:
var way = [];
for (var i = 0; i < routes.length; i++) {
way.push(new google.maps.LatLng(parseFloat(routes[i].lat), parseFloat(routes[i].lng)));
}
NB: the use of parseFloat to convert strings like "50.495121" into floating point numbers.

Related

RabbitMQ parsing "client_properties" header from c#

I'm listening for connection changes through events pluging ("amq.rabbitmq.event", "connection.#").
It works properly so I'm adding at java side two additional parameters as clientproperties, to get the identity of the user that connects or disconnect.
However at c# side I can only access these properties as a list of byte[], and not sure on how to convert it to a Dictionary or so..
If I print all entries
if (args.BasicProperties.Headers.TryGetValue("client_properties", out object value))
{
var items = value as List<object>;
foreach(var item in items)
{
Console.WriteLine($"{item.GetType().ToString()}");
var bytes = item as byte[];
result.Add(Encoding.UTF8.GetString(bytes));
}
}
I can see this:
{<<"platform">>,longstr,<<"Java">>}
{<<"capabilities">>,table,[{<<"connection.blocked">>,bool,true},{<<"basic.nack">>,bool,true},{<<"exchange_exchange_bindings">>,bool,true},{<<"authentication_failure_close">>,bool,true},{<<"publisher_confirms">>,bool,true},{<<"consumer_cancel_notify">>,bool,true}]}
{<<"groupId">>,longstr,<<"1e6e935f0d4d9ec446d67dadc85cbafd10d1a095">>}
{<<"information">>,longstr,<<"Licensed under the MPL. See http://www.rabbitmq.com/">>}
{<<"version">>,longstr,<<"4.8.1">>}
{<<"copyright">>,longstr,<<"Copyright (c) 2007-2018 Pivotal Software, Inc.">>}
{<<"product">>,longstr,<<"RabbitMQ">>}
What kind of object format is and how can I parse this?:
{<<id>>,type,<<value>>}
Apparently ( as for an answer I got on Rabbit client google group for this questions ), client_properties is something that's not created to being read by the receiving party..
However is a really good way to have something like LWT ( Last Will and Testament ), then I am using it at the minute doing the parse by myself.
if (args.BasicProperties.Headers.TryGetValue("client_properties", out object value))
{
var items = value as List<object>;
foreach (var item in items)
{
var bytes = item as byte[];
//{<<id>>, type, <<value>>}
String itemStr = Encoding.UTF8.GetString(bytes);
var parts = itemStr.Split(",");
var key = CleanErlangString(parts[0]);
var value = CleanErlangString(parts[2]);
// Do things with key/value
}
}
ClearErlangFunction
private static string CleanErlangString(string toClean)
{
return toClean
.Replace("{", "").Replace("}", "")
.Replace("\"", "")
.Replace("<<", "").Replace(">>", "");
}
What I am doing to use it as LWT, is setting a custom property on client side and then obtaining it while reading events at "amq.rabbitmq.event", "connection.#". With that I know who have disconnected and even process something as LWT with my core server.
I hope this helps someone :)

Create JSON Array from List<Object> in Java

This is a basic Java question I think that I can't work out how to get around.
I get data from Google Analytics API and store the rows in my database as a string as a JSONArray
[["New Zealand","Auckland","1640","8.795731707317072","516.4469512195122"],["New Zealand","Wellington","1314","8.428462709284627","580.3302891933029"]]
For Google Maps I need a JSON Array:
function drawMap() {
var data = google.visualization.arrayToDataTable([
['City', 'Popularity'],
['New York', 200],
['Boston', 300],
['Miami', 400],
['Chicago', 500],
['Los Angeles', 600],
['Houston', 700]
]);
From https://developers.google.com/chart/interactive/docs/gallery/geomap
I need to change my data, by parsing it and iterating through it to remove the first (i.e. "New Zealand") and last variable from each object - I also need to add the headers i.e. ['City', 'Popularity']
Using GSonBuilder I can create JSON
[{"city":"Wellington","sessions":"1314","viewsPerSessions":"8.428462709284627","avgDuration":"8.428462709284627"},{"city":"Christchurch","sessions":"432","viewsPerSessions":"10.127314814814815","avgDuration":"10.127314814814815"}]
How do I turn that into a JSON Array?
I use the JSON parse of Android. With this you can get what you want.
Try this:
JSONArray js_data = [["New Zealand","Auckland","1640","8.795731707317072","516.4469512195122"],["New Zealand","Wellington","1314","8.428462709284627","580.3302891933029"]];
int lenght = js_data.length();
JSONArray city;
for(int i=0;i<length;i++) {
//get each city
city = js_data.getJSONArray(i);
String nameCity = city.getString(0);
String pop = city.getString(4);
//Create a object JSON or whatever you want with this data
JSONArray js_array = new JSONArray();
js_array.put(city); js_array.put(pop);
//And put on a list
js_map.put(js_array);
}
This is a basic java coding.
Hope it's helps.

Ajax call to retrieve hashmap

I have a hashmap which I have converted into a JSONObject. This JSONObject I am retrieving via a REST api using an AJAX call. What I wish to know is that how will the ajax look like in order to get the JSONObject which I can use afterwards.
My ajax call looks like this :
Ext.Ajax.request({
url : '...',
method:'GET',
scope : this,
success : function(result, request) {
console.log("2");
var data = Ext.decode(result.responseText)[0];
for (var i = 0; i < data.size(); i++) {
console.log("4. ");
}
}
})
The error which appears is
Ext.Error: You're trying to decode an invalid JSON String:
result.responseText returns the Invalid JSON String.Use this code
var responseArray = Ext.decode(response.responseText);
var data = responseArray.data;
console.log(data);
data variable will contain the JSON Object.

Retrieve JSON object after jQuery get finish

I'm trying to retrieve JSON object using jQuery get, and the Object I retrieve I want to embed in innerHTML. The following code is how i construct my JSON
getListOfActivity.jsp
<%
String urusStr = request.getParameter("ukid");
int urusId = Integer.parseInt(urusStr);
lkpPdkCommon[] activity = getListOfActivity(urusId);
if(activity!=null){
out.println("{PartList:");
out.println("[");
for(int x=0;x<2;x++){// the lkpPdkCommon[] return from getListOfActivity(urusId) huge so I limit the array to 2
out.println("{");
out.println("ActivityID:\""+activity[x].getID()+"\",Description:\""+activity[x].getDescription()+"\"");
out.println("}");
if((x+1)!=2){
out.println(",");
}
}
out.println("]");
out.println("}");
response.setContentType("application/json");
%>
and below code is my jQuery/jscript
var ukid = document.getElementById("ukid").value
var aktivityId = row.insertCell(1);
var description = row.insertCell(2);
var JSONObject;
var $ac = jQuery.noConflict();
$ac.get("../../getListOfActivity.jsp",{ukid:ukid}, function(data){
JSONObject = data
//for testing purposes I do not iterate through the JSON Object
aktivityId.innerHTML = JSONObject.PartList[0].ActivityID
description.innerHTML = JSONObject.PartList[0].Description
});
The following code didn't return any error, but it seems doesn't work. This is the JSON Object I check using firebug
Have you tried Jquery getJSON.
I think this would help you.
http://api.jquery.com/jQuery.getJSON/
The problem solved after I modified the following line in jsp
out.println("{PartList:");
to
out.println("{\"PartList\":");
and
out.println("ActivityID:\""+activity[x].getID()+
"\",Description:\""+activity[x].getDescription()+"\"");
to
out.println("\"ActivityID\":\""+activity[x].getID()+
"\",\"Description\":\""+activity[x].getDescription()+"\"");
The original JSON object send by response header before I do the modification are like below:
{PartList:
[
{ActivityID:"8638",Description:"GERMS"},
{ActivityID:"8639",Description:"GOVERNMENT CERTIFY PROGRAMMES"}
]
}
and after the modification
{"PartList":
[
{"ActivityID":"8638","Description":"GERMS"},
{"ActivityID":"8639","Description":"GOVERNMENT CERTIFY PROGRAMMES"}
]
}

Strange parsing issue

I'm trying to send some data to a servlet and then to get back a .xls file from it. In order to do this, I'm using jquery, but I'm facing some strange issues. Let me explain.
Here is how I'm sending the data to the servlet and how I'm supposed to get the generated file back:
jQuery.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : jQuery.param(data);
//split params into form inputs
var inputs = '';
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
download = function () {
var a = this.mainData();
var b = JSON.stringify(a);
console.log(b);
what = "test",
obj = $.extend({WrJOB: "xlsExport", mainData: b}, tJS.getCommonPostData());
var data = $.param(obj); //.replace(/\+/g, '%20'); its just a test
$.download('/myapp/AppProxy', data);
},
A button in my html is calling the download function wich is sending some JSON data to the servlet. In my case it is var b.
I'm pretty sure that there is an encoding issue, but I have no idea how to fix it.
Please, help me with this strange problem, I'm already working many hours on it and I can not find a solution.
You should unescape your output at some point. I would advise to do it on servlet side.
It looks like the servlet is receiving it encoded for a URL. You might be able to decode it on the servlet side if you have control over the code on the servlet.
For instance, in PHP, using urldecode()
Hope this helps.
like this
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}});
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ jQuery.URLDecode(pair[1]) +'" />';
});
The problem is that you urlencode your data twice. First explicitly in your javascript, then implicitly when creating the form. The browser will be "nice" to you and urlencode the input parameters before doing the request.
Either decode the parameters before adding them as input values or change the way you build your data to avoid the explicit encoding.

Categories