Friday Dec 14, 2007

Five-Minute Ruby on Rails jMaki Tutorial

If you have installed the NetBeans IDE support for Ruby and you are interested in integrating jMaki in your Ruby on Rails projects, here is a five-minute tutorial that will get you started. In this tutorial, you add a Yahoo data table to a Ruby on Rails view. (If you have not yet installed the NetBeans IDE 6.0 or if you need to add Ruby support to your NetBeans IDE, learn how to here.)


  1. If you haven't installed the jMaki plugin for the NetBeans IDE, it takes just a minute. Select Tools > Plugins from the main menu, select jMaki Ajax Support, click Install and follow the instructions.

  2. Follow the steps in the "Working With Ruby on Rails Files" section in the Getting Started With Ruby and Rails. This should take just a few minutes as no database is involved. Finish all the steps up to but not including the "Practicing What You Have Learned" subsection. It is important that you add the routing code (Code Sample 10) to the routes.rb file and delete the Public > index.html file.

    Note: If you already have done these sections, but added the jMaki plugin after you created the project, you need to create a new project in order to have jMaki included.

  3. Edit the Views > item > index.rhtml file.

  4. Remove the <table> including the nested <tr> and <td> tags. You will replace this HTML table with the Yahoo Data Table.

  5. Choose Window > Palette from the main menu to view the Palette window.

  6. Expand the jMaki Yahoo section in the Palette, then drag and drop the Data Table onto the index.rhtml.

  7. Replace the jmaki_widget tag with the following code:

    <%= jmaki_widget 'yahoo.dataTable',
    :value =>
    {:columns => [
         { :label => 'Id', :id => 'id'},
         { :label =>'Type', :id => 'type'},
         { :label => 'Price', :id => 'price'},
         ],
      :rows => @items
      }
    -%>
    


  8. Click the small x button in the bottom right corner of the IDE to stop the WEBrick server.

  9. Click the Run Main Project button and the browser should display a nice Yahoo table that contains the item data.

Wednesday Sep 26, 2007

Using jMaki 1.0 With NetBeans Ruby

The jMaki 1.0 framework, with support for Java, PHP, and Ruby, was released yesterday. Last week, Arun Gupta posted a screencast showing how to use jMaki wrappers of button and table widgets from Dojo and Yahoo frameworks in a Ruby on Rails application built using the NetBeans 6.0 Beta IDE.

With Arun's permission, I am supplying the steps to recreate a similar jMaki on Rails project. To save steps, I changed the order a bit. If you don't already have NetBeans Ruby Support, go to the Installing and Configuring Ruby Support tutorial for instructions.

  1. Before you begin, create the database for this Rails application. You need a database server that is supported by JRuby, such as MySQL, Java DB, PostgresSQL, Oracle, or HSQLDB. Add a database instance named rorjmakitables_development. For example, for MySQL, start the server and type the following at a command prompt.
    mysqladmin -u root -p create rorjmakitables_development
    If you don't need a password, omit the -p.

  2. If you haven't already, download the jMaki NetBeans plugin (This is org-netbeans-modules-sun-jmaki.nbm. The installer tells me it is version 1.6.11, and the info.xml in the NBM says its release date is Sept. 25, 2007).

  3. To install it into the IDE, complete the following steps:

    1. In the IDE, choose Tools > Plugins from the main menu.

    2. Click the Downloaded tab and click Add Plugins.

    3. Navigate to and select the downloaded org-netbeans-modules-sun-jmaki.nbm module, then click Open.

    4. Click Install, and click Next.

    5. Select the radio button to accept the license agreement and click Install.

    6. Select Restart IDE Now and click Finish.

  4. To create a new Ruby on Rails project, complete these steps:

    1. Right-click on a blank spot in the Projects window, and choose New Project from the pop-up menu.

    2. Select Ruby in the Categories pane, select Ruby on Rails Application in the Projects pane and click Next.

    3. If you have other Ruby installations in your path besides the bundled JRuby installation, you are asked to choose a Ruby interpreter. This dialog only pops up the first time the IDE needs to access the interpreter. For this tutorial, choose JRuby and then click Close. Note that this choice affects all Ruby projects. You can switch this setting whenever you want. See Installing and Configuring Ruby Support to learn how.

      If you have configured the IDE to not use JRuby, please use the Options wizard to switch back to JRuby for this tutorial, as described in Installing and Configuring Ruby Support.

    4. Type rorjmakitables, and accept the default location or, optionally, enter a different path.

    5. Choose a Database from the drop-down list. Your choice specifies how to set up the database.yml file. This tutorial uses MySQL.

      At the time of this writing, Java DB is not on the list, but it probably will be added later. So, if you are using the Java DB, and you don't see it on the list, don't bother selecting a database. You can edit the database.yml file instead. See Using Database Servers With JRuby for instructions.

    6. With JRuby, if you don't use MySQL, you must select the Access Database Using JDBC checkbox. This causes the project to modify the environment.rb configuration file to use the ActiveRecord-JDBC gem. So, unless you are using MySQL, check this box.

    7. Click Next.

    8. Because you are using the bundled JRuby, which includes Rails, the wizard shows that Rails is already installed. The wizard gives you the option of updating the installed version, but let's skip that.

      Click Finish.

      The Generate Rails Project tab in the Output window shows all the folders and files that the IDE creates.

  5. The IDE opens the database.yml file in the editor. Set the username for the development configuration, as shown below. If your database requires a password, set the password too.
      development:
      adapter: mysql
      database: rorjmakitables_development
      username: root
      password: root_password
      host: localhost
    
  6. To add a controller, right-click the rorjmakitables project node in the Projects window, and choose Generate. Select controller from the Generate drop-down list, set the Name to say and set the View to table, then click OK.

  7. In the Projects window, expand Configuration and double-click routes.rb to open it in the editor.

  8. Add the following line above all the other map.connect entries.
      map.connect '', :controller => 'say', :action=>'table'
    
  9. In the Projects window, expand Public, right-click index.html and choose Delete (or Rename if you would rather rename the file).

  10. In the Projects window, expand Views, expand say, and double-click table.rhtml to open it in the editor.

  11. On the right-side of the IDE is the Palette, as shown below. Expand jMaki Yahoo.



  12. Drag a Button widget from the jMaki Yahoo section and drop it on the file.

  13. Drag and drop a second Button widget.

  14. Replace the widget code fragments with the following code.
    <%= jmaki_widget 'yahoo.button',
      :value => { :label => 'Select 1',
      :action => { :topic => '/jmaki/table/select',
        :message => { :targetId => '1' }
      }
    } -%>
    <%= jmaki_widget 'yahoo.button',
      :value => { :label => 'Select 2',
      :action => { :topic => '/jmaki/table/select',
        :message => { :targetId => '2' }
      }
    } -%>
    
    These buttons use the jMaki publish/subscribe mechanism to publish to the /jmaki/table/select topic, which you will program two table widgets to listen to. The table widgets will select either the first row or the second row, depending on which button is clicked. For more details on how to use publish/subscribe, see Carla Mott's Widgets Talking To Widgets blog entry.

  15. Drag a Data Table widget from the jMaki Yahoo section onto the file.

  16. Expand jMaki Dojo and drag a Table widget from that section onto the file.

    Both these widgets use the jMaki Table Data Model.

  17. Add :subscribe=> "/jmaki/table", to each table widget, as shown in bold below, to make both tables listen to all the /jmaki/table topics.

    (Important)Also, change the row data to include numeric ids, as shown in bold, so that they match the target ids in the button code. For the first row, you have to add :id= > '1',. For the second row, which already has the :id argument, simply change bar to 2.
    <%= jmaki_widget 'yahoo.dataTable', :subscribe=> "/jmaki/table",
      :value =>
      {:columns => [
        { :label => 'Title', :id => 'title'},
        { :label => 'Author', :id => 'author'},
        { :label => 'ISBN', :id => 'isbn'},
        { :label => 'Description', :id => 'description'}
      ],
      :rows => [
        { :id=> '1', :title => 'Book Title 1', 
              :author => 'Author 1', :isbn => '4412', 
              :description => 'A Some long description'},
        { :id => '2', :title => 'Book Title 2', 
              :author => 'Author 2', :isbn => '4412', 
              :description => 'A Some long description'}
      ]
    }
    -%>
    <%= jmaki_widget 'dojo.table', :subscribe=> "/jmaki/table",
      :value =>
      {:columns => [
        { :label => 'Title', :id => 'title'},
        { :label => 'Author', :id => 'author'},
        { :label => 'ISBN', :id => 'isbn'},
        { :label => 'Description', :id => 'description'}
      ],
      :rows => [
        { :id=> '1', :title => 'Book Title 1', 
              :author => 'Author 1', :isbn => '4412', 
              :description => 'A Some long description'},
        { :id=> '2', :title => 'Book Title 2', 
              :author => 'Author 2', :isbn => '4412', 
              :description => 'A Some long description'}
      ]
    }
    -%>
    
  18. Click the Run Main Project button on the main menu (the green arrow). This starts the server and opens the table view in a browser.

  19. Click the first button to select the first row, and click the second button to select the second row.

  20. In order to display database data in the table, we must first create a model. In the Projects window, right-click the project node, and choose Generate from the pop-up menu.

  21. Choose model from the Generate drop-down list, type grid in the Arugments text box, and click OK.

  22. To define the model's data structure, expand Data Migrations in the Projects window, then expand migrate and double-click 001_create_grids.rb to open it in the editor.

  23. Replace the up method with the code shown in bold.
    class CreateGrids < ActiveRecord::Migration
    
     def self.up
        create_table :grids do |t|
          t.column :title, :string
          t.column :author, :string
          t.column :isbn, :string
          t.column :description, :string
        end
        Grid.create(:title=> 'Marathon',
           :author=> 'Jeff Galloway',
           :isbn=> '0936070250',
           :description => 'A running book for everybody');   
        Grid.create(:title=> 'The Runners Bible',
           :author=> 'Marc Bloom',
           :isbn=> '0385188749',
           :description => 'How to train, race, and get in shape');   
      end
    
      def self.down
        drop_table :grids
      end
    end
    
  24. To create the database table and populate it with the two rows of data, right-click the project node in the Projects window and choose Migrate Database > To Current Version from the pop-up menu.

  25. Now you can define a variable that contains the data from the database table. In the Projects window, expand Controllers and double-click say_controller.rb to open it in the editor.

  26. Replace the table definition with the following code shown in bold.
    class SayController  < ApplicationController
    
      def index
        table
        render :action => 'table'
      end
     def table
        @rows_data = []
        Grid.find_all().each do |data|
          @rows_data  << { :id => data.id,
            :title => data.title,
            :author => data.author,
            :isbn => data.isbn,
            :description => data.description
          }
        end
      end
    end
    
    The above code defines the rows_data variable and initializes it to an empty array. It uses the active record to find all the rows from the database and, for each row, add a hash of the fields to the rows_data array.

  27. Return to the table.rhtml view by right-clicking in the editor and choosing Navigate > Go To Rails Action or View.

  28. Replace the static rows data in the table fragments with the @rows_data variable as shown in bold below.
    <%= jmaki_widget 'dojo.table',
    :value =>
    {:columns => [
         { :label => 'Title', :id => 'title'},
         { :label =>'Author', :id => 'author'},
         { :label => 'ISBN', :id => 'isbn'},
         { :label => 'Description', :id => 'description'}
         ],
      :rows => @rows_data
      }
    -%>
    <%= jmaki_widget 'yahoo.dataTable',
    :value =>
    {:columns => [
         { :label => 'Title', :id => 'title'},
         { :label => 'Author', :id => 'author'},
         { :label => 'ISBN', :id => 'isbn'},
         { :label => 'Description', :id => 'description'}
         ],
      :rows => @rows_data
      }
    -%>
    
  29. Choose File > Save All from the main menu to save all your changes.

  30. Go back to the browser and refresh the page. The data now comes from the database table.

There you have it! To learn more about jMaki, go to www.jmaki.com. To learn more about NetBeans support for Ruby, go to wiki.netbeans.org/wiki/view/Ruby.

Friday Aug 10, 2007

jMaki 0.9.7: Using the Yahoo Tabbed View in a NetBeans Visual Web Application

Yesterday, in our blog entry about using the Spry Accordion widget, we mentioned that it uses the same data model as the tabbed view and that you would swap out widgets. Today I will show you how simple it is to do so.

First, complete the steps from yesterday's mini-tutorial.

Next, open your Base jMaki project, and drag a Yahoo Tabbed View widget into index.jsp. Run the project to ensure that all the necessary files are copied into the  resources/yahoo folder.

Copy the resources/yahoo folder from the Base jMaki project and paste it into the resources folder of your Visual Web project.

Click JSP to view the JSP tags for Page1. Replace the following line:

<a:widget name="spry.accordion" value="#{SessionBean1.tripContent}"/>

with:

<a:widget name="yahoo.tabbedview"
  value="#{SessionBean1.tripContent}" />

Now click the Run Main Project button. You should see a tabbed view instead of the accordion.

Thursday Aug 09, 2007

Using the Spry Accordion in a Visual Web Application With jMaki 0.9.7

The jMaki team keeps making great changes to the technology, but sometimes it is hard to keep up with all the changes. I have finally gotten a working version of the latest jMaki-wrapped Spry Accordion. I think that this API will be stable for awhile, so now is a good time to post some instructions on how to use the Spry Accordion in a NetBeans 5.5.1 Visual Web project using the latest NetBeans jMaki plug-in (1.6.9.9.9.5), which bundles jMaki 0.9.7.

One of the recent changes has been the data model. The jMaki team is now publishing the data model information on the ajax.dev.java.net portal at http://wiki.java.net/bin/view/Projects/jMakiDataModels. The data model for the Spry Accordion widget is as follows:

    items::= "{"  {<label> } "}"
    label ::=  "{" "label:"  <string>, [<content> | <include> |<action> ] 
       [<lazyload>]  [<rowid>] <selected>"},"
    selected ::= "selected:" "true" | "false"  (default is false)
    include ::= "include:" <string> ,  
    lazyload ::= "lazyload:" "true" | "false",
    rowid ::= "rowid:" <string> ,
    content ::= "content:" <string>,
    action ::= "action:" "{" [<topic>] <message>  "},"
    topic ::=  "topic:" <string>,
    message ::= "message:" <obj>
    obj ::= <string> | <JavaScript object literal>

Note: This model is the same as the data model for the tabbed view. This means that you can swap out the accordion with a tabbed view and not have to change the data.

To follow this mini-tutorial, you need to get the NetBeans jMaki Plugin. If you have already installed the plugin, use the NetBeans Update Center from the Tools menu to make sure you have the latest version (1.6.9.9.9.5). If you have an earlier version, See Carla's blog entry about how to update the jMaki framework resources in a jMaki project.

I noted in an earlier blog entry that you also need to download the JSF Compounds library (jsfcompounds-0.0.2.jar). This is no longer true. The 1.6.9.9.9.5 plug-in includes this library.

  1. Create a plain (not a Visual Web) Web Application project, name the project something like BaseJSFjMaki097, choose the Sun Java Application Server, and click Next. Select jMaki Ajax Framework and select JavaServer Faces, then click Finish (honestly, for the purposes of this tutorial, it doesn't really matter if you include the JSF framework or not. It works either way). You now have a project from which you can copy the necessary jMaki resources into your Visual Web Project.

  2. Drag the jMaki Spry Accordion widget from the Palette into the index.jsp to add the the widget's resources to the project.

  3. (Important) Click the Run Main Project button. I have noticed that not all the widget resource library files get copied into the project until you run the project. We need to make sure we have them all before we copy them into our VWP project.

  4. Now, create a new Visual Web Project and make it the main project.

  5. To add the jMaki libraries (ajax-wrapper-comp, org.json, and jsfcompounds) to your project, right-click the Libraries node and choose Add Library. Choose jmakilibrary from the Library Manager (when you installed the plugin, it put the jmakilibrary into the Library Manager) and click OK.

  6. Copy the supporting files from the BaseJSFjMaki project to your project:

    1. Copy BaseJSFjMaki/Web Pages/glue.js to Your-VWP-Project/Web Pages.

    2. Copy the following files from BaseJSFjMaki/Web Pages/resources to Your-VWP-Project/Web Pages/resources:

      • config.json
      • jmaki.js
      • system-glue.js


    3. Copy the BaseJSFjMaki/Web Pages/resources/spry folder to Your-VWP-Project/Web Pages/resources.

  7. You can now close the BaseJSFjMaki project.

  8. In the Visual Designer add a Group Panel component to the page (Page1). You will be putting the accordion in this component. This enables you to position the ajax widget as well as see in the visual designer where this jMaki widget is. Any of the layout components will suffice, but for this tutorial, I chose to use the Group Panel.

  9. In the IDE, click the JSP button in the editing toolbar to display the JSP tags for the page.

  10. Add xmlns:a="http://jmaki/v1.0/jsf" to the <jsp:root> tag.

  11. Replace the <webuijsf:panelGroup> tag with the following tags:
    <webuijsf:panelGroup binding="#{Page1.groupPanel1}" id="groupPanel1"
      style="position: absolute; left: 72px; top: 48px;">
       <a:widget name="spry.accordion" value="#{SessionBean1.tripContent}"/>
    </webuijsf:panelGroup>

Now we can setup the web application to return data from the Travel database in the data model format for the accordion.

  1. Click Design to display Page1 in the Visual Designer. This also causes the Navigator window to appear, which you will need in Step 5.

  2. Click the Runtime tab to display the Runtime window.

  3. In the Runtime window,  expand databases , right-click the jdbc:derby node for the travel database, and choose connect. If prompted, type travel in the Password text box and click OK. (The sample travel database is installed if the Sun Java Application Server was added to the IDE before you installed the Visual Web Pack. If you do not see the travel database, go to the NetBeans Visual Web Pack Installation Instructions for information about installing the sample travel database.)

  4. Expand the jdbc:derby node for the travel database, and expand the Tables node.

  5. Drag the TRIP node from the Runtime window and drop it on the SessionBean1 node in the Navigator window, as shown in the following screen shot.



  6. When you dropped the TRIP table on the SessionBean1 node, the IDE added a tripDataProvider node and a tripRowSet node. Double-click the tripRowSet node to open its query in the query editor.

  7. Replace the query in the Query pane (the third pane down) with the following query.
    SELECT ALL TRAVEL.PERSON.PERSONID, 
      TRAVEL.PERSON.NAME, 
      TRAVEL.TRIP.TRIPID, 
      TRAVEL.TRIP.DEPDATE 
    FROM TRAVEL.PERSON
      INNER JOIN TRAVEL.TRIP ON TRAVEL.TRIP.PERSONID = 
        TRAVEL.PERSON.PERSONID
    ORDER BY TRAVEL.PERSON.PERSONID ASC, 
      TRAVEL.TRIP.DEPDATE ASC 
    


  8. Right-click in the query pane and choose Parse Query. The query editor updates the other panes to match the query.

  9. Close the query editor.

  10. Click the Projects tab to display the Projects window.

  11. In the Projects window, double-click the Session Bean node to open the source for SessionBean1.

  12. Add the following code to the bottom of the source, just before the ending brace (}).
         public String getTripContent() {
            // Data Model Format
            // { items : [
            //   {label: "label", content : "content"},
            //   ...
            //  ]}
            String retVal = "";
            try {
                retVal = buildTripTreeData().toString();
            } catch (JSONException ex) {
                log("Exception building tree data" +
                        ex.getMessage());
            }
            return retVal;
        }
        
        
        public JSONObject buildTripTreeData()
        throws JSONException {
            JSONObject rootObject = new JSONObject();
            JSONArray items = new JSONArray();
            JSONObject itemObject = new JSONObject();
            boolean hasNext = tripDataProvider.cursorFirst();
            Integer currentPersonId =
                    (Integer) tripDataProvider.getValue(
                    "PERSON.PERSONID");
            String currentName = 
                    tripDataProvider.getValue(
                    "PERSON.NAME").toString();
            StringBuffer currentContent = new StringBuffer();
            while (hasNext) {
                Integer newPersonId =
                        (Integer) tripDataProvider.getValue(
                        "PERSON.PERSONID");
                if (!newPersonId.equals(currentPersonId)) {
                    // write out data for previous person
                    itemObject.put("label", currentName);
                    itemObject.put("content", 
                      currentContent.toString());
                    items.put(itemObject);
                    // start gathering data for a new item
                    currentPersonId = newPersonId;
                    currentName = 
                            tripDataProvider.getValue(
                            "PERSON.NAME").toString();
                    itemObject = new JSONObject();
                    currentContent = new StringBuffer();
                }
                // Add trip's date to the content
                currentContent.append(tripDataProvider.getValue(
                        "TRIP.DEPDATE").toString() +
                        "<br>");
                hasNext = tripDataProvider.cursorNext();
            }
            // write out data for last person
            itemObject.put("label", currentName);
            itemObject.put("content", currentContent.toString());
            items.put(itemObject);
            rootObject.put("items", items);
            return rootObject;
        }
    

    Note: I got the idea for the buildTripTreeData method from Watsh Rajneesh;s Working With jMaki post.

  13. Click the Run Main Project button to run the web application. You should see a panel for each employee, and each panel should contain the dates of that employee's trips. One odd thing happens, though, that I don't now how to fix. Everytime I click a panel header, the accordion gets wider. Does anyone know why that happens?

Greg and Carla say that they have added some cool features to the accordion widget. I am hoping that as I learn about them, I can add to this mini-tutorial.

Thursday Jun 14, 2007

Using jMaki 9.3 With the NetBeans Visual Web Pack or the Sun Java Studio Creator IDE

We have been blogging about jMaki for over a year, and, during that time, the technology has gone through many iterations, making most of our posts obsolete. With the release of 9.3, there became enough changes that it was time to start reposting these mini tutorials. So, to start, here are new instructions for adding jMaki to a Visual Web Application project or a Sun Java Studio Creator project.

Note: To learn about the modifications, see Carla Mott's Big changes in jMaki blog entry.

Aug 6, 2007 Update: With the later versions, such as 9.6.1, they abstracted some of the functionalities into a separate JSF Compounds library ( jsfcompounds-0.0.2.jar), which you can download from https://ajax.dev.java.net/servlets/ProjectDocumentList?folderID=7871. You must add this jar file to your classpath, by right-clicking the Libraries node in the Projects window, choosing Add Jar/Folder, navigating to and selecting jsfcompounds-0.0.2.jar, and clicking Open. A symptom of this missing jar file is getting the following error in the JSP editor: java.lang.NoClassDefFoundError: com/truchsess/faces/compound/webapp/CompoundChildTagBase

Doing the Set Up

  1. Get the 9.3 jMaki zip. You can download it from http://ajax.dev.java.net/download.html.

    Note: There is also a NetBeans jMaki plug-in. In the past, we have written how to create a NetBeans jMaki project and copy the resources from that project into a Visual Web project. When I try it with the latest NBM, I get the following error: Unable to create an instance of jmaki.widgets.yahoo.tree.Widget. See the error log for more details. If I figure out what I am doing wrong, I will repost this with the added instrucitons.

  2. Unzip it to a folder of your choice. I will refer to this folder as jmaki-dir.

  3. Unzip the zip files in jmaki-dir/widgets for the desired widget libraries. In this mini tutorial, you will use the Tree widget from the Yahoo widget library, so, at a minimum, unzip the jmaki-yahoo zip so that you end up with jmaki-dir/widgets/resources/yahoo.

  4. Create a project (if you are using the Visual Web Pack, create a Visual Web Application). In this example, I named mine Jmaki93Demo. I will refer to to the location of this project as project-dir.

  5. Copy the supporting files to your project. You can use File > Add Existing Item to add files to your project. However, to cut down on the number of steps that I have to write up, I will explain up how to copy the files using the operating system instead of using the IDE.

    1. Copy jmaki-dir/scripts/glue.js to project-dir/web.

    2. Copy jmaki-dir/scripts/system-glue.js and jmaki-dir/scripts/jmaki.js to project-dir/web/resources.

    3. Copy jmaki-dir/core/web/resources/config.json to project-dir/web/resources.

  6. In the Projects window right-click Libraries and choose Add Jar/Folder. Then, navigate to and select jmaki-dir/lib/ajax-wrapper-comp.jar, and click OK.

    This is the jMaki tag library.

  7. Copy the desired widget resource libraries to jmaki-dir/widgets/resources. For this mini tutorial, you need to copy jmaki-dir/widgets/resources/yahoo to project-dir/web/resources.

  8. In the IDE, click the JSP button in the editing toolbar to display the JSP tags for the page.

  9. Add xmlns:a="http://jmaki/v1.0/jsf" to the <jsp:root> tag.

Adding the Yahoo Tree Widget

Now you are done setting up your project resources and you can add the Tree widget to your web page. One problem that you have to work around is that the jMaki widgets do not expose their features using the Design-Time API. What this means is that you will not be able to see the widgets in the Visual Designer. In addtion, with jMaki, you wrap the component in an <a:widget> tag. Even if you were to use a component from the Pallette, if you wrap the component in an <a:widget> tag, the Visual Designer won't see it. To make it easier to work with the widgets in the Visual Designer, I usually put them inside layout components, such as the Grid Panel. That way, I can position the widgets and be able to see in the Visual Designer where the jMaki widgets are on the page.

Note: Work is in progress to provide the jMaki widgets in component libraries that will work in the Visual Designer. We did a JavaOne Hands-On Lab that covered how this is done.

  1. Click Design in the editing toolbar to return to the Visual Designer.

  2. Drag a Grid Panel component from the Layout section of the Palette and drop it on the page.

    While in the development stage, I like to set the border property to 1 to make it easier to visualize the location of the widget on the page. You can clear the border property when you are ready to deploy.

  3. Click JSP in the editing toolbar to display the JSP tags for the page. Replace the <h:panelGrid> tag with the following (this assumes that the Grid Panel's id is gridPanel1. If not, change to match. It is OK if you change the style tag.
    <h:panelGrid binding="#{Page1.gridPanel1}" border="1" id="gridPanel1" 
    style="position: absolute; left: 48px; top: 48px">
    <a:widget name="yahoo.tree"
    value="{'root' : {
    'title' : 'Food',
    'expanded' : true,
    'children' : [
    {'title' : 'Nuts'},
    {'title' : 'Fruit',
    'children' : [
    {'title' : 'Banana'}
    ]
    }
    ]
    }
    }"/>
    </h:panelGrid>
    You now have added a jMaki tag for the Yahoo Tree widget.

  4. Click the Run button. When the page displays in the browser, view the source from the browser to see how the jMaki tags are rendered.

  5. In future blogs, we will further explore the jMaki features. To keep this blog short, we will just show how to subscribe to the Tree widget's onClick topic get the widget's value. If necessary, click Design in the editing toolbar to display the page in the Visual Designer. Drag a Script component from the Advanced section of the Palette and drop it on a blank spot on the page.

  6. Click JSP to view the JSP tags.

    • If you are using the Sun Java Studio Creator IDE, replace the <ui:script> tag as follows:
      <ui:script binding="#{Page1.script1}" id="script1">
      var handler = function(message) {
      alert('You selected ' + message.value.label);
      }
      jmaki.subscribe("/yahoo/tree/onClick", handler);
      </ui:script>
    • If you are using the NetBeans Visual Web Pack, replace the <webuijsf:script> tag as follows:
      <webuijsf:script binding="#{Page1.script1}" id="script1">
      var handler = function(message) {
      alert('You selected ' + message.value.label);
      }
      jmaki.subscribe("/yahoo/tree/onClick", handler);
      </webuijsf:script>
  7. If the script tag appears before the <a:widget> tag, cut the script tag and paste it below the <a:widget> tag, or else you might get a jMaki undefined error when you run the web application and click on a tree node..

  8. Run the web application again. When you click on a tree node (not the expansion box), you get an Alert box that shows what you just clicked.

Wednesday Apr 11, 2007

See You at JavaOne 2007

For the past few months, I have been collaborating with a great group of people to bring you a fantastic hands on lab for JavaOne. This lab, session # LAB-4460 Building Ajax-Enabled JavaServer Faces Components and Web Applications With jMaki, Dynamic Faces, and the NetBeans IDE, was put together by Craig McClanahan, Matthew Bohm, Gail and Paul Anderson, Winston Prakash, and myself. It starts out by showing how to use Dynamic Faces (JSF Extensions) to add Ajax functionality to plain old JavaServer Faces components. It then teaches you how to build your own JSF Ajax-enabled component and add design-time features so that you can use it in the NetBeans Visual Web Pack. Last, it shows how to build a JSF component from a jMaki widget. By leveraging an existing jMaki widget and specialized base classes, you quickly build an Ajax-enabled JavaServer Faces component offering a rich user interface with a minimum of code.

They will also be handing out CDs of the hands on labs. The CDs contain additional labs including another lab (4420) that Craig, Matt, and I wrote that covers some of the above material as well as how to use the jMaki-wrapped DHTML Goodies Tooltip widget. In addition, the CD contains lab 4450. I contributed a section to this lab that shows how to use the jMaki-wrapped Dojo Fisheye widget.

Wednesday Sep 06, 2006

Using the dojo ComboBox in a Java Studio Creator Project

Note: See Using jMaki 9.3 With the NetBeans Visual Web Pack or the Sun Java Studio Creator IDE for updated instructions on how to add jMaki to a project.

Jennifer Ball just published two new jMaki tutorials, which you can read about in her blog. One of the tutorials shows how to use jMaki in JavaServer Faces projects, and it completes the information that I needed to figure out how to integrate a jMaki widget in a page built using the Java Studio Creator IDE. In particular, how to bind to a bean property, how to save off the widget's values, and how to make managed bean methods available for the AJAX requests.

So, here is a mini-tutorial on how to use jMaki to add a dojo AJAX combo box to a JavaServer Faces web page.

  1. Download version 4 of the jMaki zip from https://ajax.dev.java.net/. There is a newer version, but it might have changes that would break this tutorial. I will update this post after I have done some testing.

  2. Unzip the zip file, then unjar the JAR file and copy the following files to your project. To unjar the JAR file, you can use the jar xvf jMaki.war command, or you can rename the file to have a .zip extension and unzip it.

    • jmaki/resources/jmaki.js to creator-project-dir/web/resources.
    • jmaki/resources/dojo/combobox to creator-project-dir/web/resources/dojo/combobox.
    • The contents of the /resources/libs/dojo directory (not the whole dojo directory) to creator-project-dir/web/resources/libs/dojo/version.3.1.
    • jmaki/WEB-INF/lib/ajax-wrapper-comp.jar to creator-project-dir/web/WEB-INF/lib.


    Note: You might want to add the ajax-wraper-comp.jar to the IDE's library manager. Then, you can easily add the jMaki library to a project by right-clicking the Libraries node in the Projects window and choosing Add Library.

  3. Create a project.

  4. Add a Group Panel component to the page and position the component where you want the combo box to be.

  5. In the editing area of the IDE, click JSP to view the JSP script.

  6. Add xmlns:a="http://java.sun.com/jmaki-jsf" to the top-level <div> tag.

  7. Inside the tag for the Group Panel component, add the jMaki ajax tag for the combo box . Wrap the a:ajax tag inside an f:verbatim tag, as shown below. Note that the service attribute is referring to ApplicationBean1. Later, you add the completeCountry() method to the application bean to return the list of choices.

    Notice: February 2007: jMaki is still evolving. I am working with the latest version from https://ajax.dev.java.net/jmaki-plugin.html. I am still experimenting, but I think instead of the service attribute you need something like value="#{ApplicationBean1.completeCountry}". Once I get it figured out, I will post a new entry.

     
    	
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="1.2" xmlns:a="http://java.sun.com/jmaki-jsf" 
    xmlns:f="http://java.sun.com/jsf/core" 
    xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:jsp="http://java.sun.com/JSP/Page" 
    xmlns:ui="http://www.sun.com/web/ui">
        <jsp:directive.page contentType="text/html;charset=UTF-8" 
             pageEncoding="UTF-8"/>
        <f:view>
            <ui:page binding="#{Page1.page1}" id="page1">
                <ui:html binding="#{Page1.html1}" id="html1">
                    <ui:head binding="#{Page1.head1}" id="head1">
                        <ui:link binding="#{Page1.link1}" id="link1" 
                            url="/resources/stylesheet.css"/>
                    </ui:head>
                    <ui:body binding="#{Page1.body1}" id="body1" 
                        style="-rave-layout: grid">
                        <ui:form binding="#{Page1.form1}" id="form1">
                            <ui:panelGroup binding="#{Page1.groupPanel1}" 
                                id="groupPanel1" 
                                style="position: absolute; left: 24px; top: 48px">
                            <f:verbatim>
                            <a:ajax id="cb1" name="dojo.combobox" 
                               service="ApplicationBean1-completeCountry.ajax" />
                            </f:verbatim>
                            </ui:panelGroup>
                        </ui:form>
                    </ui:body>
                </ui:html>
            </ui:page>
        </f:view>
    </jsp:root>
    
    
     


  8. In the Projects window, double-click the Application Bean node to open the code in the Source Editor.

    Note: In this mini-tutorial, you add the properties to ApplicationBean1, mostly to make the tutorial short. In your own applications, you might want to create a class that extends AbstractApplicationBean and use the Managed Beans node in the Projects window to make the class' properties available in application scope.

  9. Add the following code to the bottom of the class (I got this from Jennifer's tutorial):


     
        private String[] countries =new String[] {
            "Canada", "France", "Uganda", "Ukraine", "United States of America",
                    "United Kingdom", "Japan", "Korea", "Jamacia", "Thailand"
        };
        
        private String[] countryCodes =
                new String[] {"CA", "FR", "UG", "UR", "USA", "UK", "JP",
                        "KR", "JA", "TH"
        };
        
        public void completeCountry(FacesContext context,
                String[] args,AjaxResult result) {
            result.setResponseType(AjaxResult.JSON);
            result.append("[");
            for (int loop=0; loop < countries.length; loop++){
                result.append("[\\"" + countries[loop] + "\\",\\""
                        + countryCodes[loop] + "\\" ]");
                if (loop < countries.length -1) result.append(",");}
            result.append("]");
        }		
    		
     


  10. Right-click in the code and choose Fix Imports.

  11. Run and test the code. The countries should show up in the drop-down list and, if you type K, Korea should show up in the text box.

  12. In the Projects window, double-click the Session Bean node to open it in the Source Editor. You will now add a property for storing the combo box's selection.

  13. Add the following code to the bottom of the class:

     
        private String country = "";
        
        public String getCountry() {
            return country;
        }
        
        public void setCountry(String country){
            this.country = country;
        }
    		
     


  14. In the JSP for Page1, add the value="#{SessionBean1.country}" attribute to the ajax tag, as shown below.

                            <a:ajax id="cb1" name="dojo.combobox" 
                               service="ApplicationBean1-completeCountry.ajax" 
                               value="#{SessionBean1.country}"/>		
    		
     


  15. Click Design to switch to the Visual Designer.

  16. In the Outline window, select the form1 node.

  17. In the Properties window, set the value for the onSubmit property to jmaki.attributes.get('form1:cb1').saveState();.

  18. Drop a Button component on the page and set it's text to Go.

  19. Right-click in the page and choose Page Navigation.

  20. In the Page Navigation editor, right-click and choose New Page. Click OK to accept the name Page2.

  21. Click Page1.jsp to expand the icon, then drag from Button1 to Page2.jsp.

  22. Double-click Page2.jsp to open it in the Visual Designer.

  23. Drop a Static Text component on the page.

  24. Right-click the component and choose Bind to Data. Click the Bind to an Object tab and select SessionBean1 > country (if, by chance, the property does not appear on the list, close and reopen the project and try again).

  25. Add a Hyperlink component to the page and set its text to Back. Click the ... button for the component's url property, choose Page1, and click OK.

  26. Click OK.

  27. Run the application. Select a value and click Go. The selected value, which was saved to the session bean's country property, is displayed.

  28. Click Back. Because the widget's value attribute is bound to the session bean's country property, the previously selected value is displayed.

To understand how the jMaki tags work, I highly recommend that you read both of Jennifer's tutorials.

Thursday Aug 03, 2006

jMaki, the Spry Accordion Widget, and Java Studio Creator Projects

Note: See Using jMaki 9.3 With the NetBeans Visual Web Pack or the Sun Java Studio Creator IDE for updated instructions on how to add jMaki to a project.

One of the widgets in the jMaki zip is the Spry Accordion. I thought this would be a nice way to display a page fragment menu in an application that I am building using the Sun Java Studio Creator IDE. Here is how I used the jMaki tag library to add the Accordion widget to my page fragment.

1. First, I downloaded the latest jMaki zip from https://ajax.dev.java.net/. I used 3.2.6.

2. Just like with my earlier project, I unjared the jar file and copied the necessary files to my project:

  • jmaki/resources/jmaki.js to creator-project-dir/web/resources.
  • jmaki/WEB-INF/types.properties to creator-project-dir/web/WEB-INF.
  • jmaki/WEB-INF/lib/ajax-wrapper-comp.jar to creator-project-dir/web/WEB-INF/lib.
  • jmaki/resources/spry/plainAccordion to creator-project-dir/web/resources/spry/plainAccordion.

3. Additionally, I added a resources/libs directory and copied over the Spry libraries from jmaki/resources/libs/spry.

4. I added a pageFragment, Sidebar.jspf, to my project, and in the JSP file for my page fragment, I added xmlns:a="http://java.sun.com/jmaki" to the top-level <div> tag.

5. In the page fragment, I used a Group Panel component to wrap the jMaki tag. The JSPF file looks like this:

 
	
<?xml version="1.0" encoding="UTF-8"?>
<div style="height: 400px; width: 200px; -rave-layout: grid" 
    xmlns:a="http://java.sun.com/jmaki" 
    xmlns:f="http://java.sun.com/jsf/core" 
    xmlns:ui="http://www.sun.com/web/ui">
    <f:subview id="Sidebar">
        <ui:panelGroup binding="#{Sidebar.groupPanel1}" 
            id="groupPanel1" 
            style="height: 382px; left: 0px; top: 0px; position: absolute; width: 190px">
            <f:verbatim>
                <a:ajax type="spry" name="spry.plainAccordion" />       
            </f:verbatim>
    </ui:panelGroup>
    </f:subview>
</div>

 

6. I wanted each section in the accordion to resize to the section's content. The samples that you get when you download the components from Adobe come with an AquaAccordion style that does not set a section height. To save some time, I simply copied those styles to the resources/spry/accordion/components.css file.

 
	
.AquaAccordion {
	border-left: solid 1px gray;
	border-right: solid 1px black;
	border-bottom: solid 1px gray;
	overflow: hidden;
	font-family: "Times New Roman", Times, serif;
	font-size: 16px;
}

.AquaAccordion .Tab {
	height: 24px;
	background-image: url(images/aqua-gradient.gif);
	background-repeat: repeat-x;
	background-color: #6dc1fc;
	border-top: solid 1px black;
	border-bottom: solid 1px gray;
	margin: 0px;
	padding: 2px;
	cursor: pointer;
	-moz-user-select: none;
	-khtml-user-select: none;
	text-align: center;
}

.AquaAccordion .Content {
	overflow: auto;
	margin: 0px;
	padding: 0px;
	background-image: url(images/gray-gradient.gif);
	background-repeat: repeat-x;
}

.AquaAccordion .hover {
	background-image: none;
	background-color: #33CCFF;
}

7. Now I can design my Accordion widget menu. In this simple example, I hard-coded the menu contents in my resources/spry/accordion/components.htm file. Note that because I am using the overriding styles, I am using Panel instead of AccordionPanel, Tab instead of AccordionPanelTab, and so forth.

 
	
<div id="${uuid}" class="AquaAccordion" tabindex="0">
    <div class="Panel">
        <div class="Tab">
            <div class="Label">Fruit</div>
        </div>
        <div class="Content">
            <a href="faces/FoodDetail.jsp?name=banana">Banana</a><br/>
            <a href="faces/FoodDetail.jsp?name=papaya">Papaya</a><br/>       
            <a href="faces/FoodDetail.jsp?name=grapes">Grapes</a><br/>   
        </div>
    </div>
    <div class="Panel">
        <div class="Tab">
            <div class="Label">Vegetables</div>
        </div>
        <div class="Content">
            <a href="faces/FoodDetail.jsp?name=avocado">Avocado</a><br/> 
            <a href="faces/FoodDetail.jsp?name=sprouts">Brussel Sprouts</a><br/>
            <a href="faces/FoodDetail.jsp?name=asparagus">Asparagus</a><br/>       
            <a href="faces/FoodDetail.jsp?name=onion">Onion</a><br/> 
        </div>       
    </div>
    <div class="Panel">
        <div class="Tab">
             <div class="Label">Grains and Cereal</div>
        </div>
        <div class="Content">
            <a href="faces/FoodDetail.jsp?name=rice">Rice</a><br/> 
            <a href="faces/FoodDetail.jsp?name=macaroni">Macaroni</a><br/>
        </div>       
    </div>    
</div>

 

8. To make the content sections shrink to fit the content, you must turn off animation, so I modified the widget creation statement in component.js as follows:

var acc1 = new Spry.Widget.Accordion(widget.uuid, { enableAnimation: false });

9. I can now add this page fragment to all the pages in my application.

About

divas

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