Dynamic Data in jMaki Widgets Using JPA

jMaki provides a rich set of data widgets that can be embedded in a web application. For most of the widgets to be useful, they need to be tied a database backend. For example consider a Table widget displaying data about your favorite stock tickers. This blog explains the steps to create such a Web application, deployed on GlassFish V2, that contains a jMaki-wrapped Yahoo Data Table widget pulling data from JavaDB.

If you are using a jMaki build higher than 0.96 (or dated after jul 30) then some steps in this entry need to be updated and described here. These steps are marked with "SEE THE UPDATED ENTRY".

  1. Create the Web application project
    1. In NetBeans IDE 5.5.1, create a new 'Web Application' project and name it as 'jmaki-jpa'.
    2. Choose GlassFish V2 as the Server as shown below:

    3. Add 'jMaki Ajax Framework' by clicking on 'Next' button while creating the project.
    4. Choose the 'Standard' layout as shown below:



      and click on 'Finish'.
  2. Configure the Database
    1. In NetBeans IDE, 'Runtime' tab, expand Databases, connect to the default database (with the URL 'jdbc:derby://localhost:1527/sample [app on APP]'). Specify the username 'app' and password 'app'.
    2. Right-click on the newly created connection and select 'Execute Command...' and enter the following query to create the table definition:

      create table COMPANY (id int,
                            companyName varchar(255),
                            price float,
                            change float,
                            percentChange float,
                            lastUpdated varchar(50),
                            PRIMARY KEY (id))
    3. Right-click on the database connection, select 'Refresh' to see the newly created table in the Tables tree. Select the 'COMPANY' table, right-click and select 'Execute Command...' and enter:

      insert into COMPANY values (1, 'A Co', 71.72, 0.02, 0.03, 'Jan 1, 2007, 10:00am' );
      insert into COMPANY values (2, 'B Inc', 29.01, 0.42, 1.47, 'Feb 1, 2007, 10:00am' );
      insert into COMPANY values (3, 'C Group Inc', 83.81, 0.28, 0.34, 'Mar 1, 2007, 10:00am' );
      insert into COMPANY values (4, 'D Company', 52.55, 0.01, 0.02, 'Apr 1, 2007, 10:00am' );

      Now our database structures are created and populated.
  3. Create the JPA (Java Persistence API) Entity class that maps to the database.
    1. In the projects window, select the project 'jmaki-jpa', right-click and select 'New' and choose 'Entity Classes From Database...'.
    2. Select 'jdbc/sample' as 'Data Source'.
    3. Select 'COMPANY' in 'Available Tables' and click on 'Add' and enter the values as shown below:



      and click on 'Next'.
    4. Specify the package name as 'server' as shown below:

    5. Click on 'Create Persistence Unit...' to create the persistence unit and enter the values as shown below:



      and click on 'Create'.

    and click on 'Finish'.

  4. Configure Persistence Unit
    1. In your project, expand 'Configuration Files' and open 'persistence.xml'.
    2. Click on 'Add Class' button and click on 'Cancel' button. For some reason the entity classes are not loaded during the first time.
    3. Click again on 'Add Class' button and choose 'server.Company' class and click 'OK'. This will ensure that the generated entity class is explicitly recognized by the EntityManagerFactory.
  5. In your project, right-click on 'Web Pages', select 'New' and then 'JSP...'. Give the name as 'data' as shown:



    and then click on 'Finish'.
  6. SEE THE UPDATED ENTRY - Replace the entire content of template 'data.jsp' with the following:

    <%@ page import="java.util.\*" %>
    <%@ page import="server.Company" %>
    <%@ page import="javax.persistence.\*" %>

    <%
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("jmaki-jpaPU");
        EntityManager em = emf.createEntityManager();

        List<Company> list = em.createQuery("select c from Company c").getResultList();

        out.println("[");
        for (int i=0; i<list.size(); i++) {
            Company c = list.get(i);
            out.println("['" + c.getCompanyname() + "'," +
                c.getPrice() + "," + c.getChange() + "," +
                c.getPercentchange() + ",'" + c.getLastupdated() +
                "']");
            if (i < list.size()-1)
                out.println(",");
        }
        out.println("]");
    %>
  7. Add and Configure jMaki widget
    1. In the generated 'index.jsp', drag-and-drop a 'Yahoo Data Table' widget from the jMaki Palette in the 'Main Content Area'.
    2. SEE THE UPDATED ENTRY - Change the generated code fragment from:

      <a:widget name="yahoo.dataTable" args="{
          columns :[
              {title : 'Company', width : 200, locked:false},
              {title : 'Price', width : 75, renderer: 'usMoney'},
              {title : 'Change', width : 75, renderer: 'change'},
              {title : '% Change', width : 75, renderer: 'pctChange'},
              {title : 'Last Updated', width : 85, renderer: 'italic'}
          ]}"
          value="[
              ['A Co',71.72,0.02,0.03,'9/1 12:00am'],
              ['B Inc',29.01,0.42,1.47,'9/1 12:00am'],
              ['C Group Inc',83.81,0.28,0.34,'9/1 12:00am'],
              ['D Company',52.55,0.01,0.02,'9/1 12:00am']
          ]" />


      to

      <a:widget name="yahoo.dataTable" args="{
          columns :[
              {title : 'Company', width : 200, locked:false},
              {title : 'Price', width : 75, renderer: 'usMoney'},
              {title : 'Change', width : 75, renderer: 'change'},
              {title : '% Change', width : 75, renderer: 'pctChange'},
              {title : 'Last Updated', width : 85, renderer: 'italic'}
          ]}"
          service="data.jsp" />

      The new text is highlighted in bold. The 'service' attribute tells jMaki runtime to pick up the data for DataTable widget from 'data.jsp' instead of the static data.
  8. That's it! Click on the Green button in NetBeans IDE to run the project or default keyboard shortcut (F6). And your browser shows the application deployed as:



    This jMaki-wrapped Yahoo Data Table widget is pulling data from JavaDB.

UPDATED: SEE THE UPDATED ENTRY - Based upon a user request, a NetBeans project for this sample can be opened via Java WebStart here. Alternatively, you can download the project and view at your own ease. Thanks to Geertjan for the tip!

Technorati: jmaki glassfish jpa netbeans

Comments:

Another way to embed dynamic data into JMaki component is to use the JSON approach which is easier to maintain and comprehend. JMaki comes with the org.json.\* classes (JSONObject, JSONArray etc) which enable one to generate the JSON format dynamic data for the JMaki UI components with ease. I have blogged about this approach with sample code at http://rwatsh.blogspot.com/2007/06/working-with-jmaki.html.

Posted by Watsh Rajneesh on June 24, 2007 at 10:47 PM PDT #

Hi Arun !! I'm trying to follow your example and others of similar characteristics, such as one I've found at JenniferB's Blog. So far I've had only "partial" success, I mean, the Yahoo table only works when I put static data on it !!! For example, if I simplify data.jsp to contain just this: <% System.out.println("[ ['A Co',71.72,0.02,0.03,'9/1 12:00am'] ]"); %> and change value="....." to service="data.jsp", the table is not displayed at all. I've also tried using something like value="${teams.teamsData}"> as suggested by Watsh, based on a JSONArray filled with data using a loop, and it didn't worked either. I'm using NB M10 and the latest jmaki module installed as a downloaded plugin. Any hints ?? Thanks in advance, Daniel

Posted by Daniel on July 06, 2007 at 09:33 AM PDT #

Daniel, You can download the NetBeans project (available at the end of entry) and play with the data yourself. Once the project is deployed, you should be able to view jmaki-jpa/data.jsp that will show exactly how data.jsp needs to look like. In your case, data.jsp needs to contain only "<% .out.println("[ ['A Co',71.72,0.02,0.03,'9/1 12:00am'] ]"); %>". System.out will print the data to GlassFish console instead.

Posted by Arun on July 06, 2007 at 09:53 AM PDT #

Thanks for you prompt answer, I'd already noticed the output to the server console, but I'm getting an error in the editor if I don't use System, so I tried that way. The error I got in every out.println line is: "unreported exception java.io.IOException; must be caught or declared to be thrown". Now the funny part is, I've downloaded and installed your project, and I got the same error in the out.println lines in data.jsp. After setting up the DB and running the project, I see it is working as expected, even though the errors keep showing up. Now I've tried with my project, compiling with errors anyways, and it worked. No trace of the error messages in the server console. Strange, what can it be ?? I'm using J2SE 6, in case this matters. Thanks for your help !!! Daniel

Posted by Daniel on July 06, 2007 at 11:24 AM PDT #

Daniel, I'm using JDK 1.5.0_011 and that could certainly be a disconnect. I'll try with Java SE 6 later and let you know.

Posted by Arun on July 10, 2007 at 07:39 AM PDT #

Hi, Arun. Very cool! It would be a very small step to use this same component with Java DB running on the client, embedded in the browser! Take a look at this article for an example of how this works.

Posted by David Van Couvering on July 11, 2007 at 03:25 PM PDT #

Excelent example, but I have problem - create new project - the name, server, ... -next- and on the next screen whenewer I check to use jMaki and the button finish becomes disabled ... any hint??? The funy is that after going back to first screen of project creation I can create project - the button finish is ebnabled.

Posted by vlk on July 11, 2007 at 10:32 PM PDT #

David, thanks for the pointer. I've added it to my todo list! Vik, is this a repeatable behavior ? If yes, then please file a bug on netbeans.org.

Posted by Arun on July 16, 2007 at 10:21 AM PDT #

NetBeans 5.5.1 SJSAS 9 Update 1 I created my own NetBeans project and followed every step very carefully, but running into the following error: exception org.apache.jasper.JasperException: java.lang.IllegalArgumentException: An exception occured while creating a query in EntityManager root cause java.lang.IllegalArgumentException: An exception occured while creating a query in EntityManager root cause Exception [TOPLINK-8006] (Oracle TopLink Essentials - 2006.8 (Build 060830)): oracle.toplink.essentials.exceptions.EJBQLException Exception Description: A problem was encountered resolving the class name - The descriptor for [Company] was not found.

Posted by Muhammad Ali Sabir on July 17, 2007 at 01:58 AM PDT #

Arun: yes it is repeatable - bug reported (response is: should be corrected in NB 6.0).

Posted by Vlk on July 17, 2007 at 03:08 PM PDT #

thanks Vlk!

Posted by Arun on July 17, 2007 at 03:21 PM PDT #

[Trackback] jMaki提供了一批可内嵌于Web应用程序的数据小部件。要使大部分小部件派上用场,需将其绑定到数据库后端,例如,我们来考虑设计一个能显示您需要的股价信息的Table小部件。本文将阐述创建此类Web应用程序的步骤,该应用程序部署在GlassFish V2上,其中包含一个jMaki包装的Yahoo Data Table小部件,用于从JavaDB取回数据。

Posted by yanglilibaobao on July 19, 2007 at 05:33 AM PDT #

[Trackback] jMaki提供了一批可内嵌于Web应用程序的数据小部件。要使大部分小部件派上用场,需将其绑定到数据库后端,例如,我们来考虑设计一个能显示您需要的股价信息的Table小部件。本文将阐述创建此类Web应用程序的步骤,该应用程序部署在GlassFish V2上,其中包含一个jMaki包装的Yahoo Data Table小部件,用于从JavaDB取回数据。

Posted by yanglilibaobao on July 19, 2007 at 05:33 AM PDT #

Muhammad, Looks like the Company entity is not found for some reason - could be some sort of packaging problem, e.g. persistence.xml is in wrong place or doesn't have a reference to the jar file where the entity is (if it is in a jar file). Can you send me the zip file of your project ?

Posted by Arun Gupta on July 31, 2007 at 12:20 AM PDT #

[Trackback] jMaki returns from vacation...with pictures:)

Posted by Ludovic Champenois's Blog on July 31, 2007 at 11:09 AM PDT #

[Trackback] jMaki is a light-weight framework for build Web 2.0 applications. It provides support for multiple languages - Java (1, 2, 3, 4, 5, 6) , PHP, Ruby (1, 2), Phobos (1). The numbers in parentheses indicate the entries that I've...

Posted by Arun Gupta's Blog on August 23, 2007 at 11:08 PM PDT #

[Trackback] Doris pointed out that one of my earlier post is not working any more. The main reason for this is because jMaki data models have evolved since I wrote the original entry and are now formalized. Here is the delta...

Posted by Arun Gupta's Blog on August 27, 2007 at 01:50 PM PDT #

Hi, how can I use GROUP BY in this example? select c from Company c group by ..." ; doesn't work - Failed to load data: doAjax error communicating with data.jsp. Server returned status code 500.. best regards Anja

Posted by Anja on October 22, 2007 at 06:32 AM PDT #

Anja, if your query return results correctly then there is nothing specific done in the jMaki table. Can you make sure your query is returning correct results ?

Posted by Arun Gupta on October 22, 2007 at 06:45 AM PDT #

I have solved this problem. I created a view and load the data now from this table.
Thank you.

Posted by Anja on October 24, 2007 at 07:43 AM PDT #

Glad you could solve it. Do you want to post a blog entry and link it from here ? :)

Posted by Arun Gupta on October 24, 2007 at 07:49 AM PDT #

Hi people I still have the problem "An exception occured while creating a query in EntityManager" I use NETBEANS 6. Please help me I going CRAZY!

Posted by Victor on February 26, 2008 at 04:20 AM PST #

[Trackback] This Sample Catalog app demonstrates the usage of the Java Persistence APIs to implement server side pagination (recommended for large sets of data), and jMaki to get and display the results in a dynamic Ajax table

Posted by Carol McDonald's Blog on June 06, 2008 at 08:54 AM PDT #

[Trackback] This Sample Catalog app demonstrates the usage of the Java Persistence APIs to implement server side pagination (recommended for large sets of data), and jMaki to get and display the results in a dynamic Ajax table

Posted by Carol McDonald's Blog on June 06, 2008 at 01:29 PM PDT #

[Trackback] This Sample Catalog app demonstrates a RESTful Web Service, coded using JAX-RS: Java API for RESTful Web Services and the Java Persistence API, and a jMaki client which gets and displays the Web Service responses in a dynamic Ajax table.

Posted by Carol McDonald's Blog on July 18, 2008 at 09:04 AM PDT #

HAI

I am shamsheer, MCA working in a company using netbeans JPA, and Jmaki. please give me some information and guidelines for learning Jmaki. also give me some pdf help full for devloping jmaki aplications using databases

Posted by shamsheer muhammed on August 19, 2008 at 07:33 PM PDT #

shamsheer, I posted your request to dev@ajax.dev.java.net. Stay tuned, somebody will post a detailed response.

Posted by Arun Gupta on August 21, 2008 at 09:10 AM PDT #

shamsheer, please post your question to dev@ajax.dev.java.net directly for the benefit of other users as well.

Posted by Arun Gupta on August 22, 2008 at 02:42 AM PDT #

i use mysqljdbc connector and mysql database when i try to run data.jsp
i recieve this message.
description
The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: null
Error Code: 0
root cause

Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: null
Error Code: 0
root cause

java.sql.SQLException: Error in allocating a connection. Cause: null
note The full stack traces of the exception and its root causes are available in the GlassFish/v3 logs.

Posted by abbaspour on October 14, 2008 at 11:57 AM PDT #

abbaspour, I've not tried it with GlassFish v3 so not sure if it is something related to that. Any case, I recommend posting a question to users@ajax.dev.java.net for a wider audience.

Posted by Arun Gupta on October 15, 2008 at 02:42 AM PDT #

hi Arun i will do it but tell me the url for this forum to be able to participate in i looked for it in java.net but i could not find it.
thanks Arun

Posted by abbaspour on October 16, 2008 at 10:31 AM PDT #

abbaspour, jMaki forum is at:

http://forums.java.net/jive/forum.jspa?forumID=96

Posted by Arun Gupta on October 16, 2008 at 10:34 AM PDT #

abbaspour, I've not tried it with GlassFish v3 so not sure if it is something related to that. Any case, I recommend posting a question to users@ajax.dev.java.net for a wider audience.

Posted by BATTERY on November 27, 2008 at 08:55 AM PST #

Post a Comment:
Comments are closed for this entry.
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today