• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Passing a JSF dataTable into a javascript chart for rendering

 
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a standard JSF application which returns a list of numbers into a list. I would like to have an accompanying javascript line chart on the same page. My confusion is whether I need to grab the values from the managed bean and declare these in the js file or whether i can get the same values from the xhtml file to achieve the same goal. Thanks!

My bean is:




The List.xhtml (summarized to give one column only):



In the xhtml element I tried to give the various tags html IDs corresponding to the below js file. Needless to say that didn't work. The javascript file:



 
Rancher
Posts: 989
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can reference JSF backing bean properties directly in your JS using the #{beanName.propertyValue} syntax.

Just write your JS function taking data as argument and pass that data to the function from the xhtml page.

e.g in you xhtml head section



Where createGraphs is your imported js function that builds the graph from the supplied data.



 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your helpful reply. The concept makes perfect sense but I don't fully understand.

1) Wouldn't i need an "src" tag as a script tag attribute when putting the script in the xhtml? eg:




2)

Where createGraphs is your imported js function that builds the graph from the supplied data.



So what would this function look like? Would it look something like this?




Or would it use one of the existing methods in my js file? Eg:



Please help me to understand this issue a little better. Many thanks!
 
E Armitage
Rancher
Posts: 989
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the function would be a normal javascript function that accepts the data used to build the graph e.g

The code inside that function depends on the javascript charting library that you are using. You would need to check that library's docs.
 
Saloon Keeper
Posts: 28114
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh, Jay, surely you've been around long enough to have heard my standard tirade on how JSF backing beans are NOT Controllers, they're Models. Tsk, tsk.

There's too much code flying around here for this early in the morning. My mind refuses to read it. But if you want backing bean (Model) data for use in client-side (Javascript) code, you have 2 options:

1. Push the data out as part of the page rendering and let the JavaScript code pick it up.

2. Use AJAX in your javascript code to make a request back to the server to fetch just that data. Maybe in JSON form, if you like, although I've got an app or 2 that gets it as XML. Lines of raw text work, too.

If you use option #1, the data is static on your web page, You can hide it from view inside an invisible DIV, a hidden text control, or whatever you want. Simply use the DOM functions to access it. However the data is static, so unless your javascript modified the DOM, it will not see any changes until the page (or at least the portion of the page where you've cached the values) is re-rendered.

Uusually option #2 works better.

Don't forget - when using jQuery that if you have embedded JavaScript, the "$" jQuery convention conflicts with JEE EL syntax, so either use precautions, use the alternative ("jQuery()") form, or put the javascript in its own separate resource outside of the xhtml.
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I humbly apologize for misrepresenting the sacred Hollowayan JSF Mantra. I do remember you making the distinction but I'm only gradually getting it.

I'm running for cover as I ask this next question, but isn't the difference kinda symantic? I mean isn't a controller an extension of a model (so a model itself)?

I prefer method 1 below because I'm a JQuery newbie and I want to avoid cluttering my application with different libraries. I'll use JSON if it's absolutely necessary but I figure it's easier to get the 'raw jQuery' working first. I hope you re-read my code after the morning brew, otherwise I will summarize. Happy Monday (somehow that doesn't sound right)
 
E Armitage
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jay Tai wrote: I'll use JSON if it's absolutely necessary but I figure it's easier to get the 'raw jQuery' working first.


Most client side graphing libraries will use JSON anyway. You don't need to store the data in any hidden fields if you are using JSF2 + as you can use the syntax I mentioned above directly in your JS script.
 
Tim Holloway
Saloon Keeper
Posts: 28114
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Isn't "Happy Monday" an oxymoron?

In Model/View/Controller, each leg of the tripod has a clear and distinct function.

The Model contains data.

The View presents data and allows people to alter data by interacting with controls in the View (which are typically sub-Views themselves)

The Controller is the glue that ensures that the Model and the View are in agreement. That is, if you modify the Model, then the data displayed in the View is updated. If you update the View, then the Model gets updated. That's what the Controllers do, and it's the ONLY thing that they do. In JSF, that function is part of the JSF lifecycle and the details are handled by the FacesServlet (for the overall View) and the tag library implementation code (for the individual UI control sub-views. So In JSF, you never write Controller code (at least unless you're implementing your own custom tag!)

One reason why the Controller is - and MUST be - separate from the Model is that it's entirely legal and often useful to not have a 1-to-1 View-to-Model correspondence. Obviously, a JSV View can reference multiple backing beans, but the reverse applies as well. A classic example would be if you had a table display and a corresponding chart or set of charts. When the Model changes, both the table and chart(s) are updated to reflect it via their respective Controllers. A Chart Controller is almost certainly going to be different than a Table Controller.

A lot of people get confused and think that the Action processors are Controller functions. They are not. They're outside of the MVC paradigm and are basically business methods. Likewise stuff like ValueChangeListeners are not Controller code. Remember, a Controller's SOLE function is to replicate data back and forth from Model to View. A ValueChangeListener doesn't move data, it just acts when it has been informated that data was moved.

So it's more than just a semantic curiosity. Understanding this basic concept will help you understand JSF itself, help you write simpler code with less JSF-specific dependencies and thus reduce the cost and effort of both design and debugging.

One of the primary reasons for the popularity of jQuery is its support for AJAX. It hides the warts of the various different browsers and presents a common - and simple API. So by all means, use it if it helps. jQuery AJAX can provide client-side Controller logic where necessary, which is one reason why many of the popular JSF extension tag libraries use jQuery internally. RichFaces and PrimeFaces are 2 such extensions, which means that a little care is required (since the versions of jQuery they pull in by default are sometimes ancient), but it's not that hard to get everyone playing nice together. JSON is simply a data format that happens to decode easily when fed to JavaScript. Which figures: JavaScript Object Notation.

 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe Monday's the reason it's not sinking in!

So In JSF, you never write Controller code (at least unless you're implementing your own custom tag!)



I'm confused about the term 'in JSF'. There's always a controller class in my jsf application. If I write a controller as part of an application containing jsf pages, conforming to the MVC paradigm, I'm using the JSF framework. So I'm in the JSF framework and the controller is part of that framework. Right? What else is the controller if it's not part of JSF? A separate servlet?


So are you saying the above is a model not a controller because it contains methods to get and set data where it should only have methods to ensure the model and view are in agreement? Or is the class conceptually correct and I'm wrong to call it a controller? The way I see the typical JSF MVC app is:

Model: 1) Entity class 2) Dao classes, service and façade classes (optionally with interfaces) 3) Persistence related xml files (persistence.xml)

View: 1) JSF pages 2) Methods from the controller class and model classes tasked specifically with rendering the view 3) css and image resources

Controller: 1) Controller class / servlet 2) xml and other configuration files (web.xml, glassfish-web.xml) 3) JavaScript and other 'glue' configuration resources

Knowing my mistakes in the context of the classes I've written helps me grasp the concept more thoroughly. I'd like to ask more about the use of JSON and Ajax but i'd like to rest easy on understanding the core MVC paradigm first (which I thought I did!). Thanks for the eye opener!



 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@ E.Arimtage. So the library I'm using could include JSON as a default. I don't see any references to JSON. Is there an obvious way to check? Do you recommend any libraries that play well with JSF and use JSON? From my very limited knowledge I always thought of JSON as being used in cases where persistence without a database was required.
 
Tim Holloway
Saloon Keeper
Posts: 28114
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jay Tai wrote:Maybe Monday's the reason it's not sinking in!

So In JSF, you never write Controller code (at least unless you're implementing your own custom tag!)



I'm confused about the term 'in JSF'. There's always a controller class in my jsf application.



And it's called FacesServlet.

I repeat: Backing beans are NOT Controllers. It is not merely conceptually wrong to call them Controllers, it is literally wrong. They are Models. The get/set methods are not Controller methods, they're simply the accessors that the Controllers (FacesServlet, tag implementations) use to get and set the Model properties.

Be careful when using the term "Model", though, since a lot of JSF apps contain 2 very different types of Model.

1. The GUI Model (backing bean)

2. The ORM Object Model. That is, EJB, Hibernate Entity, or whatever.

If you have ORM Objects, they're not technically part of JSF. JSF itself knows nothing about persistence. However, since ORM Model Objects and GUI Model Objects are both POJOs, you can wire them together. You can't USUALLY use an ORM Model object as a GUI Model object because JSF isn't capable of doing stuff like fetching and finding, but it's very common to make ORM objects be properties of a GUI Model object.

And, incidentally, yes, the JSF GUI Model is "dirty", since a "pure" Model would be strictly a data container, but JSF allows a backing bean to be all-data/all-logic or a mixture. It may not be ideologically pure, but it saves the need for extra coding. Struts kept the actions and the Model more widely separated, but that doubled the number of classes you needed to create, which is why JSF wasn't designed that way. People preferred the convenience.

So much for the Model. Now the View.

In JSF2, you don't construct View objects. JSF/Facelets does that, using View Templates (.xhtml). Facelets used to be an add-on, but in JSF2 it became an integral part of JSF. The View itself is the rendered HTML sent out to the client. Rendering is not done by JSF application logic, and in fact, in JSF, you can plug in alternate renderers. The Renderers are, like the Controllers, typically part of the JSF Control tag implementations. A View should not contain logic - that violates the Separation of Concerns that MVC is all about. It's not a hard rule, because you can make parts of a page conditionally renderable, but the EL logic that you use should ONLY affect rendering, and not business logic. And, since EL is a to debug, I recommend putting any logic that that's complex in a backing bean property instead of coding it directly on the View Template. Backing beans are Java code, meaning you can set breakpoints and use a debugger on their properties.

Stuff like web.xml, the actual server, and so forth are not part of the MVC subsystem. web.xml is actually known technically as the "server-independent deployment descriptor" and typically is paired with a server-dependent deployment descriptor which is often external to the WAR and has a format defined by the server implementers - there's no standard for it.

MVC in its pure form is a closed system consisting only of Model, View, and Controller. You change a Model, the Controller updates the View. You change the View, the Controller updates the Mode. The Controller is stateless, thus a single Controller instance can serve many Model/View pairs. And that's all. Nothing but data being copied back and forth automatically. Since that's actually kind of useless in the real world, we tack on appendages to import and persist data, do business computations, and so forth, but they're not actually part of the MVC part of the app. MVC cares only about the GUI.
 
E Armitage
Rancher
Posts: 989
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jay Tai wrote:@ E.Arimtage. So the library I'm using could include JSON as a default. I don't see any references to JSON. Is there an obvious way to check? Do you recommend any libraries that play well with JSF and use JSON? From my very limited knowledge I always thought of JSON as being used in cases where persistence without a database was required.


You could try flotcharts. JSON is just another data representation format much leaner than XML (because of the lack of end tags that XML has).
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

And, incidentally, yes, the JSF GUI Model is "dirty



So the only 'pure' JSF is actually a very simplistic data container part of the GUI part of the model. The rest of the model and the true power of JSF is how it talks to external POJOs, xml and property files. These external components make up a very sizeable part of a typical JSF project. They also provide much of any functionality beyond simply containing data in a GUI. So besides the huge importance on understanding the underlying technology, i'd like to ask some questions specifically about my code in this post.

If I have understood the above correctly, does this mean I have any 'excess' or redundant code in my application? Should I be including the JavaScript code in the model class instead of the controller? Have I made any syntactic or other major mistakes in the way I have coded my application?

Above all please let me know if I'm understanding the model controller distinction and the underlying concept of JSF. Thank you!
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@E.Armitage. Many thanks. I've seen Jsflot before. I will look into it
 
Tim Holloway
Saloon Keeper
Posts: 28114
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jay Tai wrote:So the only 'pure' JSF is actually a very simplistic data container part of the GUI part of the model. The rest of the model and the true power of JSF is how it talks to external POJOs, xml and property files.




Well. as a rough definition, JSF is an MVC framework with built-in validation suppport and a mechanism for firing business methods when valid data is submitted. With a side order of automatic instantiation and initialization of the GUI Model objects (backing beans).

It handles that part of the webapp very well, allowing you to use POJOs for the most part, and that's good because not only are POJOs easier to use, even in non-JSF projects, but they're usually also easier to test stand-alone without the overhead of actually firing up a web application server.

And, of course, you're correct. UI data entry and validation are only a small part of most web applications. For the rest, you can mix in whatever suits you. I like the Spring Framework, since it allows me to work with non-UI components in much the same way that JSF works with UI components and there's even a bridge service that allows you to wire Spring and JSF objects together in a simple uniform way and reference them using EL. Spring can be used to manage the persistency objects as well as other subsystems, such as emailers, LDAP interfaces, Timer services, etc. etc. etc.

Should I be including the JavaScript code in the model class instead of the controller?



Well, as I said before, you don't write any java Controller code yourself in JSF. And obviously, puttling JavaScript in a Java module doesn't work. You'd be putting the JavaScript either in a distinct ".js" file sent to the client or as an embedded <f:verbatim> element in a View Template (.xhtml). Which would then be rendered via the JSF render subsystem to produce an HTML page sent to the client.

If you employ Controller logic in JavaScript, either by brute force or via something like jQuery, the common way that it would work is by submitting a JSF FORM to the server, where JSF's normal MVC logic will handle the server-side Controller functions automatically just like any other submit of a JSF form. Then the results would come back and be used by your Javascript code. to manually re-render the part(s) of the webpage that you want updated.

An alternative would be for the JavaScript to invoke a NON-JSF part of the webapp such as a servlet or JSP, sending a standard URL request. For example, the URL might request a JSP whose layout was a JSON data template. The returned JSON data can then be easily parsed by JavaScript and used for whatever nefarious purposes you like. JSF and non-JSF components play well together. Usually by passing data back and forth as session objects, since a JSF session-scope object is exactly the same thing as a non-JSF session-scope object with the only difference being that if JSF needs it and it doesn't already exist, JSF's Managed Bean mechanism will automatically instantiate it.
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well your guidance has helped me move along in this but I'm not there yet. The advice from Tim and E. Armitage helped me to choose the right charting library and create a basic bar chart interacting between JSF and js.

I decided to use d3 chart library. I can now pull in data from a POJO controller in my JSF application to populate a bar chart, declaring in the js script:



where timeList is a java.util.List object that gets a result set from a query for a single column (actualNum), which returns a list of integers.


Most client side graphing libraries will use JSON anyway. You don't need to store the data in any hidden fields if you are using JSF2 + as you can use the syntax I mentioned above directly in your JS script.



I'm not writing any custom JSON or Ajax. So the y axis of the bar chart is being correctly populated. Now I need to pull in values to populate the data labels (x axis).

I tried using an arrayLIst (timeList = new ArrayList<TimeSeries>() in my bean). Then I used the array index in the js script:



This did not work. It gave blank values on the jsf page and an 'Unexpected Token' syntax error in the browser console. Before going any further I'd like to know if I'll need to write any custom Json or Ajax to be able to go further than pulling in just numbers into the graph. I mean it seems like the client library (js) and JSF are able to exchange data and populate the charts 'as is' without any custom parsing. So is it a matter of figuring out the correct JSF components and how to write the Array Lists in order to be able to populate the chart fully (with numbers and data labels)?

Forgive the simplistic approach to this as I really want to learn the right practices for creating these charts and the wider issue of how to best make javascript interact with JSF. Thank you!




 
E Armitage
Rancher
Posts: 989
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jay Tai wrote:

I decided to use d3 chart library. I can now pull in data from a POJO controller in my JSF application to populate a bar chart, declaring in the js script:



Don't do this. Do the EL in the JSF page to call a Javascript function using the data (as I mentioned above). That way you keep your Javascript functions containing only Javascript code.

Jay Tai wrote:



That won't work in Javascript because the statement is executed as EL first and that is invalid syntax in EL. It's one of the reasons you shouldn't be doing EL in Javascript functions. After passing the data to the Javascript function you should now be using Javascript to navigate the data object to get at the properties you want. That is why you are better off returning the graph data as JSON from your backing bean method. JS libraries (like flot)use JSON as the format for the graph data and rendering properties. You really can;t get away from using JSON if you want to do client side programming these days.
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is extremely helpful although I still have a few questions.


Don't do this. Do the EL in the JSF page to call a Javascript function using the data (as I mentioned above).



So please help me to understand this. In the below example are you not using EL within the JS script to call 'yourBean'?


<script type="text/javascript">
function refreshGraph(){
createGraphs(#{yourBean.graphData});
}

//if running on body load

$(function () {
refreshGraph();
});
</script>



JS libraries (like flot)use JSON as the format for the graph data and rendering properties. You really can;t get away from using JSON if you want to do client side programming these days.



If I understand you correctly parsing Json is a convention for more efficient integration between Java and JS. I'm going to experiment with some Json libraries and hopefully this will let me pass values into the chart. To help me fully understand the basic idea, what would be the alternative to using Json? Would I simply pass an arrayList in the EL and call this from JS script which would use Xml to parse the data?

Thanks for your help!
 
E Armitage
Rancher
Posts: 989
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The example I posted was if calling the JS file on body load (which is common) and yes it does use EL in a javascript function but as you can see it only does so to pass the data without trying to manipulate it.

Yes, you can return the data as XML from the backing bean method as well but that would not be wise if you still have to use JSON for your graph libraries
 
Greenhorn
Posts: 6
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If still an option, you can also have a quick look at highfaces (http://www.highfaces.org). There you can provide any List or Map from your backing bean to the JSF component and it instantly turns it into a chart and you won't have to play around with JavaScript or JSON. HighFaces follows a declarative approach so you can even declare multiple lists as sources for individual lines or bar series in your chart.

If you are already fixed on d3, you might at least take a look at highfaces' open src code; it is apache licensed but you could get some inspiration from it.
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@E. Armitage

Ok, making sure I fully understand the underlying concepts of Json. I was thinking of how to implements 'barebones' alternative (pure Java, EL, xml) for the full lifecycle (bean processing, js function call and chart rendering). This way I would better understand exactly where and how Json comes in (beyond its basic definition as a lightweight, human readable interchange format). Your above comment suggests that the client library (d3)

So it's ok to use EL within a js script tag, in the jsf body to call a js function provided you are only passing and not manipulating values. Basically the js logic for data manipulation should be kept in a separate file.

Yes, you can return the data as XML from the backing bean method as well but that would not be wise if you still have to use JSON for your graph libraries



Ok, making sure I fully understand the underlying concepts of Json. I was thinking of how to implements 'barebones' alternative (pure Java, EL, xml) for the full lifecycle (bean processing, js function call and chart rendering). This way I would better understand exactly where and how Json comes in (beyond its basic definition as a lightweight, human readable interchange format). Your above comment suggests that the client library (d3) almost expects the resulting data to be in Json. So while it would be possible to use 'barebones' methods all the way from the bean to the chart that would involve some very specific and possibly 'clunky' configuration of bean elements? So while it's possible to implement pure Java and EL throughout the lifecycle, Json is simply faster and more efficient? Do client charting libraries impose restrictions where you are compelled to use Json? I suspect it is not mandatory but simply more efficient? Thanks!
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Markus. Many thanks for that excellent observation. I'll have a look at highcharts immediately. I like d3 for all the visualization it offers and I figure there's almost no avoiding mastering client side technologies these days, BUT I would also like to use a library which works seamlessly with Java and jsf. I'll let you know how I get on with it. Thanks again!
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So I have managed to use Gson to pass a Gson string to the d3 library, but the List I'm using contains BOTH numbers and String values, where I want to pass each element separately to the appropriate graph axis. The Gson parse method is:







in the jsf page I call the Gson string like this:


Now I need to separate out the elements in the list so that only the integer values are passed in the Gson string. I guess i have to declare a new Gson String to pass the String labels to the y axis from the String values in the List. As shown in the commented part of the Gson method, I tried using an enhanced for loop to only return the integers but this threw a ClassCastException.

So is the final step to rendering the graph just a matter of separating out the List array elements? Is a loop iteration the right way to achieve this so that x and y values are passed correctly from the DB through Gson? Thanks


 
Tim Holloway
Saloon Keeper
Posts: 28114
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
JSON is almost literally JavaScript code (like I said earlier, JavaScript Object Notation). You can, in fact, submit it to the JavaScript eval() function to get a fully-assigned set of JavaScript variables. Although in practice, raw use of eval() is discouraged.

So when you build up JSON using GSON (or whatever), you're effectively building up a list of assignment statements that Javascript will execute on the client. And those assignment statements can be anything that makes sense to the client code. So include or exclude whatever name/value pairs you want.

Debugging hint:



Should display the actual JSON string on your web page so you can see if you've set it up properly.
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the hint. The outputputText produced pretty normal output consistent with the select * query. The table schema is timid int, varval String, actualnum int, daterec Date. The output:




I think the gson / json parsing is now pretty straightforward. I even tried to apply to a JS eval function (more interesting than practical). I think my problem now is more pure Java. Specifically I need to return specific array values and I'm trying to figure out how to apply the appropriate loop. I need to return only the 'actualnum' int value from this array.

An enhanced for loop seems to be the way to go. I started trying this in the list getter method.





I previously got a CCE which I solved. Now I still get the same values back no matter what number is chosen for the index. I'm figuring out if there is a way to alter the timeList so that it only displays only the specified index number
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think I solved a large part of this. I realize how wrong the code is opn my prior post was! Using get.(index) in the for loop is wrong. It returns an object with a specified index number. I am only interested in a single element of the Timeseries object. After some research it turns out that can be done by creating a new array list of the values I want to use (in this case Integers). Then iterating through the original object list (timeSeries) and pulling the target elements of that list to populate the integer list.




this is then used in the following Gson code:



The above seems to populate the graph succesfully from the DB. Would welcome any comments and thanks for all the help!
 
Tim Holloway
Saloon Keeper
Posts: 28114
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think the only fault that I can find is that getNumList() is creating a fresh copy of the numList on each invocation.

In POJOs - including JSF POJOs - a "getXXX" function is conventionally an accessor function. In JSF it's important that "get" functions have 2 characteristics:

1. They should be idempotent. That is, if you call them 150 times, you get exactly the same result each and every time. This is very important in JSF, since a single request may invoke the property's get function 5 or 6 times.

2. They should be very fast. Since the method can be called many times, any delays will be multiplied. For that reason, when my "get" methods are bound to high-overhead objects such as the results of a database fetch, I typically go to the well on the first invocation, cache the results as an internal property and return that property value for subsequent invocations. In other words:


I'm not sure if you've actually defined getNumList with the intent of invoking it from the View and thus as a bean property "get" method, but since you declared it "public", it is at least potentially usable as such, so I'd either implement the strategy I outlined above or change the name to something that didn't imply a property "get". In which case, you probably also want it to be a private method.
 
Jay Tai
Ranch Hand
Posts: 222
Netbeans IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So I've been mulling over your first strategy as well as the whole subject of how 'fiddly' it can be integrating JS libraries with JSF.

public Xtype getX() {
if ( this.x == null ) {
this.x = this.buildX();
}
return this.x;



I'm trying to understand how that's fundamentally different from what I wrote:



If I've correctly applied the above to your example, is the point of it to allow caching based on getting an instance of the current numList object?



 
Tim Holloway
Saloon Keeper
Posts: 28114
198
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's a little confusing there, since getTimeList itself could have had side-effects. But yes, caching is precisely the point. Build once, read many times.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, I don’t know the exact solution for it, but In our office, we generally prefer www.koolchart.com for javascript graphs, HTML 5 charts, Pie charts etc.
 
She's out of the country right now, toppling an unauthorized dictatorship. Please leave a message with this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic