Monday Jul 28, 2008

TOTD #39: Prototype/ Autcomplete widget with MySQL, GlassFish, NetBeans

There are several JavaScript libraries that can be embedded in your webapplication to create a visually appealing interface. is one of the popular ones and is built on the Prototype JavaScript Framework. The library provides an easy-to-use, cross-browser user interface JavaScripts that allows you to create fancy effects commonly visible on web pages these days.

This blog entry gets you started by using Ajax.Autocompleter that allows for server-powered autocompleting of text fields. Basically, you type a character in a text field and suggestions for possible correct values starting with that character are shown . This is achieved by by sending an Ajax request to the data source on server, passing the typed character in the request and processing the response to display on the web page. This effect was first popularized by Google Suggest.

In this TOTD (Tip Of The Day) we will create a simple web application with a text field in a JSP page that will use Servlet as the data source. The Servlet retrieves the parameter from the RequestContext, uses Java Persistence API to query the database and return response in the expected format. We will use:
Let's get started!
  1. TOTD #38 explains how to create a MySQL Persistence Unit. Please follow the steps there to create a new Web application and Persistence Unit. Follow the steps listed below after the PU is created.
    1. In Project Explorer, expand "Source Packages", "server" and open "States" class. Add the following NamedQuery:

      @NamedQuery(name = "States.findLikeName", query = "SELECT s FROM States s WHERE LOWER( LIKE :searchString"),

      at the position shown below:

    2. In "StatesServlet" class, replace the commented code in "processRequest" with the following fragment:

                  String searchString = request.getParameter("autocomplete_parameter");

                  List<States> list = em.createNamedQuery("States.findLikeName").
                          setParameter("searchString", searchString.toLowerCase() + "%").


                  for (int i = 0; i < list.size(); i++) {
                      States s = list.get(i);
                      out.println("<li>" + s.getName() + "</li>");

      and fix the imports by right-clicking in editor pane and selecting "Fix Imports".
  2. Download & Use libraries
    1. Download latest libraries from here (version 1.8.1 as of this writing) and unzip them.
    2. In NetBeans, right-click on "Web Pages", select "New", "Folder" and specify the folder name as "javascripts".
    3. From the unzipped bundle, copy all files from "src" and "lib" directory to the newly created "javascripts" folder.
    4. Expand "Web Pages" and open "index.jsp". Add the following fragment in HTML <head>:

              <script src="javascripts/prototype.js" type="text/javascript"></script>
              <script src="javascripts/scriptaculous.js?load=effects,controls" type="text/javascript"></script>
              <script type="text/javascript">
                  window.onload = function() {
                      new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "/Autocomplete/StatesServlet", {});

      and the following in HTML <body>:

              <input type="text" id="autocomplete" name="autocomplete_parameter"/>
              <div id="autocomplete_choices" class="autocomplete"></div>

      These fragments are part of the original tutorial.
    5. Optionally, specify a stylesheet to render the result nicely
      1. Create a "stylesheets" folder in "Web pages".
      2. Right -click on the newly created folder, select "New", "Other...", "Other" category and "Cascading Style Sheet" file type. Give the name "autocompleter" and click on "Finish".
      3. Replace the generated template with the following contents:

        .autocomplete {
        .autocomplete ul {
        .autocomplete ul li.selected { background-color: #ffb;}
        .autocomplete ul li {
      4. Add the following fragment in "index.jsp" in <head>:

        <LINK href="stylesheets/autocompleter.css" rel="stylesheet" type="text/css">
Now the show time ... right-click the project and select "Run". This deploys the project on GlassFish v2 and brings up "http://localhost:8080/Autocomplete/index.jsp" in the default browser window. The default page looks like:

As you start typing characters in the text box, Ajax.Autocompleter sends a request to the Servlet (specified using the "/Autocomplete/StatesServlet") by passing the typed characters as query parameters. The servlet returns an unordered HTML list. Typing "A" in the text box shows the following output:

and Firebug output looks like:

Typing "C" in the text box shows the following output:

Typing "Mi" in the text box shows the following output:

A request to the Servlet is made everytime a letter is typed. The minimum number of characters that must be entered in the field before a Servlet request is made can be altered by passing the arguments to Ajax.Autocompleter function as shown below (changes highligted in bold):
            window.onload = function() {
                new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "/Autocomplete/StatesServlet", { minChars: 2 });

Some potential fun ideas to make this entry more meaningful:
  • Servlet can access data from a RESTful endpoint and transform the data to an unordered list
  • Autocompleter data source return data in JSON format
  • Autocompleter used in a HTML <form> and "afterUpdateElement" is used to process the selected entry, may be filter the data shown
Please leave suggestions on other TOTD (Tip Of The Day) that you'd like to see. A complete archive of all tips is available here.

Technorati: totd web2.0 autocompleter scriptaculous prototype javascript glassfish mysql netbeans

Tuesday Jul 22, 2008

FREE Hosting for Facebook & OpenSocial Developers - Social App Program

Are you developing Facebook and/or OpenSocial applications ?

Would you like to deploy them and monetize before spending any money on infrastructure ?

Social App Program is a new collaborative offering from Sun Microsystems and Joyent that allows you to do exactly that! It allows you to leverage Scalability and Cost-effectiveness of Joyent's cloud powered by OpenSolaris on Sun's renowned reliable servers and storage for deploying critical applications. And all this completely FREE for 12 months.

This program is also accompanied with FREE Sun-Joyent Social Developer Days planned for 8 cities (San Francisco, Los Angeles, Seattle, Vancouver, Chicago, Boston, New York and Austin/Dallas) in the US later this year to learn and get hands-on experience on writing applications which can scale to million of users. Learn how to architect, develop and deploy web-scale applications on Cloud infrastructure.

All details are available here. Also read the official press release.

FREE infrastructure with FREE training for YOU to write Facebook/OpenSocial apps - cool!

Is yours a startup company and under-equipped on infrastructure ? Join Startup Essentials today for FREE and discounted enterprise-class software, discounted partner hosting & storage and much more - apply online and membership FREE! Very minimal eligibility requirements and you can join inside the US or outside the US.

Technorati: sun joyent facebook opensocial social web2.0 cloud opensolaris startup startupessentials

Thursday May 29, 2008

Screencast #25: Project SocialSite - Enabling Social Network in your Application

Project SocialSite makes it easy to add social networking features to your existing web applications or community sites (running on Java, PHP or Ruby) and turn it into an OpenSocial container. It comes with a comprehensive and highly scalable implementation of social graph, integrates seamlessly with existing identity and authentication mechanism, make it easy to plug into existing directory server or other user management systems.

This screencast shows how to add social networking features such as Friends, Activities, Profile and an OpenSocial-compliant gadget to your application using NetBeans IDE.

This is a preview of the technology that will soon be released at

Enjoy it here!

Technorati: screencast glassfish socialsite web2.0 netbeans

Thursday May 22, 2008

Redmine on GlassFish - Ruby-on-Rails Project Management Application

is a flexible project management web application written using Ruby on Rails framework. The feature list is pretty comprehensive from the usual suspects like multiple projects, role-based control, forums/wikis/SCM for each project to enterprise level features such as LDAP-authentication and multiple languages. It is cross-platform and cross-database and deploys very nicely on GlassFish v3.

GlassFish v3 modularity and extensibility allows Rails applications to be deployed without any modification (no WARing). This blog explains the steps on how to deploy Redmine on GlassFish and shows some screenshots later. More documentation is available in Redmine Guide.
  1. Check out the most stable release of Redmine by giving the command:

    ~/testbed/redmine >svn co redmine-0.7
  2. Configure the database
    1. Start your MySQL server 

      ~/testbed/redmine >sudo mysqld_safe --user root
      Starting mysqld daemon with databases from /usr/local/mysql/data
    2. Create the database as:

      ~/testbed/redmine/redmine-0.7 >../jruby-1.1.1/bin/jruby -S rake db:create
      (in /Users/arungupta/testbed/redmine/redmine-0.7)
    3. Migrate the database as:

      ~/testbed/redmine/redmine-0.7 >../jruby-1.1.1/bin/jruby -S rake db:migrate
      (in /Users/arungupta/testbed/redmine/redmine-0.7)
      == 1 Setup: migrating =========================================================
      -- create_table("attachments", {:force=>true})
         -> 0.2840s
      -- create_table("auth_sources", {:force=>true})
         -> 0.0540s
      -- create_table("custom_fields", {:force=>true})
         -> 0.0430s
      -- create_table("custom_fields_projects", {:id=>false, :force=>true})
         -> 0.0080s
      -- create_table("custom_fields_trackers", {:id=>false, :force=>true})
         -> 0.0500s

      . . .

      == 90 ChangeVersionsNameLimit: migrating ======================================
      -- change_column(:versions, :name, :string, {:limit=>nil})
         -> 0.0220s
      == 90 ChangeVersionsNameLimit: migrated (0.0220s) =============================

      == 91 ChangeChangesetsRevisionToString: migrating =============================
      -- change_column(:changesets, :revision, :string, {:null=>false})
         -> 0.0210s
      == 91 ChangeChangesetsRevisionToString: migrated (0.0230s) ====================

      == 92 ChangeChangesFromRevisionToString: migrating ============================
      -- change_column(:changes, :from_revision, :string)
         -> 0.0130s
      == 92 ChangeChangesFromRevisionToString: migrated (0.0150s) ===================
  3. Download, Install and Configure GlassFish v3
    1. Download GlassFish v3 from here.
    2. Unzip the downloaded bundle.
    3. Add the following fragment as the last line in "glassfishv3-tp2/glassfish/config/asenv.conf" file:

  4. Deploy Redmine as:

    ~/testbed/redmine >./glassfishv3-tp2/glassfish/bin/asadmin deploy redmine-0.7
    Command deploy executed successfully.

    ... and the GlassFish console shows:

    May 21, 2008 4:58:30 PM com.sun.enterprise.rails.RailsDeployer registerAdapter
    INFO: Loading application redmine-0.7 at /redmine-0.7
    May 21, 2008 4:58:30 PM 
    INFO: Starting Rails instances
    May 21, 2008 4:58:37 PM 
    SEVERE: JRuby limited openssl loaded. gem install jruby-openssl for full support.
    May 21, 2008 4:58:42 PM com.sun.grizzly.jruby.RubyObjectPool$1 run
    INFO: Rails instance instantiation took : 11979ms
    May 21, 2008 4:58:42 PM com.sun.enterprise.v3.deployment.DeployCommand execute
    INFO: Deployment of redmine-0.7 done is 12091 ms
That's it, your application is ready to be used! Here are some screen snapshots from my trial run:

Rails powered by the GlassFish Application Server provides all the good reasons on why you should consider using GlassFish instead of the traditional deployment models for Ruby-on-Rails applications.

This application is also covered in LAB 5539 as part of FREE 20-week Ruby-on-Rails course by Sang "with Passion" Shin.

Technorati: web2.0 rubyonrails jruby ruby glassfish redmine

Wednesday May 21, 2008

Socialsite @ Enterprise 2.0 Conference - Add social networking to your community

Sun Microsytems is a sponsor of Enterprise 2.0 Conference (Jul 9-12, 2008, Boston).

The conference has regular tutorials, keynotes and general sessions, multiple tracks and pavilion (even a free pavilion pass). They also have Launch Pad that allow companies developing new social networking products to compete for the chance to present them in front of the largest audience in the Enterprise 2.0 community.

There are 8 companies in Round 2 and each one of them has submitted a video highlighting their offering. One of the semi-finalists is Project Socialsite - an offering from Sun Microsystems.

Project SocialSite makes it easy to add social networking features to your existing web applications or community sites (running on Java, PHP or Ruby) and turn it into an OpenSocial container. It comes with a comprehensive and highly scalable implementation of social graph, integrates seamlessly with existing identity and authentication mechanism, make it easy to plug into existing directory server or other user management systems.

The submitted video shows how easy it is add social networking features (such as Profile, Friends and Activity) to MediaWiki by adding simple tags. We hope you like the functionality shown and give us a higher rating to help us qualify for finals :)

Follow the conference blog, Facebook group or participate using conference wiki.

Technorati: conf enterprise2.0 socialsite web2.0

Monday May 19, 2008

FREE 20-week Ruby-on-Rails Programming Course - with Passion!

Sang Shin and Brian Leonard are starting a new free online course of "Ruby, JRuby and Rails Application Development (with Passion!)". The course is taken online and will start from Jul 15, 2008.

The objective of this course are "This course will go through briefly the basics of Ruby (and JRuby) programming language first.  The rest of the course will be devoted to learning Rails functionality such as Active Record, Active Controller, and Active View.  Attendees will acquire sufficient knowledge in order to write reasonably sophisticated Rails application upon completion." Read more details here.

In this course, you'll learn various NetBeans and GlassFish tricks for Ruby-on-Rails development and deployment.

Read the Registration FAQ and send a blank email to to register.

This course runs very much like a regular college course in which the students are expected to do weekly homework after studying the learning material and doing the hands-on
lab. By registering with the email address above, students can ask/answer questions. Some quick links ...
It is FREE and can be taken online, so what are you waiting for - register now!

Technorati: rubyonrails jruby ruby glassfish netbeans web2.0

Sunday May 18, 2008

Benefit of using JRuby-on-Rails: Using Java 2D power within Rails

One of the main advantages of using JRuby-on-Rails instead of Ruby-on-Rails is to harness the power of Java libraries available in the Java platform. The Java 2D API is a set of classes for advanced 2D graphics and imaging, and provides extensive support for image compositing and alpha channel images, a set of classes to provide accurate color space definition and conversion, and a rich set of display-oriented imaging operators.

Jennifer published a new blog showing image-filtering effect (negative, grayscale, brigthen, sharpen). Read the complete entry.

A more comprehensive tutorial for JRuby-on-Rails on GlassFish v3 TP2 (also Jennifer's work) is available here.

Technorati: rubyonrails ruby jruby glassfish v3 java2d web2.0

Saturday May 17, 2008

Ask The "JRuby + NetBeans + GlassFish" Experts

NetBeans and GlassFish have changed the landscape of Ruby, JRuby and Rails development and deployment. Code completion, debugging, similar development and deployment environment and many other features (NetBeans, GlassFish) together make it a compelling offering.

Tor Norbye, Brian Leonard and Charles Nutter are fielding questions on Ruby/JRuby/Rails support in the NetBeans IDE and GlassFish in a week-long Ask The Expert session (May 19-23). A complete archive of the Q&A will be available later. You can submit your question here.

If "Ask The Expert" window is missed, the questions can always be asked on, and

Technorati: ruby jruby rubyonrails netbeans glassfish web2.0

Wednesday May 14, 2008

WAR-based Packaging and Deployment of Rails on GlassFish - Goldspike, RailServlet, Warbler, Rack, ...

WAR-based packaging and dispatching of Rails application on Java Application Servers is going through third iteration based what is used for packaging and dispatching:
  • Goldspike + RailsServlet: The first iteration was WAR-packaging of Rails app as defined by Goldspike plugin (nee Rails-integration) and using RailsServlet (part of Goldspike) for dispatching.
  • Warbler + RailsServlet: The second iteration (slightly short lived) overcame the shortcomings of Goldspike (packaging with sane defaults, fast, light-weight, and flexible configuration) by using Warbler for packaging. It decoupled packaging and dispatching by doing only packaging and allowing for pluggable dispatching mechanism. RailsServlet continues to be the default Servlet binding mechanism. This is the version currently supported by GlassFish v2 Update Center.
  • Warbler + Rack:  Nick released JRuby-Rack (JRuby version of Rack, also see Introducing Rack and Docs) last week. And so the third iteration is using Warbler packaging and Rack-based dispatching. JRuby-Rack provides a more seamless connection between the Servlet environment and Rack.

The JRuby-Rack wiki says "JRuby-Rack is a lightweight adapter for the Java servlet environment that allows any Rack-based application to run unmodified in a Java servlet container. JRuby-Rack supports Rails, Merb, as well as any Rack-compatible Ruby web framework.".

This means that, other than Rails, conceptually Merb applications (which also use Rack for deployment) can now also be deployed on GlassFish. This blog entry explains how to deploy a simple Rack-based Rails application.
  1. Install Rails and JRuby-Rack (as part of Warbler) as:

    ~/testbed/jruby-1.1.1 >bin/jruby -S gem install rails warbler --no-ri --no-rdoc
    JRuby limited openssl loaded. gem install jruby-openssl for full support.
    Updating metadata for 289 gems from
    Successfully installed activesupport-2.0.2
    Successfully installed activerecord-2.0.2
    Successfully installed actionpack-2.0.2
    Successfully installed actionmailer-2.0.2
    Successfully installed activeresource-2.0.2
    Successfully installed rails-2.0.2
    Successfully installed warbler-0.9.9
    7 gems installed
  2. Create a template Rails app as:

    ~/testbed/jruby-1.1.1/samples/rails >../../bin/jruby -S rails hello -d mysql
          create  app/controllers
          create  app/helpers
          create  app/models
          create  app/views/layouts
          create  config/environments
          . . .
          create  doc/README_FOR_APP
          create  log/server.log
          create  log/production.log
          create  log/development.log
          create  log/test.log
  3. Disable database access from the application by uncommenting line 21 (remove "#" at the beginning) from "config/environment.rb" as:

       config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
  4. Create a WAR file as:

    ~/testbed/jruby-1.1.1/samples/rails/hello >../../../bin/jruby -S warble
    JRuby limited openssl loaded. gem install jruby-openssl for full support.
    jar cf hello.war -C tmp/war .

  5. A new file "hello.war" is generated in the current directory.
  6. The generated WAR file can be easily deployed on GlassFish.
    1. Download and Install GlassFish v2 UR2 from here.
    2. Start GlassFish Application Server as:

      ~/testbed/glassfish/v2ur2/glassfish >bin/asadmin start-domain --verbose
      Starting Domain domain1, please wait.
      May 13, 2008 11:23:44 AM com.sun.enterprise.admin.servermgmt.launch.ASLauncher buildCommand
      . . .

      [#|2008-05-13T11:34:13.252-0700|INFO|sun-appserver9.1|javax.enterprise.system.container.web|_ThreadID=10;_ThreadName=main;4848;|WEB0712: Starting Sun-Java-System/Application-Server HTTP/1.1 on 4848|#]

      [#|2008-05-13T11:34:13.691-0700|INFO|sun-appserver9.1|javax.enterprise.system.core.selfmanagement|_ThreadID=10;_ThreadName=main;|SMGT0007: Self Management Rules service is enabled|#]

      [#|2008-05-13T11:34:13.718-0700|INFO|sun-appserver9.1|javax.enterprise.system.core|_ThreadID=10;_ThreadName=main;|Application server startup complete.|#]
    3. Deploy the WAR on GlassFish as:

      ~/testbed/jruby-1.1.1/samples/rails/hello >~/testbed/glassfish/v2ur2/glassfish/bin/asadmin deploy hello.war
      Command deploy executed successfully.

      The output in the GlassFish console looks like:

      [#|2008-05-13T11:34:23.330-0700|INFO|sun-appserver9.1||_ThreadID=14;_ThreadName=httpWorkerThread-4848-0;/private/tmp/s1astempdomain1server1547440193/hello.war;|ADM1006:Uploading the file to:[/private/tmp/s1astempdomain1server1547440193/hello.war]|#]

      [#|2008-05-13T11:34:26.019-0700|INFO|sun-appserver9.1||_ThreadID=15;_ThreadName=Thread-30;|deployed with moduleid = hello|#]

      [#|2008-05-13T11:34:30.626-0700|INFO|sun-appserver9.1|javax.enterprise.system.container.web|_ThreadID=16;_ThreadName=httpWorkerThread-4848-1;|PWC1412: WebModule[/hello] ServletContext.log():Info: using runtime pool timeout of 30 seconds|#]

      [#|2008-05-13T11:34:30.626-0700|INFO|sun-appserver9.1|javax.enterprise.system.container.web|_ThreadID=16;_ThreadName=httpWorkerThread-4848-1;|PWC1412: WebModule[/hello] ServletContext.log():Warning: no initial runtimes specified.|#]

      [#|2008-05-13T11:34:30.627-0700|INFO|sun-appserver9.1|javax.enterprise.system.container.web|_ThreadID=16;_ThreadName=httpWorkerThread-4848-1;|PWC1412: WebModule[/hello] ServletContext.log():Warning: no max runtimes specified.|#]
    4. The default Rails page is now visible at "http://localhost:8080/hello" as shown below:

  7. Add some functionality to the application to show Servlet and Rack integration
    1. Add a Controller and View as

      ~/testbed/jruby-1.1.1/samples/rails/hello >../../../bin/jruby script/generate controller home index
      JRuby limited openssl loaded. gem install jruby-openssl for full support.
            exists  app/controllers/
            exists  app/helpers/
            create  app/views/home
            exists  test/functional/
            create  app/controllers/home_controller.rb
            create  test/functional/home_controller_test.rb
            create  app/helpers/home_helper.rb
            create  app/views/home/index.html.erb
    2. Change the "index" helper method in "app/controllers/home_controller.rb" as:

      def index
              @greeting = "Hello from Rack!!"

              # access Servlet Context
              @server_info = $servlet_context.get_server_info
              # alternative way to get Servlet Context
              #@server_info2 = request.env['java.servlet_context'].get_server_info

              # access Servlet Request
              @method = request.env['java.servlet_request'].get_method
              @request_uri = request.env['java.servlet_request'].get_request_uri
              @protocol = request.env['java.servlet_request'].get_protocol
              @port = request.env['java.servlet_request'].get_server_port
    3. Add the following fragment as the last line in "app/views/home/index.html.erb":

      <%= @greeting %><br><br>
      Hosted on "<%= @server_info %>" on port "<%= @port %>"<br>
      <%= @method %> <%= @request_uri %> <%= @protocol %>
  8. Re-create and deploy the WAR file
    1. Re-create the WAR file as explained in step 4.
    2. Re-deploy the WAR file as explained in step 5.3.
    3. Now "http://localhost:8080/hello/home/index" shows the output as:

The magic fragment in "tmp/war/WEB-INF/web.xml" is:



And also "WEB-INF/lib/jruby-rack-0.9.jar" is bundled in the WAR.
Let us know if you try Rack-based deployment of Merb applications on GlassFish.

Technorati: rubyonrails jruby ruby rack merb glassfish web2.0

Sunday May 04, 2008

GlassFish v3 Gem 0.2.0 released

A newer version of GlassFish v3 Gem for Ruby on Rails is now available.

What's new ?
  • Codebase aligned with GlassFish v3 Technology Preview 2
  • Previous version (0.1.2) had some packaging issues which increased the size but now it's back to sweet 2.8 Mb.
Check if previously installed by using the following command:

~/testbed/jruby-1.1.1 >bin/jruby -S gem list glassfish

\*\*\* LOCAL GEMS \*\*\*

glassfish (0.1.2)

If already installed (as indicated by the list of gems) then uinstall it using the following command:

~/testbed/jruby-1.1.1 >bin/jruby -S gem uninstall glassfish
Successfully uninstalled glassfish-0.1.2-universal-java
Remove executables:
        glassfish_rails, asadmin, asadmin.bat

in addition to the gem? [Yn]  y
Removing glassfish_rails
Removing asadmin
Removing asadmin.bat

And then install it again as:

~/testbed/jruby-1.1.1 >bin/jruby -S gem install glassfish
JRuby limited openssl loaded. gem install jruby-openssl for full support.
Successfully installed glassfish-0.2.0-universal-java
1 gem installed

Updating the gem is giving unpredictable results (mostly not updating) and will be investigated later.

Rails powered by the GlassFish Application Server explains why GlassFish is a better deployment option for Rails applications.

All the latest information about the gem can be found at GlassFish JRuby wiki or JRuby wiki.

Please use the gem and send us feedback on GlassFish forums, dev@glassfish or gem mailing list.

Technorati: rubyonrails jruby ruby glassfish v3 gem

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.

Java EE 7 Samples

Stay Connected


« February 2017