August 30, 2007

TOTD #5: Loading data from beans in jMaki widgets

Categories: netbeans, totd, web2.0

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();
      }
    } r>
    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

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot
Related posts:
  1. Dynamic Data in jMaki Widgets Using JPA – Updated for formal data models
  2. Dynamic Data in jMaki Widgets Using JPA
  3. TOTD #10: Consuming JSON and XML representations generated by a Jersey endpoint in a jMaki Table widget
  4. Language-neutral data format: XML and JSON
  5. TOTD #20: How to create a new jMaki widget ?

9 Comments »

  1. 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/

    Comment by Glen — September 1, 2007 @ 10:45 am

  2. 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

    Comment by Glen — September 1, 2007 @ 10:49 am

  3. 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 !

    Comment by Anja — October 14, 2007 @ 3:57 pm

  4. 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.

    Comment by Arun Gupta — October 14, 2007 @ 8:43 pm

  5. 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?

    Comment by Anja — October 15, 2007 @ 6:10 am

  6. Stay tuned, I’ll write something on those lines.

    Comment by Arun Gupta — October 16, 2007 @ 6:10 am

  7. 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

    Comment by Alexander Cordeiro — September 24, 2008 @ 5:13 pm

  8. 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?

    Comment by LAPTOP BATTERY — November 27, 2008 @ 5:03 pm

  9. I’ve not tried it with JSF managed beans so don’t know what might be going on. Please send your questions to for a quicker response time.

    Comment by Arun Gupta — November 28, 2008 @ 7:08 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress
46016 visits from Sep 11, 2009