How to send a POJO as a callback param using PrimeFaces' RequestContext? - callback

I can send callback param(s) and it works perfectly as long as I am only sending some primitive types like String. But the same thing does not work for even the simplest POJO. PrimeFaces guide says that the RequestContext.addCallbackParam() method can handle POJOs and it coverts them into JSON. I don't know why it's not working in my case.
Has anybody done that?

Solution found! ---------------------------------------------------------------------
I did some research and found the answer to this question.
And the solution was to use some JSON library (right now I am using GSON) to convert Java objects to JSON objects.
new Gson().toJson(someJavaObj)
returns string. Just send the string as the param and on the client side using js' eval or some js library's function to turn that into JSON again.
Actually, it was pretty clean and simple.
Sorry I actually did not post the solution. Below is the my solution -
Action method in the backing bean -
public void retrievePieData() {
List<String> categories = new ArrayList<String>();
categories.add("Electronic");
categories.add("Food");
categories.add("Liguor");
categories.add("Stationary");
categories.add("Mechanical");
List<Integer> itemCounts = new ArrayList<Integer>();
itemCounts.add(5);
itemCounts.add(20);
itemCounts.add(1);
itemCounts.add(50);
itemCounts.add(10);
RequestContext reqCtx = RequestContext.getCurrentInstance();
reqCtx.addCallbackParam("categories", new Gson().toJson(categories));
reqCtx.addCallbackParam("itemCounts", new Gson().toJson(itemCounts));
}
PrimeFaces p:commandButton in the view -
<p:commandLink action="#{pieDataProvider.retrievePieData}" oncomplete="feedPieData(xhr, status, args);" value="Pie chart demo" update="pieData" />
Javascript function -
function feedPieData(xhr, status, args) {
var categories = eval('(' + args.categories + ')');
var itemCounts = eval('(' + args.itemCounts + ')');
options.xAxis.categories = categories;
var series = {
data: []
};
series.name = new Date().toString();
series.data = itemCounts;
options.series = [series];
chart = new Highcharts.Chart(options);
}
I would really appreciate and welcome any suggestion or opinion.
Thank you!

Related

Angular 2 creating models vs working with json objects on the fly?

when interacting with a rest api using Angular 2. Is it worth creating typescript classes for each object (eg. employee, company, project, user ...). the other option is getting json object and working with it on the fly ?
i suggest using models because :
your code will be more readable for yourself after a while coming back to change it, every one else also can easily understand what you've done
making changes in project will be more easily for example obj[0] does not have any special meaning but obj['username'] is more obvious
you will get intellinsense in you IDE
you can put logic in model for example so your controller will be more thin
name: string
age: number
sayInfo(): string {
return `name is ${this.name} and age is ${this.age}`
}
generally managing you app will be without headache (or at least less headache) :D
just remember that fat models thin controllers
don't forget that passing more than five arguments to a function is not a good practice use an object instead for example :
constructor(file) {
this.id = file['id']
this.fileName = file['fileName']
this.extention = file['extention']
this.fileSize = file['fileSize']
this.permission = file['permission']
this.description = file['description']
this.password = file['password']
this.isFolder = file['isFolder']
this.parent = file['parent']
this.banStat = file['banStat']
this.tinyLink = file['tinyLink']
}
getName(): string {
return `${this.fileName}${(this.isFolder) ? '' : '.'}${this.extention}`
}
getIcon(): string {
return this.isFolder ? 'fa-folder' : 'fa-music'
}

How to get the underlying object from a SpyMessage in JBossMQ

I am trying to write a simple Java program that reads from JBossMQ's jms_messages table using JDBC. I am using JBoss 4.0.4.GA.
I can get the as far as getting a SpyMessage, but how can I get the actual message content (which is an Object in the particular case I'm looking at).
I have a result set "rs" from this statement:
SELECT messageid, messageblob FROM jms_messages WHERE DESTINATION LIKE 'TOPIC.MyTopic%' limit 3"
and then I do this (based on JBoss code):
long messageid = rs.getLong(1);
SpyMessage message = null;
byte[] st = rs.getBytes(2);
ByteArrayInputStream baip = new ByteArrayInputStream(st);
ObjectInputStream ois = new ObjectInputStream(baip);
message = SpyMessage.readMessage(ois);
message.header.messageId = messageid;
String jmstype = message.getJMSType();
String jms_message_id = message.getJMSMessageID();
System.out.println("jmstype=" +jmstype);
System.out.println("jms_message_id=" +jms_message_id);
String propertyName;
Enumeration e = message.getPropertyNames();
while (e.hasMoreElements())
{
propertyName = (String)e.nextElement();
System.out.println("property name = " +propertyName);
}
but I get no properties printed and I don't know how to get my actual object from the SpyMessage (actually a SpyObjectMessage). I'd be grateful for any pointers.
I've tried asking this question on the JBoss forum without reply, so I'm hoping for better luck here.
Thanks.
Sorry - the answer was so obvious I'm not really sure what I was thinking when I posted the question - simply:
Object objMessage = ((SpyObjectMessage)message).getObject();

Why is GWT ArrayList of String objects truncating text with an ampersand?

I'm using GWT on the client side. I store String objects in an ArrayList instance, and when I add the value "AT&T", it only seems to be storing "AT". I suspect this is the result of the ArrayList truncating the text due to the ampersand, but I have yet to write a smaller proof-of-concept to be sure. Has anyone else encountered this problem?
GWT 2.1.1
Tomcat 7.0.5
Firefox 5.0.1
So this test succeeds:
ArrayList<String> test = new ArrayList<String>();
test.add( "testing&123");
Window.alert( test.get(0) + " - " + test.get(0).contains("&") );
My code effectively does this:
String test = "AT&T";
MyApp.getInstance().getDataStore().add( test );
Window.alert( test + " - " + MyApp.getInstance().getDataStore().getItems().get(0) );
public void DataStore.add( String item ) {
itemsList.add( item );
}
public ArrayList<String> getItems() {
return itemList;
}
The output is "AT&T - AT". So if the ArrayList is not the problem, is it the method calls?
Well, it turns out it was an interaction between my History Manager and the DataStore class. A very strange situation that no one could have helped me with given the limited amount of information I had provided.

Inserting JSON in DataTable in Google Visualisation

I read that JSON can be inserted into a datatable. However, its done
in JS on the HTML page (if memory serves right). I am using the GWT-
visualisation driver as given here, and the only methods to add a row are not
designed with JSON in mind. Is there any work-able solution? I am
trying to make a Stacked Column Chart.
Thanks.
I also struggled with this using geomap and data table combined. In my workaround I used the evalJSON() in prototype javascript framework to make the json string an object.
var country_obj = country_data.evalJSON(true);
Then I loop over the object's length :
var data = new google.visualization.DataTable();
data.addRows(country_obj.country.length);
data.addColumn('string', 'Country');
data.addColumn('number', map_context);
var j = country_obj.country.length;
for ( i = 0; i < j; i++ )
{
var num = new Number(country_obj.country[i].geo_mstat_reads);
data.setValue(i, 0, country_obj.country[i].country_name);
data.setValue(i, 1, num.valueOf());
}
// and then the table.draw() with the data
This worked very well for me because it scales to the exact size of the dataset you are trying to show.
Also you can do a whole whack of operations on an object which makes your life and coding easier to read and write.
I hope this helps you with your problem.
same pb, and don't know if it's feasible :
public native DataTable createDataTable(String obj) /*-{
console.log("create Datatable :" + obj);
var dt = new $wnd.google.visualization.DataTable(obj);
console.log("Datatable created");
return dt;
}-*/;
This create an empty dataTable whereas the JSON input is well formatted...

What is the better way to do the below program(c#3.0)

Consider the below program
private static bool CheckFactorPresent(List<FactorReturn> factorReturnCol)
{
bool IsPresent = true;
StringBuilder sb = new StringBuilder();
//Get the exposure names from Exposure list.
//Since this will remain same , so it has been done outside the loop
List<string> lstExposureName = (from item in Exposures
select item.ExposureName).ToList<string>();
foreach (FactorReturn fr in factorReturnCol)
{
//Build the factor names from the ReturnCollection dictionary
List<string> lstFactorNames = fr.ReturnCollection.Keys.ToList<string>();
//Check if all the Factor Names are present in ExposureName list
List<string> result = lstFactorNames.Except(lstExposureName).ToList();
if (result.Count() > 0)
{
result.ForEach(i =>
{
IsPresent = false;
sb.AppendLine("Factor" + i + "is not present for week no: " + fr.WeekNo.ToString());
});
}
}
return IsPresent;
}
Basically I am checking if all the FactorNames[lstFactorNames] are present in
ExposureNames[lstExposureName] list by using lstFactorNames.Except(lstExposureName).
And then by using the Count() function(if count() > 0), I am writing the error
messages to the String Builder(sb)
I am sure that someone can definitely write a better implementation than the one presented.
And I am looking forward for the same to learn something new from that program.
I am using c#3.0 and dotnet framework 3.5
Thanks
Save for some naming convention issues, I'd say that looks fine (for what I can figure out without seeing the rest of the code, or the purpose in the effort. The naming conventions though, need some work. A sporadic mix of ntnHungarian, PascalCase, camelCase, and abbrv is a little disorienting. Try just naming your local variables camelCase exclusively and things will look a lot better. Best of luck to you - things are looking good so far!
- EDIT -
Also, you can clean up the iteration at the end by just running a simple foreach:
...
foreach (var except in result)
{
isPresent = false;
builder.AppendFormat("Factor{0} is not present for week no: {1}\r\n", except, fr.WeekNo);
}
...