Monday Nov 26, 2007

Getting Started With NetBeans Ruby and Rails

Do you need help getting started with NetBeans Ruby? If so, we have three learning trails to get you going. Our first trail gives you a whirlwind tour of the NetBeans Ruby and Ruby on Rails environment. The second trail provides the nuts and bolts for creating a basic Ruby on Rails application. The third trail is an all-in-one lesson for working with Ruby and Java applications. You can start at whatever trail best meets your needs.

Trail 1: Getting Started

Trail 2: Creating a Ruby on Rails Application

Trail 3: Integrating Ruby and Java Development

Tuesday Nov 13, 2007

Getting Your Feet Wet With Java in JRuby

If you haven't tried calling Java classes from a JRuby application yet, here is a simple code snippet to get you started. Paste the following code into the Ruby shell (JRuby IRB), press Enter, and a small desktop app opens (To open the Ruby shell in the NetBeans IDE, choose Ruby > Other > Ruby Shell (IRB) from the main menu). This code is an updated version of an example in the JRuby and the Java Platform article.

Note: A current known bug causes the JRuby IRB to report an ExitSecurityException, this bug does not affect the output.

Code Sample: Using Java Classes in the IRB Console
include Java

import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JButton
import java.awt.BorderLayout

frame = JFrame.new
panel = JPanel.new
panel.layout = BorderLayout.new
panel.background = java.awt.Color::white
frame.get_content_pane.add(panel)
frame.default_close_operation = JFrame::EXIT_ON_CLOSE
button = JButton.new "Click Me"
text = JLabel.new "I'm a Simple Program"

panel.add(BorderLayout::CENTER, text)
panel.add(BorderLayout::SOUTH, button)

class Click
    include java.awt.event.ActionListener

    def initialize(button, text)
        @button, @text = button, text
        @click_me_mode = true
    end

    def actionPerformed(event)
        source = event.source
        if (source == @button)
            if (@click_me_mode)
                @text.text = "Button Clicked"
                @button.text = "Click Again"
                @click_me_mode = false
            else
                @text.text = "I'm a Simple Program"
                @button.text = "Click Me"
                @click_me_mode = true
            end
        end
    end
end

button.add_action_listener(Click.new(button, text))
frame.title = "Example"
frame.pack
frame.visible = true 

The IRB is a nice way to test out your code. However, with the NetBeans IDE, it is just as easy to test out code in a scratch program. To see what I mean, right-click in the NetBeans Projects window and choose New > Project. In the New Project wizard, select Ruby in the Categories pane, select Ruby Application in the Projects pane, and click Next. Name the project Scratch (or whatever you want) and click Finish. The main.rb file opens in the editor.

Replace the contents of the main.rb file with the code sample. Then click the Run Main Project button in the main toolbar (the green arrow) to run the application.

As you can see by the following screenshot, the advantage of testing your code in a scratch project as opposed to using the IRB is that you get syntax coloring and all the other wonderful NetBeans Ruby editing features.

To learn about the editing features, see the NetBeans Ruby Editing wiki page, or look at Tor's screenshot of the week entries, such as Ruby Screenshot of the Week #18: Errors and Snippets (as of today, he is up to screenshot #23). We are also working on a getting started guide that will cover some of the editing features. Last, you can watch Roman's Editing screencast.

There are a couple of FAQs that you might find helpful

  1. How to Call Java From Ruby
  2. How Can I Access Java From the JRuby IRB?

You also might want to check out the Swing with JRuby: Developing a Desktop Application with the JRuby and Java Swing APIs tutorial that was written by Sun campus ambassador Teera Kanokkanjanarat.

Monday Nov 12, 2007

Help Us Design Our Docs Pages

We are redesigning the documentation lists and learning trails to include more than just written articles and tutorials. We are asking for your help in coming up with a design that works best for you. Below are links to four designs. Please take a look at each of the designs in terms of identifying the media type for a title.

Of the four, which page (v1, v2, v3, or v4) do you think makes it easiest to find what you are looking for in the desired media? Please briefly explain the benefits of that page and why you prefer it over the others.

Which page (v1, v2, v3, or v4) do you think is the worst for finding information in the desired media? Please briefly explain why you rate it last.

So as to not bias other people's opinions, please do not post your feedback as a comment. Instead, send your response to nbdocsfeedback@emailias.com

Thank you very much for your time. Hopefully your input will make it easier to find the right docs at the right time.

Wednesday Nov 07, 2007

NetBeans Ruby Shortcuts

The other day, Tor Norbye sent us an email listing some NetBeans Ruby navigation shortcuts, which we thought we'd highlight in the blog. We did a little further research on the subject and also list here some favorite user shortcuts that we undercovered.

(For a complete list of NetBeans Ruby Keyboard Shortcuts, see Ruby Shortcuts).

Navigation Shortcuts

Navigation is important - jumping between files and their tests, or between Rails actions and views. Here are some navigation shortcuts:

  • If you're in a controller file, and realize you need to modify its corresponding view, press Ctrl-Shift-A (Command-Shift-A on the Mac) to jump to it. Press again to go in the opposite direction.
  • Similarly, if you're in a Rails controller file (for example) and want to go edit its unit test, hit Ctrl-Shift-T (Command-Shift-T on the Mac) to jump to it - and again to jump back.

User Favorite Shortcuts

Here are some more frequently used shortcuts.

Action Shortcut Mac Shortcut
Show code completion alternatives Ctrl-Space. If Ctrl-Space does not work for your language, try using Ctrl-\\ Ctrl-Space
Open File by name prefix (not path) Alt-Shift-O Ctrl-Shift-O
Show name of current parameter (when editing an argument list for a method call) Ctrl-P Command-P
Format Code Alt-Shift-F Ctrl-Shift-F
Reformat the current comment paragraph Ctrl-Shift-P Command-Shift-P
Jump to matching parenthesis / brace / bracket, or other matching Ctrl-[ Command-[
Show Documentation Ctrl-Shift-Space Command-Shift-Space

NetBeans Shortcuts

You can download a shortcut card that lists the highlights of the NetBeans IDE 6.0 keyboard shortcuts and code templates. In the NetBeans IDE, choose Help > Keyboard Shortcuts Card from the main menu. Similarly, you can view the shortcuts online from the NetBeans IDE 6.0 Keyboard Shortcuts Specification.

Friday Nov 02, 2007

Confessions of a NetBeans Ruby User

Teera Kanokkanjanarat is a Sun campus ambassador who recently contributed the tutorial Swing with JRuby: Developing a Desktop Application with the JRuby and Java Swing APIs. Here we interview Teera to find out more about his interest in NetBeans Ruby.

First, tell us a little bit about yourself.

I've been working as a freelance software developer for about 8 years ever since finishing high school. My work mainly focuses on the web platform with various technologies ranging from Java, ASP.NET, PHP, and recently I got started on Ruby and Rails. Since November 2006, I've been hired by Sun as a campus ambassador at Simon University in British Columbia, Vancouver, where I'm completing my degree in Computing Science and Business Administration.

What is your interest in Ruby?

Coming from the strongly-typed language world of Java and C#, I find the flexibility and dynamic of the Ruby language to be very interesting. I believe that the productivity of developers has a heavy impact on the cost of software projects. I often find that I waste time waiting for the project to compile and re-deploy to web or application servers. So that's the first thing I found really appealing when I started working with the Ruby and Rails framework. Ruby seems to gain a lot of momentum on the web platform with the Rails framework. Now I'm more interested in the future of Ruby as a rich client on the desktop.

How did you learn Ruby?

I started out on Hal Fulton's The Ruby Way book to learn the Ruby language itself and the Ruby way of doing things. I often watch screencasts and vodcasts for techniques on learning Rails. I'm also a member of the Vancouver Ruby and Rails user group, where I attend monthly meetings. This is an interesting group; as a Java guy, I learn so much from others who work with Ruby on a daily basis.

What do you like and dislike about Ruby?

The Ruby language itself is beautiful. There are not many programming languages that are as intuitive and give me that "wow this is cool stuff!" sort of thrill. Of course, this is also because of Ruby's coding conventions and key principles.

I actually did a small experiment re-creating one of my old, small Java-based web projects with Ruby on Rails. I found that the entire project on RoR actually contains fewer lines of code than that in the previous version's configuration files!

In my opinion, performance and deployment are still the key issues of Ruby. JRuby and other initiatives are really aiming on these two issues.

How has NetBeans helped you build Ruby apps?

I tried RadRails, TextMate, and InstantRails. Yet, I like Netbeans Ruby support the most, especially in code editing, the Ruby debugger, and the auto-complete capability. Netbeans is tightly integrated with JRuby as well.

Tell us about the NetBeans Ruby app you are currently building?

I'm developing JSF web components for one of the my clients. There's future planning to release these components in rich client version (Swing and SWT). I'm doing an experimental project on how to leverage JRuby for developing these desktop components.

What was your favorite experience as a Sun ambassador?

Meeting with people! I made a lot of friends from around the world through this program. I also learned a lot from talking to people when I do evangelizing work, whether it's a tech demo or a presentation at a user group. Nothing beats learning from those who do real work out there in the field.

What are some things you like to do outside school and work?

I started a small coffee shop back when I was 19 and opened up a day-spa with my sister about two years ago. Both of them are in Thailand. So, I'm helping my sister run them remotely.

Where do you see yourself in five years?

Completing my degree is my first priority (it has been delayed several times due to my work). After finishing my term at Sun at the end of this year, I'll be joining Business Objects as a software developer. In the next five years, I might do another startup if there some good ideas come along, but things change, you never know.

Tuesday Oct 30, 2007

Ruby Getting Started Draft Available for Review

 

We have posted a draft of the first 2 sections of the Getting Started With Ruby and Rails tutorial. If you can take some time to look it over and give us feedback, please do.

For those of you who are new to using the NetBeans Ruby support, we would like to know:

  • How is it so far for getting you started with using the product?
  • Were the steps clear and complete? Did you stumble or have to try a step more than once to get it to work?
  • Is it too much for introductory material? If so, what to remove. If not enough, what to include.
  • Looking at the proposed table of contents, does it appear it will be complete? Too much?

For those of you who are experienced with Ruby, can you look for incorrect terminology or misinformation? Are the code examples ok?

To provide feedback on this tutorial, please send corrections, suggestions, and comments to the NetBeans Ruby Developers mailing list at dev@ruby.netbeans.org. Put "Getting Started Draft Feedback" in the subject line.

Monday Oct 29, 2007

Community-Contributed NetBeans Ruby Docs

In this blog, we would like to acknowledge two NetBeans Ruby community-contributed tutorials:

Thanks to Teera and Amit, we have a richer documentation set, which you can view in its entirety on the NetBeans Ruby Tutorials and Screencasts page.

If you are interested in contributing documentation to the NetBeans Community, consider joining the dev@userguide.netbeans.org email alias. This alias is for community members who want to not only contribute documentation but also provide input and feedback regarding existing NetBeans documentation. You can sign up for the alias as follows:

  1. Go to the NetBeans Mailing Lists Page
  2. Log on with your user name. If you don't have a user name, click Login and then register for a login name.
  3. Scroll to the dev@usersguide.netbeans.org mailing list.
  4. Click subscribe to send a subscription request.

Friday Oct 19, 2007

Got Ruby Questions?

Next week (October 22 - 26) you will have the opportunity to submit written questions about all things NetBeans to a team of NetBeans evangelists, including Ruby technology evangelist Brian Leonard.. You can submit a question any time during that week, and the evangelists will try to answer as many questions as possible. They will also post a selected set of questions and answers. To learn more, visit the Ask the Experts events page.

Monday Oct 15, 2007

Chart for NetBeans Ruby Database Access Setup

I have written both an installation and configuration article and an accessing databases FAQ for projects built using NetBeans Ruby support. However, because there are lots of different configuration paths, and each path requires some in-depth information, neither of these documents make it easy to quickly figure out what you must do to set up your Rails project to access your database server. I created this chart to hopefully make the steps simpler, and more clear. If you need more details, then consult the two documents that I mention above.

Steps for Accessing Databases Using NetBeans Ruby Support
 
Using JRuby
 
Using MySQL
 
   Using JDBC
Do:  Put the MySQL JDBC 3.0 compliant driver in netbeans-install-dir/ruby1/jruby-1.0.1/lib.
Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Select the Access Database Using JDBC checkbox in the New Project wizard.
 
  Using the Bundled MySQL Adapter
Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Clear the Access Database Using JDBC checkbox in the New Project wizard.
 
Not Using MySQL
   Do:  Put database's JDBC 3.0 compliant driver in netbeans-install-dir/ruby1/jruby-1.0.1/lib
Do: Select the database server from the drop-down list in the New Project wizard.
Do: Select the Access Database Using JDBC checkbox in the New Project wizard.
Notes: Currently, the supported databases are: MySQL, PostgresSQL, Oracle, HSQLDB, and Java DB (also known as Derby). The database's JDBC driver must be a pure Java driver. If you are deploying to GlassFish, you must also put a copy of your database server's JDBC driver in glassfish-install-dir/lib and start (or restart) the GlassFish server.

 
Using Native Ruby
 
Using MySQL
  
Using the Bundled MySQL Adapter
   Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Clear the Access Database Using JDBC checkbox in the New Project wizard.
  
Using a MySQL Gem
   Do:  Consult Ruby on Rails MySQL page. Download and install appropriate software.
Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Clear the Access Database Using JDBC checkbox in the New Project wizard.
  
Not Using MySQL
   Do:  Consult the Ruby on Rails Database Drivers page. Download and install appropriate software.
Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Clear the Access Database Using JDBC checkbox in the New Project wizard.
All
   Do:  Edit database.yml to specify username, password, and, if necessary, database name.

Tuesday Oct 09, 2007

Generating Rails Models

Our NetBeans Ruby tutorials show how to use the Rails Generator dialog box to add models to a Ruby on Rails web application. We show one step that uses the Rails Generator wizard to create the following:

  • Model File: This file contains the model's unique methods and business rules.
  • Initial Migration Files: Migration file for creating the database table. You run the migration files to create and modify the database table, and to back out changes
  • Unit Text Files: Files for testing your development.

In the subsequent step we have you edit the migration file to specify the column names and types. Did you know that you can can create the model and edit the migration file in one step by passing arguments in the Rails Generator? For example, let's say that I wanted a categories database table. I can right-click the project's node and choose Generate. In the Rails Generator wizard, I choose model from the Generate drop-down list. Then, I enter the following text in the Argument text box, and click OK to create the files:

Category name:string description:text level:integer created:timestamp icon:binary

The arguments list begins with the model name and is followed by column-name:type parameters. The type can be one of :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean. To learn more about model arguments, see the TableDefinition API.

After the IDE finishes creating the files, I can click on the create db/migrate/002_create_categories.rb link in the Rails Generator tab in the Output window to open the file in the editor. The contents looks like this:

class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.column :name, :string
      t.column :description, :text
      t.column :level, :integer
      t.column :created, :timestamp
      t.column :icon, :binary
    end
  end

  def self.down
    drop_table :categories
  end
end

Once you have a migration file set up, you can move your application to another machine and have the IDE create the tables automatically. The same is true for database changes. With the up and down methods, you can quickly add or back out changes. Migrations also make it easier to switch to a different database server, say from JavaDB to MySQL.

Note: If you have an existing database, and you want to quickly create migration files, right-click the project node and choose Run Rake Task > db > schema > dump. The IDE writes the schema for your database to Database Migration > schema.rb. You can copy the create statements from the schema dump into migration files.

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.

Thursday Sep 20, 2007

Installing and Configuring NetBeans Ruby

Netbeans Beta 1 was released Monday, and you can download a version of the IDE that contains Ruby support from the NetBeans IDE 6.0 Download Page. A good resource to help you get started is the new tutorial Installing and Configuring Ruby Support. This tutorial provides everything you need to know from downloading, installing, and configuring Ruby support, to working with databases, to deploying a JRuby application to Glassfish.

If you are creating Ruby on Rails applications, we have another new tutorial in that area, Building Relationships Between Rails Models. This tutorials enhances the tutorial Creating a Ruby Weblog in 10 Minutes. by enabling readers to add comments to a blog post. In particular, the new tutorial describes how to create a one-to-one and a one-to-many relationship between models in a NetBeans Ruby on Rails project.

If you are interested in contributing to NetBeans Ruby, please consider joining the Ruby mailing lists: dev@ruby.netbeans.org, used to discuss development of the Ruby features for NetBeans, and users@ruby.netbeans.org, for general support and discussions of NetBeans Ruby. To subscribe to and participate in the aliases, please visit the Mailing List page.

Monday Sep 17, 2007

Arun Pushes the Edge of the JRuby/GlassFish Envelope

Last week, Arun Gupta paid a visit to the NetBeans Ruby writers. It was great to finally meet this dynamo in person and find out what a nice guy he is. When we first started writing about NetBeans Ruby, we used Arun's blog Miles to Go as one of our resources to quickly learn about the technology. Arun tells us that the blog's name has a double meaning: he is both an avid runner and he feels like he has a lot to learn in his job.

In addition to Ruby/JRuby and GlassFish, Arun blogs on a variety of topics, including jMaki, web services, WSIT, Ajax, and Web 2.0. Arun somehow manages to be one of the first to write about how to use emerging technologies, so we like to keep an eye on his blog to find out what we will be writing about in the future. For example, last Friday, he blogged about a new GlassFish gem for Rails. We also like to follow his popular "Tip of the Day" entries. You will often see his information folded into our tutorials. Arun seems to really understand his audience's information needs and he has been very helpful by providing good suggestions as to what to include in our tutorials.

Wednesday Sep 12, 2007

Native Ruby and JRuby Support in NetBeans IDE 6.0

There is a rumor floating around that the NetBeans IDE Ruby support only works for JRuby. Don't believe it. The IDE makes it very easy to use your own Ruby installation in addition to the bundled JRuby software. As a matter of fact, the first time that you open or create a Ruby project, the IDE looks on your system for other Ruby installations. If it finds any, it pops up a dialog box listing the available installations and lets you choose which one to use.

Using JRuby is just like using Ruby, and you don't have to know anything about Java to use JRuby. You can open your existing Ruby applications for development in the IDE and work with them using the IDE's features regardless of whether you have chosen to use the JRuby interpreter or your native Ruby interpreter. The one exception that I know of is that with JRuby you have to use the ActiveRecord-JDBC adapter if you are using a database server other than MySQL. However, all you have to do is to put the client driver in JRuby's lib folder, make a couple of simple changes to your database.yml, and add a snippet to your environment.rb. Tom Enebro writes about it here. The ActiveRecord-JDBC adapter works with MySQL, Postgresql, Oracle, Derby/Java DB, HQLSDB, and H2 database management systems.

One of the advantages of using JRuby is that you can access Java libraries from your Ruby application. Tor and Cindy put together a great video about this for NetBeans TV.

Another benefit is that you can war up a JRuby application and deploy it to a Java application server, such as GlassFish, just like you would with a Java web application. Arun Gupta has written several blog entries about this and the upcoming Installing and Setting Up Ruby tutorial provides step-by-step instructions for one of the simpler methods of deploying to the GlassFish server. One advantage of deploying to Java application servers is that they are designed to be multi-threaded and thus can handle more than one request at a time. In addition, Java application servers provide tools that make it easier to manage your deployed applications. For detailed information about creating and deploying JRuby applications, see the Rails Integration page on the JRuby wiki.

Monday Sep 10, 2007

New NetBeans Ruby Videos and Articles

Cindy Church and Tor Norbye have teamed up to create two more videos on NetBeans Ruby, this time focusing on the Ruby editor:

Also recently published is Brian Leonard's and Beth Stearns' article titled Test-Driven Rails Development. This article describes the features of the NetBeans IDE that can help you test your Ruby and Rails code.

Be sure to check out the NetBeans Ruby Wiki and let us know what docs you would like and if you have docs to contribute. The wiki is a community site, and the instructions for contributing are there.

Thursday Sep 06, 2007

Table Component Sample Visual Web Project for NetBeans IDE 6.0

I migrated the sample tutorial project that I created for the Sun Java Studio Creator IDE into a NetBeans IDE 6.0 web application that uses the Visual Web Java Server Faces framework. You can download this NetBeans IDE project from here. If the pages do not display in the Visual Designer (and you get an error page instead), do a clean build, then close and reopen the IDE.

Note that this project uses the JSF 1.4 versions of the Web UI components, and not the newer versions.

This sample project:

  • Gets the data from an ObjectListDataProvider
  • Has dropdown lists, checkboxes, and buttons in the table
  • Has input fields that are not associated with the underlying data provider, so the input needs to be stored separately
  • Calculates totals from the selected table rows
  • Has dynamic footer information

When you click a detail button, the button's action method uses a tableRowGroup method to get the row key for the row that the button is in. The method then uses the row key to get the value for the foodId column, which it saves in the request bean for use by the detail page.

    public String showDetailBtn_action() {
        // Find out what row was clicked
        RowKey rowKey = tableRowGroup1.getRowKey();
        // Save food id so detail page knows what food item to show
        // provide detail info for
        getRequestBean1().setFoodId(
          getSessionBean1().getFoodListDataProvider().
          getValue("foodId", rowKey).toString());
        return "detail";
    }

The checkbox column is not bound to any column in the dataprovider, but is instead bound to a page property named selected. The getter and setter use a TablePhaseListener object to manage which checkboxes are selected.

    public void setSelected(Object object) {
        RowKey rowKey = tableRowGroup1.getRowKey();
        if (rowKey != null) {
            tablePhaseListener.setSelected(rowKey, object);
        }
    }

    /\*\*
     \* Getter for selected.
     \* @return Object value for the current row's checkbox
     \*/
    public Object getSelected() {
        RowKey rowKey = tableRowGroup1.getRowKey();
        return tablePhaseListener.getSelected(rowKey);
    }

Winston explains how to do this as well as how to highlight the rows that are selected in his How to Create Muli-Row Selectable Table Component blog.

To calculate calories, the Calculate Calories button's action method calls a method that iterates over the tableRowGroup object's selectedRowKeys to accumulate the total calories for the selected rows.

    public String calculateCaloriesBtn_action() {
        getSessionBean1().setTotalCalories(getTotalCalories());
        return null;
    }

    public String getTotalCalories() {
        int total = 0;
        // Go through the list of selected rows
        Integer calories;
        Integer nbrServings;
        FoodListDataProvider foodListDP =
          getSessionBean1().getFoodListDataProvider();
        RowKey[] selectedRowKeys =
          getTableRowGroup1().getSelectedRowKeys();
        for (int i = 0; i < selectedRowKeys.length; i++) {
            String rowId = selectedRowKeys[i].getRowId();
            RowKey rowKey = foodListDP.getRowKey(rowId);
            // get serving size
            String size = (String)
              getSessionBean1().getServingSizeMap().get(rowId);
            // get calories for serving size
            calories = (Integer) foodListDP.getValue(size, rowKey);
            // get number of servings
            nbrServings = (Integer)
              getSessionBean1().getNbrServingsMap().get(rowId);
            // add to total
            total += calories.intValue() \* nbrServings.intValue();
        }
        return Integer.toString(total);
    }

The Nbr Servings text field and Serving Size drop down list are also not bound to the underlying data provider. I created Map objects to store the values for each row and bound the components to session bean properties.

    
    /\*\*
     \* Getter for property nbrServings.
     \* @return Value of nbrServings for current row
     \* defaults to 1
     \*/
    public Integer getNbrServings() {
        TableRowDataProvider rowData = 
          (TableRowDataProvider) getBean("currentRow");
        if (rowData == null) {
            return new Integer(1);
        } else {
            String rowId = 
              rowData.getTableRow().getRowId();
            Integer nbrServingsValue = 
             (Integer) this.getNbrServingsMap().get(rowId);
            if (nbrServingsValue == null) {
                return new Integer(1);
            } else {
                return  nbrServingsValue;
            }
        }
    }
    
    /\*\*
     \* Setter for nbrServings for current row
     \* @param nbrServings New value of nbrServings.
     \*/
    public void setNbrServings(Integer nbrServings) {
        TableRowDataProvider rowData = 
          (TableRowDataProvider) getBean("currentRow");
        if (rowData != null) {
            String rowId = rowData.getTableRow().getRowId();
            this.getNbrServingsMap().put(rowId, nbrServings);
        }
    }
    
    /\*\*
     \* Getter for servingSize.
     \* @return Value servingSize for current row
     \* Defaults to cup
     \*/
    public String getServingSize() {
        
        TableRowDataProvider rowData = 
         (TableRowDataProvider) getBean("currentRow");
        if (rowData == null) {
            return "cupCalories";
        } else {
            String rowId = rowData.getTableRow().getRowId();
            String servingSize = 
             (String) this.getServingSizeMap().get(rowId);
            if (servingSize == null) {
                return "cupCalories";
            } else {
                return  servingSize;
            }
        }
    }
    
    /\*\*
     \* Setter for servingSize for current row
     \* @param servingSize New value of property servingSize.
     \*/
    public void setServingSize(String servingSize) {
        TableRowDataProvider rowData = 
         (TableRowDataProvider) getBean("currentRow");
        if (rowData != null) {
            String rowId = rowData.getTableRow().getRowId();
            this.getServingSizeMap().put(rowId, servingSize);
        }
    }
    
    /\*\*
     \* Holds value of property nbrServingsMap.
     \*/
    private Map nbrServingsMap = new HashMap();
    
    /\*\*
     \* Getter for property nbrServingsMap.
     \* @return Value of property nbrServingsMap.
     \*/
    public Map getNbrServingsMap() {
        
        return this.nbrServingsMap;
    }
    
    /\*\*
     \* Setter for property nbrServingsMap.
     \* @param nbrServingsMap New value of property nbrServingsMap.
     \*/
    public void setNbrServingsMap(Map nbrServingsMap) {
        
        this.nbrServingsMap = nbrServingsMap;
    }
    
    /\*\*
     \* Holds value of property servingSizeMap.
     \*/
    private Map servingSizeMap = new HashMap();
    
    /\*\*
     \* Getter for property servingSizeMap.
     \* @return Value of property servingSizeMap.
     \*/
    public Map getServingSizeMap() {
        
        return this.servingSizeMap;
    }
    
    /\*\*
     \* Setter for property servingSizeMap.
     \* @param servingSizeMap New value of property servingSizeMap.
     \*/
    public void setServingSizeMap(Map servingSizeMap) {
        
        this.servingSizeMap = servingSizeMap;
    }
    

Friday Aug 31, 2007

Publishing Now Belongs to the Community

Just watched this interesting video which pretty much sums up my 10 years at Sun.

At first I wrote "man" pages and hard-copy manuals that were published once a year. By the time they came out, they were already obsolete. I never knew if anyone read my stuff or if it met their needs. We eventually started writing technical articles in HTML, but these were not published until the official release. Any errors or updates could not be corrected until the next release. In the past few years, we have been publishing our tutorials on the web as soon as we write them and updating them whenever necessary. We put feedback buttons on the page so people could report errors or make suggestions. We wrote back and often started dialogs. We requested tutorial suggestions and got lots of input. Then we started this blog and started pushing out information as soon as we learned it, so that people didn't have to wait until we had put it in some polished tutorial. Now we have joined the NetBeans Ruby team and our roles have totally changed. We are no longer a group of writers who take information from the engineers and make it available to the software users, we are members of a community of contributors to the NetBeans Ruby Wiki. When I have questions about the topic I am working on, I don't just turn to the engineers, I turn to the community. They help me write my docs, and hopefully, I can help them write theirs. These are exciting times.

New Video on Java and Ruby Development

Check out the new video on NetBeans TV titled Mixing Java and Ruby Development. In this video, Ruby developer Tor Norbye uses NetBeans IDE 6.0 to integrate a Java CRUD application with a Ruby on Rails application. The video highlights many of the features of the NetBeans Ruby editor, including code completion. Also included are the Rails code generator and the IDE's JUnit module.

Our coworker, Cindy Church, put in long hours producing the video and it shows in the content and quality of the video. The video is fairly fast-paced, so a written version of the video script is also available.

Wednesday Aug 29, 2007

Opening a File From the Command Line

I learned a neat trick in the dev@ruby.netbeans.org mailing list this week, one that I wish I had discovered long ago -- how to open a file in the Netbeans editing area from the command line, even if the file is not in an opened project.

Make sure that the NetBeans bin directory is in your path. Then use the following command to open the file in the NetBeans editing area.

netbeans --open file

Even better, make an alias:

alias nb='netbeans --open '

Then you can simply type nb file. The command will start up the NetBeans IDE if necessary. If the IDE is already open, the command simply opens the file and pops it to the front of the editing area.

If you are using Windows, you can also do the following to open a file in the IDE.

  1. Right-click on a file in an explorer window.
  2. Choose Open With > Choose Program.
  3. Select NetBeans from the program list. If NetBeans is not on the program list, click Browse, navigate to and select netbeans-install-dir/bin/netbeans.exe, and click open.
  4. Click OK. The file opens in the IDE. Sometimes the IDE does not show the file's tab right away so it looks like the file has a different name. If you hover over another tab, the file's tab usually appears.

For more information, see wiki.netbeans.org/wiki/view/FaqCliOpen

Tuesday Aug 21, 2007

Relatively Positioning Web UI Components

Tip on positioning Web UI components based on the width of the browser window in a NetBeans Visual Web Application or a Sun Java Studio Creator Application.[Read More]

Friday Aug 17, 2007

Check Out the NetBeans Ruby Wiki

Gail has been very busy this week working on the docs pages at the NetBeans Ruby Wiki Check it out and let us know what you think. This is a community site, so if you have stuff to contribute, the instructions are there.

At the bottom of the main page is a link to Documents Under Construction. I have the honor of listing the first draft to be offered up for review, "Installing and Configuring Ruby Support in the NetBeans IDE." This is a very raw draft, as I am still in the learning and exploring phase of information gathering. I thought it would be good to get this out so we can get feedback on what kind of information you really need during your initial use of the Ruby Support Package.

A lot of the stuff we put in here was due to the suggestions you have sent us so far. I also want to give Tor, Brian, Arun and other developers a big applause for providing most of the information that I added to this draft through their blogs and their wiki contributions.

Thursday Aug 16, 2007

SqlException: At least one parameter to the current statement is uninitialized

When you do the Using Databound Components to Access a Database tutorial, you learn how to use the Query Editor on the rowset to build the SQL statement to retrieve the desired set of data. You also learn that for every ? (parameter) in your query, you need to call setObject() on the rowset before the query is executed. Take, for example, the following query.

SELECT ALL TRAVEL.TRIP.TRIPID, 
           TRAVEL.TRIP.PERSONID, 
           TRAVEL.TRIP.DEPDATE 
FROM TRAVEL.TRIP
WHERE TRAVEL.TRIP.PERSONID = ?
   AND TRAVEL.TRIP.TRIPTYPEID = ? 
This query has two parameters, PERSONID and TRIPTYPEID. What this means is that you have to provide values for these two parameters before the rendering phase. You typically do this in the prerender() method, as shown in the following code example.
public void prerender() {
    if ( personIdDD.getSelected() == null ) {
        try {
          personDataProvider.cursorFirst();
          getSessionBean1().getTripRowSet().setObject(
            1, personDataProvider.getValue("PERSON.PERSONID"));
          getSessionBean1().getTripRowSet().setObject(
            2, "4");
          tripDataProvider.refresh();
        } catch (Exception e) {
          error("Cannot switch to person " +
              personDataProvider.getValue("PERSON.PERSONID"));
            log("Cannot switch to person " +
              personDataProvider.getValue("PERSON.PERSONID"), e);
        }
    }
}

If you forget to set the parameters before the rendering phase, you usually get the following error.

SqlException: At least one parameter to the current statement is uninitialized.

You will also get an error like this if you do not set all the parameters. Such as only calling setObject(1, somevalue) when you have two parameters in the query.

Another common error is to forget to edit the query to add the parameters. If you call setObject(1, somevalue), but your query has no parameters (no ?), you might get an error like the following.

java.lang.NullPointerException
at org.apache.derby.client.am.PreparedStatement.checkForValidParameterIndex(Unknown Source)

Similarly, if you call setObject(2, somevalue) when your query has only one parameter, the server will emit something like the following message.

SqlException: The parameter position '2' is out of range.  
The number of parameters for this prepared  statement is '1'

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.

Tuesday Jul 31, 2007

Goodbye California, Hello Hawaii

After several years of going back and forth between the mainland and Hawaii, we decided to make the Big Island our permanent home. It was hard saying a final goodbye to my California friends, but it will nice being able to spend more time with the friends I have made here.

If there are any Java or Ruby user groups on the Big Island, please post a comment and let me know.

Friday Jul 20, 2007

NetBeans Ruby Docs

We are in the process of planning the documentation for NetBeans Ruby and would like to know what information you are interested in. Is there a certain tutorial that you want? Is there a video that you would like to see? Please let us know what information would help you better complete your job, and we will add it to our documentation plan wiki. Feel free to edit the wiki and add your own document requests.

Also, take a look at our two existing tutorials, Creating a Ruby Weblog in 10 Mintues and Putting Flickr on Rails, contributed by NetBeans evangelist Brian Leonard. To send comments on these tutorials, use the Send Us Your Feedback button on the bottom of the tutorial. It's been fun corresponding with the readers who have already sent feedback.

We welcome your contributions in other ways as well:

  • Contribute to the NetBeans Ruby wiki. These contributions might include tutorials, FAQs, articles, and tips and tricks. You can write a whole article, or send us the information and we will turn it into an article for you. If you are unsure where to start, an excellent source of information is the NetBeans Community Docs Page. Additionally, if you need any help or have any questions, please contact us. We work closely with James Branam, the NetBeans Community Docs Manager.

  • Write a hint. Tor Norbye just implemented the Quick Fix feature for Ruby in NetBeans and has invited the community to jump in and add their own quick fixes. Tor's written a How to Write a Hint document, which tells you everything you need to know.

  • Join the mailing lists. Of particular interest are dev@ruby.netbeans.org, used to discuss development of the Ruby features for NetBeans, and users@ruby.netbeans.org, for general support and discussions of NetBeans Ruby. To subscribe to and participate in the aliases, please visit the Mailing List page.

Monday Jul 09, 2007

Centering Web UI Components on a Page


If you would like the components to remain centered on a page when the browser is resized, try this trick.



  1. Open the Web Pages > resources > stylesheet.css style sheet and add the following style definitions. You will use these styles to define the colum styles in a three column grid panel.


    .ctrFirstColumn { 
       width: 10%;
    }

    .ctrSecondColumn {
       width: 80%;
    }

    .ctrThirdColumn {
       width: 10%;
    }



  2. Set the widths percentages to what works for your page.




  3. Save the changes, then close and reopen the IDE, so that the IDE picks up the new styles.




  4. Add a Grid Panel to the page in the top left corner.





  5. In the Properties window, click the ellipsis (...) button for the style property. Select Position, set both the Width and Height to 100%, and click OK.




  6. Set the columns property to 3.




  7. Click the ellipsis (...) button for the columnClasses. Select ctrFirstColumn and click the > button. Repeat for ctrSecondColumn and ctrThirdColumn. Click OK. These styles are applied to the columns in the grid panel in the order that you list them.




  8. Drop something into the first column, such as a blank Static Text component. As you drop each component into the Grid Panel, it occupies the first available column, so the first component that you drop goes in the first column, the second component goes in the second column, the third component goes in the third column, and the fourth component goes in a new row in the first column. A blank Static Text component is an easy way to occupy the left and right margins with a non-visible component.




  9. For the center column, drop a component from the Layout section, such as a Grid Panel or a Layout Panel. This is the component that you will use to layout all the components in the page. You can nest the layout components as necessary in order to achieve the right layout.



    You most likely want to set the width properties of the layout components to 100% or some other percentage value instead of using pixel sizes.


  10. When you add a Table component, set its width property to 100% or some other percentage value. (See the tips in the Laying out Multiple Table Components blog entry.) One thing to remember, is that whenever you work with the table layout, you have to check to make sure that the IDE did not change the width property back to a pixel width. If you find that your middle panel is not centering, check the width values of the Table components to make sure they are set to percentages.



  11. Drop a blank component, such as a blank Static Text component, to occupy the right column.

  12. Run the web app and resize the width of the browser. The components should remain centered.

Monday Jul 02, 2007

Laying Out Multiple Table Components



You can use the layout components, such as the Group Panel and the Grid Panel, to easily layout and size container components, such as the Table component. In the screen shot above, the two tables on the left are in a Group Panel, and the two on the right are in a Grid Panel. I can resize or move either panel in the Visual Designer, and the contents will resize and move in accordance (they won't resize in the Visual Designer, but they will resize in the client). The trick is to set the width property of each tables to 100% so that they resize based on the size of their container.

Because the Visual Designer does not display the widths of the tables accurately, you have to right-click on the page and choose Preview in Browser to get a feel of how the tables will actually appear in the client.

Tips:

  • Set the Group Panel component's block property to true. This encloses the panel in a <div> tag.

  • You can set the Group Panel component's separator property to <br /><br /> to put spacing between the tables.

  • Set the Table component's width property to 100%. If you make changes to the table, the IDE may reset this property so keep checking to make sure it is 100%.

  • I find it best to leave the Table Column width properties blank or set them at percentage amounts, such as 10%.

Friday Jun 22, 2007

Page Fragment Tips

7/16/07 Update: Thanks to Antonio, this blog entry is now available in Spanish.

Page fragments enable you to add a particular set of components, action handlers, and functions to a bunch of web pages. When you add a Page Fragment Box to a page, you are first given the option of choosing an existing page fragment or creating a new one, and then the IDE adds a <jsp:directive.include> tag to the main page (the page that includes the fragment). When you create a page fragment, the IDE adds both a .jspf file and a backing bean to the project.

The <jsp:directive.include> directive is not the same as, the <jsp:include> standard action. The directive causes the contents of the page fragment to be placed into the main page's .jsp before the .jsp file is translated into a servlet.

The page fragment's backing bean extends AbstractFragmentBean, which, unfortunately, does not provide the preprocess or prerender methods. It only provides the init and destroy methods. When a person lands on the page from another destination, such as by typing in the URL or clicking a link, the server instantiates the fragment's backing bean (and thus calls the init method) the first time that fragment is referenced. In general, this is likely to happen during the render response phase. On a postback (that is, when the page redisplays itself in response to a page submission) , the fact that the saved component state includes component bindings to properties in the fragment's backing bean will cause the server to instantiate the page fragment's backing bean much earlier.

Because the page fragment's init method can be called early in the lifecycle, you cannot reference or set component values in the init method. Conversely, a page fragment's init method might not be called until during or after the main page's prerender call. A workaround for this is to put methods in your page fragements and call those methods from the main page's prerender. For example, you can add a prerenderFragment method in each of your page fragments. Then for each fragment that you include in the main page, add code like the following:

public void prerender() {
      TopFragment topFragment = (TopFragment)getBean("TopFragment");
      topFragment.fragmentPrerender();
      ...
  }

Here are some code snippets to illustrate some common page fragment tasks:

Passing Data Between the Main Page and the Page Fragment

You can pass data to a page fragment through the a managed bean (request bean, session bean, application bean), or through function arguments as shown below

In the following snippit, the main page passes information to the page fragment by argument:

  public void prerender() {    
     Bike bike = getSessionBean1().getBike();
    ...
    PriceTable priceTable = (PriceTable) getBean("PriceTableFragment");
    totalsSubtotalPrice.setText(priceTable.subtotal(bike));
  }

Here, the main page sets the values in the request bean, which the page fragment then picks up and uses. This is from a web application where the user selects an item from a drop-down list in the main page, which, in turn, refreshes the trip data provider in the page fragment.

    // Page Fragment
    public void fragmentPrerender() {
        if (getRequestBean1().getPersonId() != null) {
            try {
                getSessionBean1().getTripRowSet().setObject(
                        1, getRequestBean1().getPersonId());
                tripDataProvider.refresh();
            } catch (Exception e) {
                error("Cannot switch to person " +
                        getRequestBean1().getPersonId().toString());
                log("Cannot switch to person " +
                        getRequestBean1().getPersonId().toString(), e);
            }
        }
    }
    // Main Page
    public void prerender() {
        // If not a postback, set the default person
        if (getRequestBean1().getPersonId() == null) {
            try {
                personDataProvider.cursorFirst();
                getRequestBean1().setPersonId(
                  (Integer)personDataProvider.getValue("PERSON.PERSONID"));
            } catch (Exception e) {
                error("Cannot switch to person " +
                        personDataProvider.getValue("PERSON.PERSONID"));
                log("Cannot switch to person " +
                        personDataProvider.getValue("PERSON.PERSONID"), e);
            }
        }
        Fragment1 fragment1 = (Fragment1) getBean("Fragment1");
        fragment1.fragmentPrerender();
    }	

Changing Component Properties in a Page Fragment

The main page can access and modify components in the page fragment through the page fragment's bean object, as shown below:

  public void prerender() { 
    Navigation navigationFragmentBean = (    
    Navigation)getBean("Navigation");
    Hyperlink homeLink = navigationFragmentBean.getHomeLink();
    homeLink.setDisabled(true);
 }

Determining What Page the Page Fragment is Included In

In this code snippet, the page fragment changes its apperance based on what page it is being displayed in.

    public void fragmentPrerender() {
        // If they are done, show the checkout button
        String page;
        String viewId = getFacesContext().getViewRoot().getViewId();
        if (viewId == null || viewId.length() == 0 || "/".equals(viewId)) {
            page = "";
        } else {
            int pos = viewId.lastIndexOf('/');
            if (pos == viewId.length() - 1) { 
                // last char in viewId is '/'
                viewId = viewId.substring(0, pos);
                pos = viewId.lastIndexOf('/');
            }
            //ok if pos is -1, then pos+1 will be 0
            page = viewId.substring(pos+1);
        }
        checkoutButton.setRendered(FINAL_ORDER_PAGE.equals(page));
    }

Using a Tab Set in a Page Fragment for Navigation

Yossarian, a Creator/NetBeans IDE user, submitted this tutorial to the Creator Community Docs Site: Simple Page Fragment Menu Example.

Dynamically Rendering a Page Fragment Component From the Main Page

Here is a snippit where the main page dynamically renders a tree in a page fragment

    public void makeTree() {
        Fragment2 pgfrag = (Fragment2)getBean("Fragment2");
        List children = pgfrag.getDisplayTree().getChildren();
        TreeNode personNode = new TreeNode();
        personNode.setId("node1");
        personNode.setText("Shari Oln");
        children.add(personNode);
    }

Other Examples

In Winston's blog he points to Josh's web site, which uses VWP page fragments to do wonderous things. How about you? Do you have some super page fragment tips to share? If so, post them to the comments below to share with other VWP developers.

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