Arun Gupta, Miles to go ...

Arun Gupta is a technology enthusiast, a passionate runner, and a community guy who works for Sun Microsystems.
« Previous month (Nov 2007) | Main | Next page of month (Dec 2007) »

http://blogs.sun.com/arungupta/date/20071231 Monday December 31, 2007

Screencast #Web11: Travel Map - Another Real-life app using jMaki & Jersey

In my role of Technology Evangelist, I get the opportunity to meet a lot of community (folks like you :) all around the world. In the year 2007, I represented GlassFish (and related technologies - Metro, jMaki and Jersey) at multiple conferences. This blog introduces a  new real-life application that plots all the places I visited this year on a jMaki-wrapped Google Map widget. Clicking on the marker shows more information about the event such as dates and the blog entry covering the event.

Play the video below to see how the application looks like.

Here is the architecture of this application:

travel map architecture

It consists of a server-side and a client-side applications - developed as NetBeans projects.

  1. Server-side project - A RESTful Web service endpoint that provides resource represenations for all the events attended and associated meta information such as date and blog URLs. This endpoint is created using Jersey.
  2. Client-side project - A jMaki-enabled Web application that consumes the representations generated by the RESTful Web service and plots the information on a jMaki-wrapped Google Map widget.

Both the server-side and client-side are deployed on GlassFish.

This is only a sample application so optimizations are certainly possible and corner cases (such as no blog entry for a particular visit) are not accounted for. But the application still demonstrates the concept. The fully built application looks like as shown below:

Arun's Travel Map 2007

My first presentation in this role was Sun Tech Days Atlanta (highlighted in the image). This application generates an interactive Google Map so feel free to zoom in/out and click 

And one last thing before we build the application. Here is the list of technologies and associated concepts used to build this application:

  1. Jersey
    1. Shows an example of how RESTful Web services can be easily generated from JPA Entity Classes.
    2. Shows how all the resource representations (instead of reference to individual resources) can be returned by a Jersey endpoint.
  2. jMaki
    1. Shows how to consume XML data from an external service (RESTful Web service endpoint) in this case.
    2. Shows how the underlying data model of a widget (Google Map in this case) can be accessed and manipulated.
  3. GlassFish
    1. All the applications are deployed on GlassFish - implicit in the development/deplyment process through seamless integration with NetBeans.
  4. NetBeans 6
    1. Used for generation of RESTful Web services from JPA Entity Classes.
    2. Used for generating/deploying jMaki projects and drag-and-drop of jMaki-wrapped widgets.
  5. JavaScript Closures - to persist the state for asynchronous callback functions
  6. JavaScript DOM processing - to process the XML data received from Jersey endpoint.
  7. Google Maps API
    1. Generate meaningful markers on each location
    2. Populate Google Map from a RESTful Web service endpoint
  8. Java Persistence API - to retrieve data from the database.

And finally, lets build this application. Lets build the RESTful Web service endpoint project first.

  1. Create and Populate the Database
    1. In the NetBeans IDE, go to Services tab, and connect to the database with URL "jdbc:derby://localhost:1527/sample [app on APP]" (right-click and select "Connect...").
    2. Right-click on this database and select "Execute Command..." and create a table by giving the following command:

      create table EVENTS (id int GENERATED ALWAYS AS IDENTITY,
                          event_name varchar(255),
                          dates varchar(20),
                          venue varchar(255),
                          blogs varchar(2056),
                          PRIMARY KEY (id))


      Notice, the "id" column is marked as IDENTITY that instructs the database to auto generate the values for this column and increment by 1 (default) for each row. This column is also marked as the primary key.
    3. Again right-click on the database and select "Execute Command..." to add data to the table by giving the following command:

      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('SunTech Days - Atlanta', 'Jan 16 - Jan 17', 'Cobb Galleria Center, Two Galleria Parkway, Atlanta, Georgia, 30339', 'http://blogs.sun.com/arungupta/entry/wsit_and_web_2_0');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('jMaki Day', ' Feb 23', '4150 Network Circle Santa Clara, CA 95054', 'http://blogs.sun.com/arungupta/entry/sun_internal_jmaki_day_review');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Ajax World - New York', 'Mar 19 - Mar 21', 'The Roosevelt Hotel, 45 E 45th St, New York, NY 10017', 'http://blogs.sun.com/arungupta/entry/sun_ajax_world');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('The Server Side Java Symposium - Las Vegas', 'Mar 22', '3355 Las Vegas Blvd. South Las Vegas, NV 89109', 'http://blogs.sun.com/arungupta/entry/sun_the_server_side_java, http://blogs.sun.com/arungupta/entry/tango_at_venetian_las_vegas');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('JavaOne - San Francisco', 'May 7 - May 11', 'Moscone Center, 747 Howard Street, San Francisco, CA 94103', 'http://blogs.sun.com/arungupta/entry/slides_for_ts_4865, http://blogs.sun.com/arungupta/entry/javaone_2007_day_1_finished, http://blogs.sun.com/arungupta/entry/javaone_2007_day_1, http://blogs.sun.com/arungupta/entry/javascript_everywhere_javaone_2007_demo, http://blogs.sun.com/arungupta/entry/excel_using_wsit_javaone_2007, http://blogs.sun.com/arungupta/entry/ts_4865_takes_two_to, http://blogs.sun.com/arungupta/entry/communityone_glassfish_day_report, http://blogs.sun.com/arungupta/entry/javaone_2007_backstage, http://blogs.sun.com/arungupta/entry/javaone_2007_is_almost_here, http://blogs.sun.com/arungupta/entry/my_javaone_2007_picks');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Rails Conf - Portland', 'May 17 - May 20', '777 NE MLK, Jr. Blvd. Portland, OR 97232', 'http://blogs.sun.com/arungupta/entry/tim_bray_s_keynote_session, http://blogs.sun.com/arungupta/entry/sun_rails_conf_2007_keep, http://blogs.sun.com/arungupta/entry/getting_started_with_jruby_tutorial, http://blogs.sun.com/arungupta/entry/jmaki_netbeans_and_glassfish_in');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Google Developer Day - San Jose', 'May 31', '150 W San Carlos St San Jose, CA 95113', 'http://blogs.sun.com/arungupta/entry/google_developer_day_report');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Mashup Camp - Mountain View', 'Jul 18 - Jul 19', 'Computer History Museum, 1401 N Shoreline Blvd., Mountain View, CA 94043', 'http://blogs.sun.com/arungupta/entry/jmaki_at_mashup_camp_report, http://blogs.sun.com/arungupta/entry/jmaki_mashup_camp');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('OSCON - Portland', 'Jul 23 - Jul 27', '777 NE MLK, Jr. Blvd. Portland, OR 97232', 'http://blogs.sun.com/arungupta/entry/jmaki_oscon');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('JRuby Hack Day - San Francisco', 'Aug 8', '1201 8th St, San Francisco, CA 94107', 'http://blogs.sun.com/arungupta/entry/jruby_on_rails_hackday_report, http://blogs.sun.com/arungupta/entry/learn_jruby_on_rails_free');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Rich Web Experience - San Jose', 'Sep 6 - Sep 8', '170 S Market St, San Jose, CA 95113', 'http://blogs.sun.com/arungupta/entry/the_rich_web_experience_2007, http://blogs.sun.com/arungupta/entry/jmaki_javafx_the_rich_web');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Rails Conf Europe - Berlin', 'Sep 17 - Sep 19', 'Maritim Pro Arte, Friedrichstrasse 151, 10117 Berlin', 'http://blogs.sun.com/arungupta/entry/rails_conf_europe_2007_day2, http://blogs.sun.com/arungupta/entry/rails_conf_europe_2007_day1, http://blogs.sun.com/arungupta/entry/rails_conf_europe_2007_day, http://blogs.sun.com/arungupta/entry/jmaki_netbeans_and_glassfish_in1');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Sun Tech Days - Rome', 'Sep 24 - Sep 25', 'Meliá Roma Aurelia Antica, Vía Aldobrandeschi, 223  Rome ITALY  00163', 'http://blogs.sun.com/arungupta/entry/netbeans_day_rome_2007, http://blogs.sun.com/arungupta/entry/travel_tips_to_rome, http://blogs.sun.com/arungupta/entry/glassfish_metro_jersey_and_jmaki');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Sun Tech Days - Milan', 'Sep 26 - Sep 28', 'ATA Hotel Quark - Via Lampedusa 11/a 20141 Milano, Italia', 'http://blogs.sun.com/arungupta/entry/glassfish_day_milan_2007');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Mid West Java Tech Days - Minneapolis', 'Oct 16', 'University of St Thomas, MPL 201, 1000 LaSalle Avenue, Minneapolis, MN 55403-2005', 'http://blogs.sun.com/arungupta/entry/mid_west_java_tech_days, http://blogs.sun.com/arungupta/entry/metro_and_jmaki_in_minneapolis');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Mid West Java Tech Days - Chicago', 'Oct 18', 'Donald E Stephens Convention Center, 9301, W Bryn Mawr Ave, Rosemont IL 60018', 'http://blogs.sun.com/arungupta/entry/mid_west_java_tech_days1, http://blogs.sun.com/arungupta/entry/crowne_plaza_chicago_o_hare, http://blogs.sun.com/arungupta/entry/metro_and_jmaki_in_minneapolis');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Silicon Valley Code Camp - Los Altos', 'Oct 27', 'Foothill College, Los Altos, CA', 'http://blogs.sun.com/arungupta/entry/silicon_valley_code_camp_trip, http://blogs.sun.com/arungupta/entry/metro_jmaki_silicon_valley_code');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Sun Tech Days - Beijing', 'Nov 1 - Nov 3', 'Beijing International Convention Center, No.8 Beichendong Road Chaoyang District, Beijing', 'http://blogs.sun.com/arungupta/entry/glassfish_day_beijing_2007_by, http://blogs.sun.com/arungupta/entry/wangfujing_street_authentic_china_in, http://blogs.sun.com/arungupta/entry/sun_tech_days_beijing_talent, http://blogs.sun.com/arungupta/entry/sun_tech_days_beijing_day, http://blogs.sun.com/arungupta/entry/travel_tips_to_beijing, http://blogs.sun.com/arungupta/entry/glassfish_day_beijing');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Partner Preso - Toronto', 'Nov 21', 'Toronto City Center', 'http://blogs.sun.com/arungupta/entry/metro_jmaki_jruby_glassfish_q');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Partner Preso - Montreal', 'Nov 21', 'Montreal City Center', 'http://blogs.sun.com/arungupta/entry/metro_jmaki_jruby_glassfish_q');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('GlassFish - Delhi University', 'Dec 3', 'New Delhi', 'http://blogs.sun.com/arungupta/entry/glassfish_delhi_university');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('FOSS.IN - Bangalore', 'Dec 4', 'India Institute of Science, Bangalore', 'http://blogs.sun.com/arungupta/entry/packaging_java_apps_for_ubuntu, http://blogs.sun.com/arungupta/entry/foss_in_schedules_now_available, http://blogs.sun.com/arungupta/entry/glassfish_foss_in_2007');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Partner Preso - Bangalore', 'Dec 4', 'Bangalore', 'http://blogs.sun.com/arungupta/entry/glassfish_bangalore_chennai_and_pune');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Partner Preso - Chennai', 'Dec 5', 'Chennai', 'http://blogs.sun.com/arungupta/entry/glassfish_bangalore_chennai_and_pune');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Partner Preso - Pune', 'Dec 6', 'Pune', 'http://blogs.sun.com/arungupta/entry/glassfish_bangalore_chennai_and_pune');
      INSERT INTO EVENTS (event_name, dates, venue, blogs) VALUES('Partner Preso - San Francisco', 'Dec 17', 'San Francisco', 'http://blogs.sun.com/arungupta/');

      These SQL statements populate the database with details about my visits in 2007. If you'd like to develop a similar application highlighting your visits then you'll need to modify the VALUES clause to match accordingly.
  2. Create and Configure RESTful Web service endpoint
    1. Create a Persistence Unit as described in "Generating Entity Classes from Database" section in Getting Started with RESTful Web Services. Lets say the project name is "WebApplication3", package name is "events" and the table name to generate Entity classes is EVENTS. Take everything else as the defaults.
    2. Generate a RESTful Web service as described in "Generating RESTful Web Services from Entity Classes" section in Getting Started with RESTful Web Services.
      1. Add a new class EventsList in the events package as:

        @javax.xml.bind.annotation.XmlRootElement
        public class EventsList {
          @javax.xml.bind.annotation.XmlElement
          protected java.util.List<Events> events;

          public EventsList() {
            if (events == null)
              events = new java.util.ArrayList<Events>();
          }

          public void add(Events name) {
            events.add(name);
          }

          public java.util.List<Events> getValue() {
            return events;
          }
        }
      2. In service.EventsResource, change the method associated with GET to:

        public EventsList get() {
                EventsList eventsList = new EventsList();
                List<Events> list  = PersistenceService.getInstance().createQuery("SELECT e FROM Events e").getResultList();
                for (Events e : list) {
                    eventsList.add(e);
                }
                return eventsList;
        }

        This will ensure that all the resource representations are returned instead of a reference to the resource. Make sure to fix the imports.
That's it, our server-side project is now ready. "http://localhost:8080/WebApplication3/resources/events" now return a complete RESTful representation of all the rows from the database table EVENTS.

Lets build the client-side application next. Make sure jMaki plug-in in NetBeans IDE is already installed.
  1. In the NetBeans IDE, create a new Web project, enable "Ajax Framework" and choose the "Standard" layout for "index.jsp".  Lets say the project name is "WebApplication4".
  2. Drag-and-drop a jMaki-wrapped Google Map widget in the 'Main Content Area' and jMaki-wrapped Yahoo Button in the 'Sidebar Content Here'.
  3. Customise the widgets
    1. Add id="mymap" attribute to the Google Map widget. The updated widget looks like as shown below:

      <a:widget  name="google.map" id="mymap"
               args="{ centerLat : 37.4041960114344,
                       centerLon : -122.008194923401 }" />

      id="mymap"
      will allow the Map widget to be accessed by name later.
    2. Add args="{label:'Plot Events'}" attribute to thes Yahoo button widget. The updated widget looks like as shown below:

      <a:widget name="yahoo.button" args="{label:'Plot Events'}"/>
  4. In glue,js, add the following code to *onClick subscribe method:

    var url = jmaki.xhp + "?id=events";
    var _map = jmaki.getWidget("mymap").map;
    _map.setZoom(2);
    _map.clearOverlays();
    _map.enableInfoWindow();
       
    jmaki.doAjax({method: "GET",
        url: url,
        callback: function(_req) {          
            var xmlobject = (new DOMParser()).parseFromString(_req.responseText, "text/xml");
            var root = xmlobject.getElementsByTagName('eventsList')[0];
            var events = root.getElementsByTagName('events');
            for (var i = 0 ; i < events.length ; i++) {
                var event = events[i];
                var eventName = event.getElementsByTagName('eventName')[0].firstChild.nodeValue;
                var venue = event.getElementsByTagName('venue')[0].firstChild.nodeValue;
                var blogs = event.getElementsByTagName('blogs')[0].firstChild.nodeValue;
                var dates = event.getElementsByTagName('dates')[0].firstChild.nodeValue;
               
    var id = event.getElementsByTagName('id')[0].firstChild.nodeValue;
                   
                var encodedLocation = encodeURIComponent("location=" + venue);
                var url = jmaki.xhp + "?id=yahoogeocoder&urlparams=" + encodedLocation;
                jmaki.myHandler(url, eventName, blogs, dates, id, _map);
            }
        }
    });
  5. Add the following functions above the *onClick subscribe method:

    // "Function closure" used from http://econym.googlepages.com/basic1.htm
    // Creates local copy of "marker" and "html" variables to be preserved for later use
    function createMarker(point,html) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(html);
        });
        return marker;
    };

    // Function closure that preserves "eventName", "blogs", "dates and "id"
    // Gets the latitude/longitude from Yahoo Geocoding service and plots them on the map
    // Also creates meaningful markers
    jmaki.myHandler = function(_url, eventName, blogs, dates, id, _map) {
        jmaki.doAjax({url: _url,
            callback : function(req) {
                if (req.responseText.length > 0) {
                    jmaki.log("name: " + eventName);
                    var response = eval("(" + req.responseText + ")");
                    var coordinates = response.coordinates;
                    jmaki.publish("/jmaki/plotmap", coordinates);
                    jmaki.log("plotting " + eventName);
                    var latlng = new GLatLng(coordinates[0].latitude, coordinates[0].longitude);
                   
                    var blogHtml = "";
                    b = blogs.split(', ');
                    for (i=0; i<b.length; i++) {
                        blogHtml += '<a href="' + b[i] + '">' + (i+1) + '</a>';
                        if (i<b.length-1)
                            blogHtml += ", ";
                    }
                   
                    var txt = '<table>' +
                    '<tr><td>#' + id + ": " + eventName + '</td></tr>' +
                    '<tr>Dates: ' + dates + ', 2007</td></tr>' +
                    '<tr><td>Blogs: ' + blogHtml + '</td></tr>' +
                    '</table>';
                   
                    var marker = createMarker(latlng, txt);
                    _map.addOverlay(marker);
                    marker.openInfoWindowHtml(txt);
                } else {
                    jmaki.log("Failed to get coordinates for " + location );
                }
            }
        });   
    };
  6. Add the following entry in Web Pages, resources, xhp.json:

    ,
    {"id": "events",
     "url":"http://localhost:8080/WebApplication3/resources/events/"
    }


    assuming WebApplication3 is the project where RESTful Web service endpoint is hosted.
That completes our client-side web application as well. Now, either hit F6 (default key to Run the NetBeans project) and this will show http://localhost:8080/WebApplication4/index.jsp in the configured browser. Once you click on "Plot Events" button, all the markers on the Google Map are plotted.
Future Improvements
  1. If Jersey can return all the resource representations directly, then the workaround used above may not be required.
  2. Use e4x after <script type="text/javascript"> in index.jsp can be generated as <script type="text/javascript; e4x=1">.
  3. Build the client-side application using Rails once issue #309 & #310 are resolved.
    1. Once deployed as Rails application on WEBrick, create a WAR file and deploy on GlassFish.
    2. Try this application using GlassFish v3 gem.
  4. Embed Google Map in the blog entry.
An alternate title of this blog entry could've been "How I spent my winter break ?". But in order to keep the title inline with rest of other entries (keeping it simple and reflecting the content of the entry) I decided to use the existing title ;-)

Technorati: screencast conf jmaki jersey netbeans glassfish jpa javascript googlemaps restful web2.0 jmakimashups

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071226 Wednesday December 26, 2007

OSX #5: Alt-Tabbing in Mac (Switching between windows on Mac)

Alt-Tabbing in Windows shows currently open windows and allows to select one of them which then becomes the active window. If there are 3 Firefox windows, then it'll show 3 icons. A slightly different behavior is available in Mac where it shows one icon for all the open windows of an application and then provide a different keyboard shortcut to switch between all the windows of that application.

Switch between different applications: Command+Tab (for example if you have Firefox, Thunderbird and other applications). Shift+Command+Tab moves in the reverse direction.
Switch between different windows of the same application: Command+~ (for example if you have multiple windows of Firefox). Shift+Command+~ moves in the reverse direction.

However if the application is minimized then it is not activated (which is bizarre)!

If you are holding the command key and hit Q then that particular application will quit, if you hit H then that application will hide (go behind all the applications?).

A complete archive of all Mac OS X tips are available here.

Technorati: mac osxtips

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071225 Tuesday December 25, 2007

Santa's Goodie Bag for Developers

Merry Christmas!

And guess what, Santa has been delivering gifts through out December:

Have you not tried any of these ?

And of course, you can get nightly builds for each of these technologies :)

Technorati: glassfish netbeans jruby ruby metro grizzly jaxb jmaki

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071224 Monday December 24, 2007

OSX #4: How to forcibly kill an application on Mac ?

The Task Manager in Microsoft Windows is multipurpose. However the most common use, IMHO, is to kill a misbehaving application or that is "Not Responding".  This is called as "Force Quit" on Mac and can be achieved by calling Command+Option+Esc which brings up a window like:

Force Quit window

Then you select the application that you would like to shutdown and click on "Force Quit" button. As in Windows, you will loose any unsaved data.

A complete archive of all Mac OS X tips are available here.

Technorati: mac osxtips

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071223 Sunday December 23, 2007

OSX #3: How to eject CD/DVD in Mac ?

  1. If there is a CD in your drive, then there will be an icon on your desktop as shown below:

    Mac CD Icon
  2. Go to "File" menu in the menu bar and click "Eject <DISK LABEL>" as shown below:

    Mac CD Eject

    Alternatively you can press Command+E in that window.

A complete archive of all Mac OS X tips are available here.

Technorati: mac osxtips

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071222 Saturday December 22, 2007

Metro 1.0.1 and 1.1 are now available

Metro 1.0.1 (integrated in GlassFish v2 UR1) ad Metro 1.1 are now released. Metro contain stable releases of JAX-WS RI and WSIT. Read Vivek's blog for more details.

Even though Metro 1.1 is a stand-alone release, it can be easily installed on an existing GlassFish instance (for example override on v2ur1). A later release of Metro 1.1 will be integrated in GlassFish v2.1. Metro Roadmap provides all the details.

Please send us your feedback on users@metro or Forum. A pleasant change that happened earlier today was that cross-posting was enabled between user's list and forum. So all the questions posted on user's list are cross-posted to Forum and vice versa. This enables wider audience for your questions and more engineers to respond back :)

Technorati: webservices metro jax-ws wsit glassfish v2ur1

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071221 Friday December 21, 2007

JRuby 1.0.3 + Rails 2.0 Hello World - Additional Steps Required


JRuby 1.0.3
was recently released and so was Rails 2.0. I decided to try JRuby 1.0.3 + Rails 2.0 and realized that a few additional steps (because of Rails 2.0) are required to get a trivial Hello World applcation up and running. Here are the steps:

  1. Unzip JRuby 1.0.3.
    1. Make sure to set JAVA_HOME and JRUBY_HOME.
    2. Also include JAVA_HOME/bin and JRUBY_HOME/bin in PATH for convenience.
  2. Install Rails 2.0 as shown below:

    ~/samples/jruby arungupta$ jruby -S gem install rails --include-dependencies --no-ri --no-rdoc
    Bulk updating Gem source index for: http://gems.rubyforge.org
    Successfully installed rails-2.0.2
    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
  3. Create a simple app using the following steps
    1. Create a template app as:

      jruby -S rails --database mysql hello or jruby -S rails -d mysql hello

      It's important to specify --database mysql otherwise Rails 2.0 uses sqlite3 as the default database.
    2. Add a Controller and View as:

      cd hello
      jruby script/generate controller say hello
    3. Edit the controller as:

      vi app/controllers/say_controller.rb

      and add the following variable in "hello" helper method:

      @hello_string = ""
    4. Edit the View as:

      vi app/views/say/hello.html.erb

      and add the following as last line:

      <%= @hello_string %>


      Notice, the view extension is .html.erb instead of .rhtml.
  4. Download, Install and Configure MySQL (additional step for Rails 2.0)
    1. Mac OS comes pre-installed with MySQL in /usr/local/mysql directory. Start the server as:

      sudo ./bin/mysqld_safe

      Alternatively, you can download and install MySQL Universal server (only .dmg format, not tar.gz format as specified here).
    2. Create a database as:

      sudo ./bin/mysqladmin create hello_development
  5. Start the WEBrick server (in hello directory) as:

    jruby script/server
That's it, now your trivial Hello World application is deployed using JRuby 1.0.3 + Rails 2.0 and displays the output in a browser window as:

JRuby 1.0.3 + Rails 2.0 Hello World

Want to try this application on GlassFish v3 gem (download or build your own - now down to 2.4 MB) ?

Technorati: ruby jruby rails mysql glassfish v3 gem

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

OSX #2: How to capture screen on Mac ?

  1. Capture a portion of the screen: Press Command+Shift+4 and the pointer turns into a bull's eye. Select area of the screen that you wish to capture. That part of the screen is captured and saved as PNG file on your Desktop "Picture 1.png" as shown below:

    Screenshot Capture Image
  2. Capture the entire screen: Command+Shift+3 captures the entire screen.
  3. Capture a highlighted window: Command+Shift+4, Space, (cursor turns into a camera), Click in the highlighted window.
Now Control+Command+Shift+ 3 or 4 will copy the captured image in Clipboard memory instead of creating a file on the Desktop. All of these keyboard shortcuts can be easly customized by going to Preferences -> Keyboard & Mouse -> Keyboard Shortcuts as shown below:

screen capture default keyboard shortcuts

A complete archive of all Mac OS X tips on this blog are available here.

Technorati: mac osxtips

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071220 Thursday December 20, 2007

OSX #1: Getting Started with a Mac for a Windows User

MacBook Image I got a new Apple MacBook Pro (Intel Core 2 Duo, 2GB RAM, 160 GB HDD and other good stuff) and excited about that! However I've been a Windows user all along and this is my first interaction with a Mac.

So here are some basic tips/tools to get you started if you are in the same situation:

  • Start with Mac101 - This will get you familiar with Mac, basic terminology, some keyboard hints and other misc stuff.
  • Keyboard mappings between a Windows and Mac keyboard are very different. It would help to print out the mappings and keep them handy. It can take more than a day to get used to the new mappings. Some specific ones are:
    • "Right-click"ing is not intuitive - Enable Two-Finger Click on the Trackpad
    • No Forward Delete key, Mac equivalent is Fn + Delete
    • No dedicated Home, Page Up or Page Down keys, Instead use Fn + Cursor keys
  • Install the following tools
Also read 10 tips for Mac users switching from Windows and a more comprehensive list at Switch to The Mac.

The box came installed with Tiger (Mac OSX 10.4) as opposed to Leopard (Mac OS X 10.5). Leopard Updates are available for $9.95 until Jan 4th, 2007.

Some other striking difference in the terms of UI are:

  • The menus, instead of stacked to each window, are always available at the top.
  • "Windows Control Panel" is available as "System Preferences" on Dock (the toolbar which is, by default, at the bottom of the screen).
  • Minimize/Maximize/Close buttons are to the left instead of to the right.
  • Maximize button only maximizes to the required extent instead of occupying the entire desktop.
  • Important keyboard shortcuts
    • F9 - Shows all open windows
    • F10 - Shows all open windows for the current application (every thing else is greyed out)
    • F11 - Hides all windows and shows the Desktop
    • F12 - Show Dashboard

Here are some other tasks that I tried:

  • iMovie is really cool, I could easily create a movie (with in-built camera) and upload a video directly to youtube. Really good intuitive interface.
  • Create clean HTML pages (like this blog): TextEdit (the default editor) adds redundant markers and viewing HTML source code is not intuitive/easy. So does NeoOffice. Microsoft Front Page is really good at that and I've thoroughly enjoyed editing my blogs using it. So I'm looking for something comparable on Mac. I found this HTML editor shootout  but most of the editors seem to require some manual addition of HTML tags. Googling further, I found KompoZer (based on Nvu) and liking it so far. Part of the reason is that the look-and-feel is quite like FrontPage ;-)

These tips will at least get you started where you can check Email, IM and Web, view your documents, import key settings from Firefox/Thunderbird and unleash the potential of GlassFish and NetBeans. Lots of other tips are available here, here and here. I'll post more as I learn them. Feel free to post your favorite tool/tip/guidance here.

A complete archive will be available here.

Technorati: windows mac apple tools osxtips

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071219 Wednesday December 19, 2007

GlassFish v2 UR1 now available

GlassFish v2 UR1 Download Button

GlassFish v2 UR1 was released earlier today (v2ur1-b09d). This is targeted to accommodate high priority bugfixes (188 of them)! Read the official announcement.

What's new ?

Download Page
Sun branded App server
Buy Support (learn more about it in a short screencast by Anissa and how it is integrated in Admin Console).

This is also integrated in Java EE SDK Update 4 Release.

If you have been using GlassFish v2, then you "must" consider moving to this release as it is certainly better quality and Cluster and Developer profiles are also supported on AIX 5.2 & 5.3 (in addition to existing list of Solaris Sparc, Solarix x86, Windows, Linux and MacOS).

Technorati: glassfish v2ur1

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071217 Monday December 17, 2007

JRuby-on-GlassFish Update Center Module - Now Updated with JRuby 1.0.2

Pramod updated the JRuby-on-GlassFish module on the GlassFish Update Center with JRuby 1.0.2, Rails 1.2.6 and Goldspike revision 808.

I created a standalone (self-contained with all the libraries, gems & plug-ins) and shared (contains only web.xml and libraries are loaded from the Application Server instance) WAR image for the bundled Hello World sample. The screencast #web9 provide detail instructions on how to create standalone and shared images. The difference in the image size is pretty significant:

Shared Image 226, 977 bytes
Standalone Image 11,039,883 bytes (48 x)

If you have multiple such applications and each application has one or more plug-ins then this size grows up pretty fast. The war:shared:create rake target in Goldspike is buggy and serves the same purpose as war:standalone:create (#13265).

Loading shared libraries from GlassFish Application Server instance to keep your Rails application size to a minimum is another reason to consider using GlassFish for deploying your JRuby-on-Rails application.

Technorati: glassfish ruby jruby rails goldspike

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071214 Friday December 14, 2007

GlassFish @ Delhi University

I presented on GlassFish and related technologies (Metro, JRuby-on-GlassFish and jMaki) at the Department of Computer Science, Delhi University last week. The slides are available here.

The talk was very well attended with approximately 120 students and 4 faculty members. The students were pretty excited and had great a interactive session.

 

Being an alumni of the school (many years ago ;), it was great seeing the new building of the department, meeting the faculty and interacting with the students. I reached there an hour earlier so that I can mingle with the staff and students and it was a lot of fun.

The department faculty proposed to use GlassFish instead of Tomcat for their next semester assignment. I believe this is a great move as it will allow the students to understand the simplicity and power of a great open-source and Java EE 5 compliant Application server.

I initiated the process of recruiting a Campus Ambassador from Delhi University and this will help establish a better relationship between this University and Sun Microsystems.

Here are the questions and answers that were asked during the session:

  1. Amongst the different Java training courses, how do I decide which one to pick ?

    Sun Learning defines several Learning Paths for different Java technologies (EE, SE, ME, Web Services and Web 2.0). Pick an appropriate learning path depending upon your interest. In addition, Sun Training Catalogue (click on your country) shows different events conducted by Sun Learning in the local geogrpahy.
  2. How does Sun make money with GlassFish being open sourced ?

    That's true, GlassFish is 100% open-source and totally free to use. The business model for Sun is that of selling support and services:
  3. What are the dis-advantages of GlassFish ?

    GlassFish provides an open source, production-quality and Java EE 5 compatible application server. It has world class performance ([1], [2]), .NET interoperable Web services stack, out-of-the-box clustering, load balancing and high availability support. However instead of identifying dis-advantages, here are some areas for improvement:
     
    • Feature-wise: The footprint for GlassFish v2 is higher than some non-full JavaEE containers (like Tomcat). This problem will disappear with GlassFish v3 which is small (< 100 kb), fast (starts up < 1 sec) and modular (load only required containers).
    • Ecosystem-wise
      • Community is not as well developed as Tomcat or JBoss because we have not been around as long. However the adoption is continuously increasing.
      • We are not yet as transparent as Tomcat, but we are more transparent than anybody else (including JBoss). Transparency will continue to improve in the future.
      • Our governance is still in transition.
  4. Any comparison between NetBeans and Eclipse ?

    Why NetBeans ? explains the top reasons to use the NetBeans IDE. Some specific points are:
    • Consistent UI across all platforms where as Eclipse runs best on Windows
    • A friendlier environment for people who are new with links to sample apps and docs accessible from within the IDE.
    • An easy to use website with tons of quality docs and screencasts.

    Here are couple of more links that provide a comparison between the IDEs:

  5. What are the main features of Ruby as compared to Java ?

    A comparison of Ruby and Java is explained in this blog.
  6. Why Ruby when there are many other languages ?
    • Ruby is getting popular due to Rails.
    • Ruby-on-Rails very popular among web developers.
    • JRuby is a pretty mature implementation of Ruby in Java, running on JVM and able to use existing Java libraries.
    • Complete deployment story on Solaris -- customer can chose native RoR or JRuby on Rails on GlassFish.
  7. What is the difference between Tomcat and GlassFish ?

    Tomcat is a Servlet container that can host JSP and Servlets. GlassFish is a Java EE 5 compliant application server that includes implementation for a Web services stack (Metro), EJBs, Java Persistence and many others incuded in the Java EE 5 specification. In addition to this, GlassFish also provides out-of-the-box clustering, high availability and load balancing capabilities that are required for enterprise applications. Read more about Why use GlassFish ?
  8. What does Sun offer to students ?

    The offerings are described in detail here.
  9. What is java.net ?

    java.net is a premier web-based, open community created to facilitate Java™ technology collaboration in applied areas of technology and industry solutions. java.net is a central gathering place for Java technology enthusiasts and existing communities across industries, platforms, and interest groups. Read more about java.net in the FAQ.
  10. How do I create a brand new jMaki widget ?

    This is explained in TOTD #20.
  11. What are the main differences between GPL and CDDL ?

    A detailed difference between EULA, GPL, CDDL and BSD in terms of copyright and patent rights is explained here.
  12. What are the different options of doing a collaborative research in association with Sun Microsystems ?

    The Collaborative Research program is explained here.
  13. What is the difference between GlassFish v2 and Sun Java System Application Server 9.1 ?

    There are three key differences:

    The detailed differences are highlighted here.

  14. What are the different ways GlassFish can be configured in NetBeans ?

    Two ways:
    • If you download a full version of NetBeans IDE then GlassFish comes pre-bundled and is installed for you.
    • You can configure an existing GlassFish installation on your machine in the Services tab. If the Services tab is not visible, then select "Windows" menu item and then "Services". Right-click on "Servers", select "Add Server...", select "GlassFish V2" in the "Choose Server" dialog box. Click on "Next" and follow the instructions.

The complete album is here:

Technorati: conf glassfish webservices metro ruby jruby jmaki web2.0 delhiuniversity delhi netbeans q&a

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071213 Thursday December 13, 2007

Screencast #WS8: Tango with NetBeans 6

David Coldrick recorded a screencast for Australian Developer Days. The demo shows how NetBeans 6 allow Web services to be easily created and deployed on GlassFish.

It is similar to screencast #ws7 but good to see somebody else creating these videos :)

Technorati: screencast glassfish webservices metro tango netbeans

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

GlassFish @ Bangalore, Chennai and Pune - Metro, jMaki & JRuby

I presented on GlassFish and other related technologies (Metro, jMaki and JRuby) in Bangalore, Chennai and Pune last week. The slides used during the preso are here. And here is the list of questions (along with answers) for you:

  1. What does WSIT offer ?

    WSIT stands for Web Services Interoperability Technology. It is a component of Metro - the Web services stack in GlassFish. WSIT specifically provides support for Security, Reliability, Transactions and interoperability with .NET 3.0. A number of screencasts are available to get you started with Metro and enable all the enterprise features mentioned using NetBeans IDE.
  2. Is Metro plugin available for NetBeans version < 6.0 ?

    Yes, Metro plugin is available for NetBeans 5.5.1. This is clearly explained in screencast #ws4. NetBeans 6.0 is now released and is the recommended version of the IDE.

  3. How do I use LDAP for authentication while using Metro based web service (with Security Token Service) interoperating with .NET web service?

    Security Token Service (STS) can be configured for LDAP authentication. STS service end can be protected with Sun Java System Access Manager web service agent (JSR 196 plugin). It can validate and authenticate the incoming user name token (username / password) against configured LDAP store at STS service side (when Access Manager is hosted as STS) and then issue the corresponding SAML token. You could also write AuthenticationValidator plugin to STS service, that can access and validate incoming username / password against Access Manager LDAP store using Access Manager Client SDK.
  4. Do Metro support Kerberos?

    Metro 1.0 does not support Kerberos. However the latest nightly builds of Metro provide Kerberos support.
  5. I want to contribute to GlassFish. Which areas can I contribute?

    Yes, GlassFish is 100% open source and encourage committers. Some of the ideas are available here. Please feel free to suggest any contributions at dev@glassfish.dev.java.net.
  6. What Ruby features are getting into Java language?

    If Java closures proposal is accepted then that will be a Ruby feature.
  7. Does jMaki take care of browsing history ?

    jMaki does not support browser history yet but this feature will be made available as an extension in the near future.
  8. Is jMaki extensible ?

    Yes, read how jMaki framework can be extended as explained here.
  9. What is the performance impact of using jMaki ?

    jMaki.js is the initialization script (18kb) for jMaki that is loaded when the web application is loaded. This script provides multiple features, included but not limited to:
    • support for common event model between widgets from multiple toolkits (using publish/subscribe)
    • Dynamic Container at component level - allows to resize the component within <div> and iframe
    • doAjax call (allows to asynchronously invoke services from back end)
    • JSON.serialize (serializes JavaScript objects to JSON)
    • inspect (2-level deep inspection of object)
    • logger & debugging (log all publish/subscribe events and other messages to enable debugging)
    • namespace API  (allows to namespace all the widgets for clean separation)

    The jMaki wrapper is a minimal code that needs to be written anyway to invoke the code anyway so there is no additional overhead there.

  10. Is Comet supported in GlassFish/jMaki?

    Yes, read about Comet support in GlassFish The Grizzly Comet and Writing a Comet application using GlassFish. Also try a simple sample that demonstrates how jMaki and Comet (read the explanation) work nicely with each other.

  11. Can GlassFish deploy EJB 2.0 apps ?

    GlassFish is Java EE 5 compliant which maintains backwards compatibility with J2EE 1.4 and so EJB 2.0 applications can be deployed.

  12. Do GlassFish support Active and Passive cluster ?

    In GlassFish the cluster instances talk to each other for health monitoring through GMS (of Shoal). The buddy instances talk to each other for replication of the session state. When a failure is detected the LoadBalancer can failover the request to any instance in the cluster. The session in question will be fetched from a replica to this instance in order to continue the conversational state of the session. In this sense, we have an active cluster.

    GlassFish does not have a concept of a standby or passive cluster which will take over when an active cluster fails altogether. That is usually considered a high cost approach for redundancy and not advisable. 

    Read more discussion here.

  13. Can we add a Metro Web service wrapper be created around EJB 2.0 ?

    Nope, Metro Web service wrapper can be created around EJB 3.0 only.

  14. How can an application deployed on WebLogic be migrated to GlassFish ?

    Migrate2GlassFish helps automate the migration of J2EE/Java EE applications to GlassFish.

  15. Can Entity beans be configured only as read-only beans - caching server for these beans ?

    Yes, read about the characteristics, good practices, how to deploy and refresh read-only beans.

  16. How can jMaki applications run behind the firewall ?

    Add the following Servlet parameters to web.xml:

    <context-param>
      <param-name>proxyHost</param-name>
      <param-value>PROXY_HOST</param-value>
    </context-param>
    <context-param>
      <param-name>proxyPort</param-name>
      <param-value>PROXY_PORT</param-value>
    </context-param>


    This is described in detail at https://ajax.dev.java.net/xmlhttpproxy.html.

Technorati: conf webservices web2.0 ruby jruby projecmetro glassfish netbeans q&a

del.icio.us | furl | simpy | slashdot | technorati | digg |
|

http://blogs.sun.com/arungupta/date/20071212 Wednesday December 12, 2007

TOTD #20: How to create a new jMaki widget ?

This TOTD explains how to create a new jMaki widget and make it available in the NetBeans palette.

In order to create a jMaki widget, it's important to understand the jMaki Widget Model.

Basically, "component.htm", "component.js" and an optional "component.css" together make a jMaki widget.

Here are the files for a Hello World widget that takes an argument, concatenates it with the string "Hello" and displays the result on the page.

component.htm

<div id="${uuid}" class="hello"></div>

component.js

jmaki.namespace("jmaki.widgets.hello");

jmaki.widgets.hello.Widget = function(wargs) {
  var hello = document.getElementById(wargs.uuid);
  hello.innerHTML = "Hello " + wargs.args.name;
}

component.css

.hello {
  font-size: 22px;color: red;
}

The following files are required if you like to package your component as a reusable widget library in the NetBeans IDE:

hello.jsp

<a:widget name="hello" args="{name: 'Duke'}" />

Bundle.properties (top-level)

jMaki.Library.Name=jMaki Hello Widget

Bundle.properties (templates)

NAME_templates.hello=Hello
HINT_templates.hello=<html>Hello</html>

widget.json

{
  'name': 'Hello',
  'type': 'custom',
  'version': '1.0',
  'jMakiVersion': '1.0'
}

Package these files together in the following directory structure (choose any zip file name):

Bundle.properties
resources
  hello
    component.htm
    component.js
    component.css
    widget.json (optional)
templates
   hello
     hello.jsp
     Bundle.properties

And then you zip up these files together, that's it! Now this zip file can be added to the jMaki palette in the NetBeans IDE as shown here. Really simple!

After the widget is added to NetBeans palette, it looks like as shown below:

Now, just like any other jMaki widget, you can drag-and-drop "Hello" from the jMaki palette in your JSP page and the following code fragment is generated:

<a:widget name="hello" args="{name: 'Duke'}" />

After the application is deployed, the page is rendered in the browser as shown below:

Couple of points ...

  1. Templates for other languages such as Ruby or PHP can be added in the templates directory. This enables drag-and-drop of your widget in those languages as well.
  2. It's important to maintain the case sensitivity of the property names in Bundle.properties otherwise they will not be recognized.

Please leave suggestions on other TOTD that you'd like to see. A complete archive is available here.

Technorati: totd jmaki web2.0 widgets ajax netbeans

del.icio.us | furl | simpy | slashdot | technorati | digg |
|
« Previous month (Nov 2007) | Main | Next page of month (Dec 2007) »

Valid HTML! Valid CSS!

This is a personal weblog, I do not speak for my employer.