Monday Nov 26, 2007
Monday Nov 26, 2007
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.
Tuesday Nov 13, 2007

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
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
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
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:
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
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
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:
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
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:
Friday Oct 19, 2007
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
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 | |||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|||||||||||||||||||||||||
|
|||||||||||||||||||||||||
|
All |
|||||||||||||||||||||||||
| Do: Edit database.yml to specify username, password, and, if necessary, database name. | |||||||||||||||||||||||||
Tuesday Oct 09, 2007
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:
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
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.
mysqladmin -u root -p create rorjmakitables_developmentIf you don't need a password, omit the -p.
development: adapter: mysql database: rorjmakitables_development username: root password: root_password host: localhost
map.connect '', :controller => 'say', :action=>'table'
<%= 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.
<%= 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'}
]
}
-%>
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
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.
<%= 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
}
-%>
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
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
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
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
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
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:
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
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.
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
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.
For more information, see wiki.netbeans.org/wiki/view/FaqCliOpen
Tuesday Aug 21, 2007
Friday Aug 17, 2007
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
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 = ? |
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' |
Tuesday Aug 14, 2007
Friday Aug 10, 2007
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

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.
BaseJSFjMaki/Web Pages/glue.js to Your-VWP-Project/Web Pages.
BaseJSFjMaki/Web Pages/resources to Your-VWP-Project/Web Pages/resources:
config.jsonjmaki.js
system-glue.js
BaseJSFjMaki/Web Pages/resources/spry folder to Your-VWP-Project/Web Pages/resources.
xmlns:a="http://jmaki/v1.0/jsf" to the <jsp:root> tag.
<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.
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
|
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;
}
|
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
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
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:
Monday Jul 09, 2007

If you would like the components to remain centered on a page when the browser is resized, try this trick.
.ctrFirstColumn { |
Monday Jul 02, 2007

Friday Jun 22, 2007
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:
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();
}
|
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);
} |
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));
} |
Yossarian, a Creator/NetBeans IDE user, submitted this tutorial to the Creator Community Docs Site: Simple Page Fragment Menu Example.
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);
} |
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.