Jun 3 2006

Rails Single Table Inheritance

Ruby on Rails supports Single Table Inheritance. Single Table Inheritance allows you to have one single SQL table, such as an employees table, manage different type of employees like managers and developers. A manager would normally have more responsibilities than a developer and you can separate these additional responsibilities in a different ActiveRecord model class.

Here is another example of Single Table Inheritance that you might find useful. You might have to support a hierarchy of users for you web application, such as User, Editor, and Administrator. An Administrator might have full Create, Read, Update, and Delete (CRUD) access while a User might just have read access. For this hierarchy of users you will need to create a Ruby class for each type and place it in the Rails app/models directory. Here is the base User class:

class User < ActiveRecord::Base
end

My Editor class:

class Editor < User
end

And the Administrator class:

class Administrator < Editor
end

Place each of these classes in their own Rails model file under the app/models directory.

To indicate to Ruby on Rails that the users table needs to support Single Table Inheritance you need to add a column named ‘type’ to the users table. Here is my users table definition:

CREATE TABLE users (
   id INT NOT NULL AUTO_INCREMENT,
   user VARCHAR(15) NOT NULL UNIQUE,
   pass VARCHAR(40) NOT NULL,
   type VARCHAR(20) NOT NULL,
   PRIMARY KEY (id)
);

In the column named type you should store the name of the class, the class type, that should be used for each user. To mark an certain user as an admin set his type to ‘Administrator’. By setting a user’s type to ‘Administrator’ you are giving him full administrator privileges as defined in your Administrator model class.

And now, in your controller you can look up all users that are administrators by using the following bit of code:

allAdmins = Administrator.find(:all)

If you want to look up all known users you can do so by using the User class as in the following snippet of code:

allUsers = User.find(:all);

At this point, you would add additional responsibilities to editors and administrators by adding methods to those model classes.


May 24 2006

JavaOne Brown Bag Session

I held a JavaOne Brown Bag session yesterday for my co-workers that were not able to attend this years JavaOne. In three days I attended 18 sessions. During my brown bag session I covered what in my mind where the highlight session of JavaOne, such as Effective Java Reloaded, Groovy = Java Tech + Ruby + Python for the JVM, Visual Basic and the Java Platform, amongst others. I also covered scripting in the Java platform, EJB 3.0, NetBeans Platform, and AJAX frameworks including the recently announced Google Web Toolkit.

Technorati Tags: , , , , ,


May 21 2006

Google Web Toolkit Tutorial: The Break Down

There was a lot of buzz at JavaOne regarding the Google Web Toolkit (GWT). Basically, GWT allows a developer to write a AJAX powered web application in Java!! The Java code gets ‘compiled’ to a set of plain old text files containing your JavaScript code. For example, the GWT will translate your rollover actions written in Java to JavaScript functions. This confused me for a second so I’ll stress again that you compile your web application written in Java to plain old JavaScript and HTML that can run in any browser.

What this means is that if you are a Java developer you don’t have to learn JavaScript and all the idiosyncrasies of every browser to develop a stable and reliable AJAX web application.

To get started download the GWT from Google, configure it with Eclipse, and create a new web application.

I created and imported into Eclipse a project called WebApp. In my Package Explorer under webapp > src > com.juixe.gwt I have a public directory that contains my WebApp.html. This file was created by the applicationCreator batch file provided with the GWT. For the purpose of this walk through I modified my WebApp.html as follows:

<HTML>
  <HEAD>
    <TITLE>HTML for WebApp</TITLE>
    <!-- You need this to reference your GWT module -->
    <META name='gwt:module' content='com.juixe.gwt.WebApp'>

    <SCRIPT language="javascript" src="gwt.js">
    </SCRIPT>

    <STYLE></STYLE>
  </HEAD>

  <BODY>
    <H1>My WebApp</H1>
    Any text or HTML goes here.
    <DIV id="changeOnRollOver"></DIV>
  </BODY>
</HTML>

The HTML is simple to describe itself. I have a body that can contain any HTML. I can use CSS style sheets. The only tag that seems out of place it he meta tag.

<meta name='gwt:module' content='com.juixe.gwt.WebApp'>

What I would like to do at this time is write some some GWT based Java code to modify the text inside this DIV identified as changeOnRollOver. To do this I had to modify WebApp.java file under webapp > src > com.juixe.gwt.client. Here is the code for WebApp.java:

/**
 * Entry point classes define onModuleLoad().
 */
public class WebApp implements EntryPoint {

   /**
    * This is the entry point method.
    */
   public void onModuleLoad() {

        // Create Label widget
      final Label roller = new Label(\"Default value\");

        // Associate HTML element to GWT widget
      RootPanel.get(\"changeOnRollOver\").add(roller);

        // Add mouse lister to label widget
      roller.addMouseListener(new MouseListener() {
         public void onMouseEnter(Widget sender) {
            roller.setText(\"Entered element...\");
         }

         public void onMouseLeave(Widget sender) {
            roller.setText(\"Leaving element...\");
         }

         // Do nothing
         public void onMouseDown(Widget sender, int x, int y) {}

         // Do nothing
         public void onMouseMove(Widget sender, int x, int y) {}

         // Do nothing
         public void onMouseUp(Widget sender, int x, int y) {}
      });
   }
}

Let me break this code down. This WebApp class needs to implement the onModuleLoad method of the EntryPoint interface. This is called when you page loads. I think of this method as the equivalent to the JavaScript onload event handler. The first thing I do in the onModuleLoad is create a GWT Label widget called roller. There are a lot of widgets such as labels, buttons, check boxes, tab panels, menu bars, trees, and a whole slough of other widgets. After I instantiated a Label associates the roller Label I just created to my DIV identified as changeOnRollOver in my HTML file. You can associate any GWT widget to any HTML element using code similar to the following:

RootPanel.get(elementNameStr).add(gwtWidgetObject);

The last thing to go over is how to wire functions to widget events. In the above code, I register a MouseListener to it via it’s addMouseListener method. For this example I am not interested in all the mouse listener methods but I still need to implement them. I am only interested in the onMouseEnter and onMouseLeave events. For this events I will just change the text of the roller Label to indicate if I am entering the element or leaving it.

Here is a suggestion to the GWT team: Add a MouseAdapter to the API, please!!!

I can run and debug this code from Eclipse or I could compile it using the WebApp-compile batch file to create the JavaScript and HTML files required to test this in my favorite browser. The WebApp-compile batch file will create a www folder under my webapp project (you might need to refresh you project in Eclipse).

This a somewhat trivial example but if I wanted to do the same thing in notepad using just HTML and JavaScript this is how it would look:

<HTML>
  <HEAD>
    <TITLE>HTML for WebApp</TITLE>
    <STYLE></STYLE>
  </HEAD>

  <BODY>
    <H1>My WebApp</H1>
    Any text or HTML goes here.
    <DIV
      onmouseover=\"this.innerHTML='entered'\"
      onmouseout=\"this.innerHTML = 'left'\">
    &nbsp;
    </DIV>
  </BODY>
</HTML>

May 20 2006

API Design

I attended the How to Write APIs That Will Stand the Test of Time session on the last day of JavaOne 2006. The speakers were from the NetBeans team and they stated that everyone is in the API business. Today a typical application is not build but assembled with a hodgepodge of open source projects, each with its own API. Since these guys are from the NetBeans team they recommended that a application be broken down into modular chunks, a la NetBeans modules or Eclipse Plug-ins. If your application is broken down into modular chunks then each module can have a separate team, life cycle, and/or schedule. This approach require a dependency management and I feel that this advice only works if you application is complex and your development team large.

An API is used to communicate not with the machine but with people, albeit developers. We all know that an API is a contract between the service and the client. The speakers said that an API is more than a contract, it is a promise. As a developer you need to make an API, as a promise, that you can keep.

Here are some quick tips from this session. Do not expose more than you have to. Factory methods gives you more freedom, because you are not tied to a specific implementation. Avoid calling foreign code in critical sections. An API is not just a method signature, it is a contract. Design to last.

Personally, I believe that a good API is one that is not noticed, that is not intrusive, that is self descriptive,that rolls of the tongue, and doesn’t require me to remember anything useless or require me to bend backwards to use.

Technorati Tags: , , ,


May 20 2006

Using UML 2.0

I attended the How to Represent the Architecture of Your Enterprise Application Using UML 2.0 and More session on the last day of JavaOne 2006. According to the speaker UML 2.0 provides “a lot of flexibility which is an euphemism for ambiguity.” A diagram is not enough. The speaker recommended that every diagram have a key. Along with your diagrams with a key add a glossary and acronym list. Record the rationale behind your design decisions including relevant rejected alternatives. It is also useful to gather the requirements and design constraints in these documents. To facilitate design and analysis documents standardize on templates and use them. I myself have written a lot of use case documents and feature specifications and when I use a template I just fill in the gaps in the template.

Technorati Tags: , ,


May 19 2006

Rich Client Platforms

The session Test Driving the Rich Client Platform by Mikael Boman was really informative. I been looking into the Eclipse RCP and have also been reading a lot about the NetBeans Platform. In this session, Mikael discussed the NetBeans Platform, the Eclipse RCP, the Spring RCP, and the alternatives for building a rich client application.

A Rich Client Platform like the Eclipse RCP helps an application developer by proving a proven application UI with most of the plumbing already wired. The Eclipse RCP has a large user base and has been well tested by a myriad of applications. By getting all this for free you, as an application developer, have more time to focus on the business logic. If you think about it, the Eclipse IDE is just a collection of plug-ins. The IBM RAD tool is basically Eclipse with a ton of plug-ins. As a positive, the Eclipse RCP counts on the SWT native UI library and hundreds of available plug-ins. The SWT is also one of the negatives for the Eclipse RCP. SWT is a competing technology to Swing and it is not 100% Java. According to Mikael, you can use Swing but will have some difficulty in some configurations.

According to Mikael, the NetBeans Plaform benefits from being 100% Java. A ton of existing modules already exist which you might be able to reuse in your own application. As for the negative aspects of the NetBeans Platform you can include the lack of documentation and the complexity of the platform.

The Spring RCP provides data binding and validation to the framework. The Spring RCP supports Swing and is feature rich. The problem with Spring RCP is that there is no documentation available for it at this time.. The Spring RCP framework is not mature and at this time if you use it you will have to do a lot of hand coding. Basically Mikael recommends that the Spring RCP is only for the brave.

Mikael’s final conclusion was to “build on what you know.” If you are using Eclipse and are developing SWT then the Eclipse RCP is for you. If you are developing Swing then maybe the NetBeans Platform will be a viable option.

I stopped at the bookstore at JavaOne after this session and noticed that you can get started with the Eclipse RCP with the help of three books. The SWT: The Standard Widget Toolkit, Eclipse: Rich Client Platform, and Eclipse: Building Commercial-Quality Plug-ins. These books are from the Eclipse Series by Addison-Wesley. I didn’t see any book that will help to get started with the NetBeans Platform and that to me speaks volumes.

Technorati Tags: , , , , ,