Arun Gupta, Miles to go ...

Arun Gupta is a technology enthusiast, a passionate runner, and a community guy who works for Sun Microsystems.
« Excel using WSIT -... | Main | First time - Blog at... »

http://blogs.sun.com/arungupta/date/20070830 Thursday August 30, 2007

TOTD #5: Loading data from beans in jMaki widgets

The jMaki tutorial from SWDP explained the different approaches to load your own data into a jMaki widget. The jMaki widget models have formalized since then and so the code there no longer works. This TOTD explains how a combo box widget in a JSP page gets it data from a bean.

This TOTD uses NetBeans IDE configured with jMaki plugin and GlassFish.

  1. Create a new Web application project using NetBeans IDE, enable "jMaki Framework" and use all the defaults. Choose GlassFish as the "Server".
  2. In the default generated "index.jsp" page, drag-and-drop "Dojo Combobox" in the "Main Content Area".
  3. Replace the generated code with the following fragment

    <jsp:useBean id="itemBean" scope="session" class="server.ItemValueBean" />
    <a:widget name="dojo.combobox" value="${itemBean.value}"/>

    jsp:useBean tag instantiates the bean "server.ItemValueBean" in session scope. a:widget tag uses ${itemBean.value} expression to load the data by invoking getValue() method from the bean.
  4. Add a new class to the project and name it "ItemValueBean" in the package "server". Replace the entire generated code with the following:

    package server;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    public class ItemValueBean {
      public String getValue() {
        JSONArray value = new JSONArray();
        for (int i=0; i<2; i++) {
          try {
            JSONObject item = new JSONObject();
            item.put("name", "name" + i);
            item.put("label", "label" + i);
            value.put(item);
          } catch (JSONException ex) {
            ex.printStackTrace();
          }
        }

        try {
          return jsonArrayToString(value, null);
        } catch (JSONException ex) {
          ex.printStackTrace();
        }

        return null;
      }

      /**
      * Converts a JSON Object to an Object Literal
      *
      */
      public String jsonToObjectLibertal(JSONObject jo, StringBuffer buff) throws JSONException {
        if (buff == null)
          buff = new StringBuffer("{");
        else
          buff.append("{");
        JSONArray names = jo.names();
        for (int l=0; (names != null) && l < names.length(); l++) {
          String key = names.getString(l);
          String value = null;
          if (jo.optJSONObject(key) != null) {
            value = key + ":";
            buff.append(value);
            jsonToObjectLibertal(jo.optJSONObject(key), buff);
          } else if (jo.optJSONArray(key) != null) {
            value = key + ":";
            buff.append(value);
            jsonArrayToString(jo.optJSONArray(key), buff);
          } else if (jo.optLong(key, -1) != -1) {
            value = key + ":" + jo.get(key) + "";
            buff.append(value);
          } else if (jo.optDouble(key, -1) != -1) {
            value = key + ":" + jo.get(key) + "";
            buff.append(value);
          } else if (jo.opt(key) != null) {
            Object obj = jo.opt(key);
            if (obj instanceof Boolean) {
              value = key + ":" + jo.getBoolean(key) + "";
            } else {
              value = key + ":" + "'" + jo.get(key) + "'";
            }
            buff.append(value);
          }
          if (l < names.length() -1) buff.append(",");
        }
        buff.append("}");
        return buff.toString();
      }
     
      public String jsonArrayToString(JSONArray ja, StringBuffer buff) throws JSONException {
        if (buff == null)
          buff = new StringBuffer("[");
        else
          buff.append("[");

        for (int key=0; (ja != null) && key < ja.length(); key++) {
          String value = null;
          if (ja.optJSONObject(key) != null){
            jsonToObjectLibertal(ja.optJSONObject(key), buff);
          } else if (ja.optJSONArray(key) != null) {
            jsonArrayToString(ja.optJSONArray(key), buff);
          } else if (ja.optLong(key, -1) != -1) {
            value = ja.get(key) + "";
            buff.append(value);
          } else if (ja.optDouble(key, -1) != -1) {
            value = ja.get(key) + "";
            buff.append(value);
          } else if (ja.optBoolean(key)) {
            value = ja.getBoolean(key) + "";
            buff.append(value);
          } else if (ja.opt(key) != null) {
            Object obj = ja.opt(key);
            if (obj instanceof Boolean) {
              value = ja.getBoolean(key) + "";
            } else {
              value = "'" + ja.get(key) + "'";
            }
            buff.append(value);
          }
          if (key < ja.length() -1) buff.append(",");
        }
        buff.append("]");
        return buff.toString();
      }
    }

    The getValue methods contains the logic to generate the business data. In this case, the method generates the data model expected by ComboBox using JSON APIs. This data can very well be generated by creating a Persistence Unit and querying a database using JPA or any other mechanism.

    The jsonToObjectLibertal and jsonArrayToString methods were originally posted here. These two methods are required because the JSON parser does not allow you to create object literals but only JSON objects. By default these contain key : value pairs where the keys are enclosed in double quotes which does not match with the expected data model.

  5. Deploy and Run the application. The browser windows shows the default page with a drop-down list box. The expanded list box shows the items that are added to the combo box.


     

Another way to populate jMaki widgets with your data (using JPA) is explained here.

Please leave suggestions on other TOTD that you'd like to see. A complete archive is available here.

Technorati: totd jmaki beans glassfish netbeans

del.icio.us | furl | simpy | slashdot | technorati | digg |
|
Comments:

Arun, I have a TOTD request: what is the format of the config.xml file used by wsmonitor([1], under step #4 of "How can I use it?" section] for us to route to non-default listening and forwarding posts? If, after answering, you can update [1] that would be great.

Thanks,
Glen

[1] https://wsmonitor.dev.java.net/

Posted by Glen on September 01, 2007 at 10:45 AM PDT #

Oops! A sample config.xml is in the /etc directory. Still, if you could update [1] to let the reader know that, that would be good.

Glen

Posted by Glen on September 01, 2007 at 10:49 AM PDT #

Hi, is there an example, how to write a selected row from a jmaki datatable into a database?

Hope to see more jmaki/java examples from you, they're very good !

Posted by Anja on October 14, 2007 at 03:57 PM PDT #

See examples of how data from a widget can be selected and used to populate another widget in:

http://blogs.sun.com/arungupta/entry/sun_tech_days_event_map

You can replace another widget with database instead and that should work. Let me know if it does not.

Posted by Arun Gupta on October 14, 2007 at 08:43 PM PDT #

Thank you for your rapid answer.

But how looks the database-query for insert the row data from data.table.
How has the component.js in yahoo/dataTable and maybe the glue.js looks like?

Posted by Anja on October 15, 2007 at 06:10 AM PDT #

Stay tuned, I'll write something on those lines.

Posted by Arun Gupta on October 16, 2007 at 06:10 AM PDT #

Hi Arun,

I tried your example of loading data from JSF beans. The problem is when I tried to do the same thing from a managed bean on my JSF project. I'm able to print the JSON string on my page, but it doesn't load the values to my combobox. Do I need a different approach?

regards
Alexander

Posted by Alexander Cordeiro on September 24, 2008 at 05:13 PM PDT #

I tried your example of loading data from JSF beans. The problem is when I tried to do the same thing from a managed bean on my JSF project. I'm able to print the JSON string on my page, but it doesn't load the values to my combobox. Do I need a different approach?

Posted by LAPTOP BATTERY on November 27, 2008 at 05:03 PM PST #

I've not tried it with JSF managed beans so don't know what might be going on. Please send your questions to users@ajax.dev.java.net for a quicker response time.

Posted by Arun Gupta on November 28, 2008 at 07:08 AM PST #

Thanks a bunch Mr.Arun,
Wish u all the best

Posted by Fereshteh on November 08, 2009 at 11:25 PM PST #

Post a Comment:
  • HTML Syntax: NOT allowed
« Excel using WSIT -... | Main | First time - Blog at... »

Valid HTML! Valid CSS!

This is a personal weblog, I do not speak for my employer.