Arun Gupta, Miles to go ...

Arun Gupta is a technology enthusiast, a passionate runner, and a community guy who works for Sun Microsystems.
« Previous page | Main | Next page »

http://blogs.sun.com/arungupta/date/20080124 Thursday January 24, 2008

RESTful representation of "sakila" using GlassFish and NetBeans IDE

"sakila" is the sample database shipped with MySQL (pronounced as my ess-kew-ell). In the context of Sun Microsystems announcing the agreement to acquire MySQL, I'd like to dedicate this entry to show how this sample database can be exposed as a RESTful Web service endpoint and deployed on GlassFish using Jersey Tooling Plugin (0.4.1 with Jersey 0.4) in NetBeans IDE.

Lets get started!

  1. Install MySQL & the sample database "sakila".
    1. Download and Install MySQL Community Server.
    2. Download sakila sample database.
    3. Install the database as described here.
    4. Start MySQL database by giving the command 'mysqld-nt --user root --console' in bin directory on Windows or './bin/mysqld_safe' from MySQL directory on Unix flavors.
  2. Create the Project & Database Connection
    1. In NetBeans IDE, create a new Web project and name it as "sakila". Choose "GlassFish v2" as the "Server:".
    2. In the "Services" tab of NetBeans IDE, expand "Drivers" and add MySQL Connector/J driver if it does not exist already.
    3. Create a new new database connection by right-clicking on "Drivers" and specifying the parameters as shown below:

  3. Create the Persistence Unit
    1. Right-click on the project and select "New", "Entity Classes from Database...". In "Data Source", select "New Data Source..." and specify the values as shown below:

    2. Click on "film" in "Available Tables" and click on "Add >" as shown below:



      Click on "Next >".
    3. Click on "Create Persistence Unit..." and take all the defaults as shown below:



      Click on "Create".
    4. Enter the package name as "sakila" as shown below:



      and click on "Finish".
    5. In the NetBeans project explorer, expand "Configuration Files" and open "persistence.xml". Specify the username and password by replacing <properties/> with the following fragment:

      <properties>
        <property name="toplink.jdbc.user" value="root"/>
        <property name="toplink.jdbc.password" value=""/>
      </properties>


      Make sure to match the username and password to your MySQL installation.
  4. Create RESTful Web service endpoint
    1. In NetBeans IDE, click on "Tools", "Plugins", "Available Plugins", "RESTful Web Services" and then click on "Install". This installs the Jersey Tooling Plugin in the IDE.
    2. Right-click on the project, select "New", "RESTful Web Services from Entity Classes...".
    3. Click on "Add >>", take all other defaults as shown below:



      click on "Next >", take all defaults and then "Finish".
  5. Test RESTful Web Services
    1. Right-click on the project and select "Test RESTful Web Services". The following web page is presented in the browser:

    2. Click on "films" and then on "Test" as shown below:



      Clicking on "Test" button or the URL "http://localhost:8080/sakila/resources/films/" shows the RESTful representation of the "Film" table. The default representation shows 10 records from the table where each entry returns the "id" of the film and a reference to the detailed entry.

      You can view more entries (say 40) by giving the URL "http://localhost:8080/sakila/resources/films/?max=40". Additional fields from the table can be displayed by adding getter methods to "converter.FilmRefConverter" class such as:

      @XmlElement
      public String getTitle() {
        return entity.getTitle();
      }


      to return the film title in addition to the fields already returned. The different columns in the table can be viewed by going to the "Services" tab, expanding the sakila database connection created earlier as shown below:



      The modified output (with film title included) looks as shown below:

Here are few more ideas for you to explore:

  • Create RESTful representations of other tables using the steps described above.
  • Display the data from different tables in a jMaki-wrapped Yahoo or Dojo data table as explained in TOTD #10.
  • Display the data retrieved from the database in a JSP page as described in Hello JPA World.
  • Create a CRUD application using jMaki Data Table as described in TOTD #15 or Screencast #Web10.

A JRuby-on-Rails application using MySQL is explained here. TOTD #9 explains how JDBC connection pooling in GlassFish can be used for a JRuby-on-Rails application using MySQL.

The key message here is MySQL can be very easily used with GlassFish and NetBeans IDE makes it possible! Once MySQL becomes part of Sun, this integration is going to be much more seamless for the betterment of community.

All the entries on this blog using MySQL can be found here. And last but not the least, Welcome aboard MySQL!

A NetBeans project with all the source code can be downloaded from here. You will still need to setup the database connection and need to make sure the correct version of Jersey plug-in as well :)

Technorati: glassfish netbeans jersey mysql sakila jpa jmaki rubyonrails

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

http://blogs.sun.com/arungupta/date/20080118 Friday January 18, 2008

Travel Plans for Q1 2008 - Fairfax, Little Rock, Orlando, Hyderabad, New York, Las Vegas

Here are my tentative travel plans for the next 3 months:

Event Dates Location
Partner Preso Jan 23 Fairfax, Virginia
Partner Preso Jan 24 Little Rock, Arkansas
Rails for All Feb 8-9 Orlando, Florida
Sun Tech Days Feb 27-29 Hyderabad, India
Ajax World Mar 18-20 New York
The Server Side Java Symposium Mar 26-28 Las Vegas

Stop by and say hello if you are at any of the locations! Also, drop a comment or shoot me an email if you'd like me to talk to your local Java User Group about GlassFish provides an open-source, production-quality and Java EE 5 compatible Application Server. We can also drill down on Metro or jMaki with numerous working samples. If you host or attend a Ruby Meetup then we can also talk about JRuby on GlassFish.

Let me know if you'll be interested in running a few miles together :)

Technorati: glassfish metro jruby ruby jmaki meetup jug webservices web2.0

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

http://blogs.sun.com/arungupta/date/20080109 Wednesday January 09, 2008

jMaki @ Ajax World, New York 2008

Ajax World 2008 - New York City

Sun Microsystems is a Gold sponsor of Ajax World 2008, New York City. I'll be speaking on Web Application Development using jMaki.

jMaki
is a light-weight framework to create Rich Internet Applications using the best tools/libraries and standard practices. I plan to deliver the talk with lots of demos and hope you'll be able to correlate them with real-life scenarios easily. Of course, GlassFish provides a robust development environment for deploying these applications.

I liked the fact that they put my name/photo on the front page as shown below (kinda cool):

Ajax World 2008 Front Page

This is the first time it happened to me :)

If you have not registered yet, Register Today (before Jan 18) and save $200.

Find out more about the Products, Solutions, Free Developer Tools, Try and Buy and Other Cool Stuff for your next generation Web application (aka "Web 2.0") at developers.sun.com/web.

Technorati: conf jmaki glassfish ajaxworld

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

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/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/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 |
|

http://blogs.sun.com/arungupta/date/20071128 Wednesday November 28, 2007

Metro, jMaki & JRuby/GlassFish Q&A from a Preso - Toronto & Montreal

I presented on Metro, jMaki and JRuby-on-GlassFish at a partner meeting on Nov 21 in Toronto and Montreal (yeah, both cities in the same day). That makes it 3 cities (the first one being Seattle) total for now!

I've given multiple talks all over the world to different types of audience but this was my first experience in terms of talking for 3 hours in the morning, flying to another city and then repeating the sessions. GlassFish (both v2 and v3), NetBeans IDE and Windows Vista behaved properly through all the demos. And my talks are typically demo intensive so it was fun! I enjoyed the overall experience (talking, demos, flying) :)

As always, the fun part was interaction with the audience and I always learn something new every time. And, in order to share the knowledge with you, here is the consolidated list of questions from both the cities:

  1. How much Ajax/jMaki support is available in Portal ?

    The Portal Pack plugin for NetBeans can support JMaki 1.0 for building JSR 168 or JSR 286 portlets that use jMaki widgets. There is no other explicit support on the Portal server for JMaki.

    The portlets using jMaki widgets can be deployed on the Sun Portal Server and they should work without any issues. The only catch is that a slight configuration is required to get these portlets to work with the Portal's Ajax container. This is to work around the cross-domain Ajax restrictions of the browser.
  2. What is the frequency of adding wrappers of newer version of toolkits, specifically Dojo toolkit ? Can I add/create the wrappers myself ?

    Frequency depends on the toolkits. Dojo revs about every 6 months with the first major rev just last month. Anyone can create and add wrappers to the palette in NetBeans as explained here. Adding to Eclipse is on a per-web app basis and it will be enabled on palette-basis in the near future.
  3. What level of browser support is available for jMaki, especially for the ones that are not mainstream ?

    Here is the list of supported browsers from jMaki's website:
    • IE 6 and 7 on Windows XP and Vista
    • Firefox 1.5 and 2.x on Solaris, Linux, Windows XP/Vista
    • Safari 2.x and Firefox 1.5 on Mac OS

    Unofficially jMaki runs on:
    • iPhone
    • Opera 9.2+
    • Opera Mobile
    • Older versions of Netscape

    Although the jmaki framework will work on these browsers some widgets may not work (such as those that use SVG) depending on the browser.

  4. When will a .NET version of jMaki be available ?

    If the demand is great we will be more than happy to work to make a version available. The greater the demand the sooner we could do this. If there is interest in the developer community on starting work on a .NET version we could accelerate this process. Please file an RFE if you are interested.
  5. Can the jMaki widgets be rendered to Flash ?

    Absolutely. We previously used some Flash Yahoo Maps and we use Flash for Sound. We are looking at having more media based widgets and it's only a matter of hours in the day that are slowing us down.
  6. Does jMaki work with Ajax4J and DWR ?
     
    jMaki works fine with DWR find a sample app here:
      https://ajax.dev.java.net/servlets/ProjectDocumentList?folderID=6977&expandFolder=6977&folderID=0

    As for Ajax4JSF (Ajax4J seems to not be active) we should work fine as jMaki widgets can be exposed as fully qualified JSF 1.1 or dynamic faces components. We also work with Facelets (see the jMaki samples for more).

And now for the Metro session:

  1. Is there any tooling for adding Security, Reliability and Transactions for Contract-First development ?

    Yes, this is explained here.
  2. Can the apps using JDK 1.4 as the deployment environment use any of the Metro capabilities ?

    Yes and No :) No because Metro programming model uses annotations heavily and that feature is available in Java SE 5 onwards. Yes because once the production environment is upgraded to Java SE 5 (it should work because of backwards compatibility, always good to check though ;) then you can develop your applications using the JDK 1.4 and deploy them on the upgraded production environment.
  3. How the Web service messages generated by Metro be logged ?

    The different options to log Web service messages in Metro are explained here.
     

And finally for the JRuby-on-GlassFish session:

  1. Other than simplicity and productivity, why should I use JRuby or Ruby at all ?

    Rails is the main reason for Ruby to gain popularity. And JRuby provides the simplicity of Ruby along with power of Java libraries.
  2. Can the number of JRuby instances created by GlassFish be configured ?

    Yes, it can be configured as defined here.
  3. With JRuby 1.0.2, there are significant performance differences between Ruby, Java and JRuby. What is being done to address that ?

    The recent releases of JRuby are much more better performing so it's recommended to use a more recent release. And with some JRuby Performance Tweaks the performance is at par with C Ruby (MRI). Also see JRuby on Rails Fast Enough for performance benchmark results.

 

Feel free to ask any other questions in Metro Forum and jMaki Forum or GlassFish forum or JRuby user list.

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

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

http://blogs.sun.com/arungupta/date/20071120 Tuesday November 20, 2007

Metro and jMaki Q&A from a Preso

I presented on Metro and jMaki in a invitation-only gathering on Nov 15. The audience in both the sessions was pretty interactive. Even though the sessions were invitation-only, I'm posting some of the questions asked during the sessions along with their answers.

  1. How to build support for jMaki in other languages such as Perl ?

    The best option is to check out jMaki workspace and look at Jmaki.php and XmlHttpProxy.php.

    The basics are relatively easy but not always obvious. There is no runtime spec so it's hard to get all the little details right: Theming, API keys, and the Proxy behavior are pretty specific. Please feel free to ask a question on jMaki Forums. It would be helpful if you can help us create such a document while adding support for Perl.
  2. Is it possible to point a DataTable widget to a Database table, introspect the database table and auto-generate the rows/columns ?

    Java Persistence API (in Java) and ActiveRecord (in Rails) already serve this purpose. There are detailed instructions for jMaki/JPA and jMaki/ActiveRecord. At this time there are no plans to tie closely to the database. Please file an RFE if you like this feature.
  3. Do we have any comparisons between jMaki and Open Laszlo ?
     
    We need to understand Open Laszlo better to prepare a comparison. At this time no comparison is available.
  4. How are topics implemented ? What is the data structure that implements them ?
     
    The topic name is a String / Regular expression Object. The topic names can also include wildcards (start, include, end with a *). The payload must be an object (strings are objects). https://ajax.dev.java.net/publishsubscribe.html provides some more details.
  5. Do we have any performance data on large data sets - e.g. 15,000 rows in a Data Table widget ?

    Carla has a good sample that explains how pagination can be achieved for large data sets. The real question is "how much can you realistically cache on the client?". There are lots of algorithms and that can be more application logic. If you are going to deal with sets like this then the Dojo Grid is supposed to be good as it handles client-side caching and paging. We'll be adding it as a widget for the dojo 1.0 push.
  6. Are there any widgets that support streaming video ?

    Not yet but it would be very easy to wrap a widget like that. For example, please look at Sound extension that is available as wrapper over Flash.
  7. How to prevent scripting attack on jMaki-wrapped widgets ?

    jMaki wrappers are very trivial. The data from an external domain is not processed in any manner and instead passed on to the underlying toolkits. We make sure the wrappers are well tested and rely on the underlying toolkits to test their widgets.

And now for the Metro session:

  1. How more recent Metro jars be installed on GlassFish ?

    A stand-alone build of Metro can be downloaded from metro.dev.java.net. This build comes with wsit-on-glassfish.xml script and can be used to override the jars in an existing GlassFish v2 installation.
  2. Why Reliable Messaging is required if TCP/IP already provides reliability ?

    TCP/IP provides reliability at the network level. The Reliable Messaging support in Metro implements a transport-independent messaging protocol (defined by the WS-Reliable Messaging spec) with a SOAP Binding. This allows the SOAP message to be used in alternate transports such as JMS or SMTP. It also enables Reliability between a Client and Endpoint with multiple intermediaries in-between which is not possible with TCP/IP.
  3. Is the "Test Web service" feature available outside NetBeans ?

    The "Test Web service" feature in NetBeans makes use of Tester application in GlassFish. It is a web application that dynamically generates the JSP pages by introspecting the WSDL. Currently it only works only for methods that have primitive types in the signature.
  4. What would it take to run Metro on Embedded Jetty ?

    Servlet-based endpoints can be easily deployed on Jetty as explained here. The different variants of Endpoint.publish() currently runs only on Light-weight HTTP server bundled along with Java SE 6. An RFE has already been filed for this functionality and it will be fixed in a future release of Metro.
  5. Does Metro Security integrate with Active Directory ?

    Even though Metro Security cannot be directly integrated with ActiveDirectory, Authentication can be plugged through the integration of Metro with OpenSSO.
  6. What specific performance improvements have we made in Metro ?

    Here are some of the key performance improvements:
    • Revisited some of the key abstractions. The physical data representation was hidden from the user and yet backed by different implementations such as InputStream, JAXB objects, DOM node, Source, etc.
    • Faster, type-safe read access to commonly used properties such as Target Endpoint Address and SOAPAction. Also lazy reading.
    • Headers are made randomly accessible.
    • Filtering of data was enabled by creating an additional wrapper instead and delaying the actual filtering
    • Mostly JAXB is used to write the JAX-WS payload. There were numerous improvements made in JAXB such as:
      • Collapsing the layers and write directly to OutputStream instead of using StAX.
      • Pre-encode tag names to UTF-8
      • Numbers are converted straight to byte stream
      • Namespace prefixes encoded just once and reused
      • Lazy reading and writing of attachments (for example image is encoded in to JPEG byte stream)

    Metro team also presented a BoF 2526 on these improvements at JavaOne 2006.

  7. How much traffic is bloated because of enabling Reliability or Security ?

    There is a definite bloating of messages that happen when either Reliability or Security or Transactions are enabled. I'll provide the exact numbers in a later blog but all the messages are clearly defined by the existing specifications.

Feel free to ask any other questions in Metro Forum and jMaki Forum.

Technorati: conf webservices jmaki glassfish netbeans web2.0 q&a

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

http://blogs.sun.com/arungupta/date/20071107 Wednesday November 07, 2007

Screencast #Web10: CRUD using jMaki and JPA

This screencast shows how to create a simple jMaki application, using NetBeans IDE, that performs some of the CRUD operations on a Data Table widget. It uses Java Persistence API (JPA) to connect to the database and the application is deployed on GlassFish. The rest of the CRUD operations can be easily built using the same methodology.

The steps followed in this screencast are also described in detail.

Enjoy it here!

Technorati: screencast jmaki netbeans glassfish jpa database crud

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

http://blogs.sun.com/arungupta/date/20071101 Thursday November 01, 2007

Sun Tech Days Beijing - Day 1 Report

1500 developers kick started 10th anniversary Tech Day event at the Beijing International Convention Center earlier today.

Joey Shen, Angela Caicedo, Doris Chen and Chuk Munn Lee demonstrated Swing/Java2D, Sun SPOTs, jMaki and JavaFX demo respectively as part of the demo showcase. All the demos were really good and showcased different technologies from Sun. I personally liked Sun SPOT demo which showcased how Robosapiens can be easily controlled using the JVM. It very well resonated with "Internet of Things" that Lionel Kim (President Greater China and COO APAC Sun Microsystems) mentioned in his keynote earlier in the morning.

According to Lionel, there are three factors driving global innovation:

  • Web.next - The key point here is that currently the major producer/consumer of content on the Internet are people. But very soon it'll be an Internet of things where different "things" are interacting on the Web fueled by all the innovations happening in Web.next.
  • Age of the startups - Facebook valued at $ 15 billion has already changed the current landscape and similar companies are going to drive the needs for next generation.
  • Rise of communities - Time magazine awarded YOU (community) as Person of The Year award for 2006. And that indeed is the most important factor in driving innovation.

Carla provided a great coverage of Jim Hughes keynote (during which I was busy with local translators for my upcoming session :) This is the 10th anniversary year of Tech Days and we celebrated by cutting a birthday cake. There is lot of backstage work (audio, video, rehearsal, logistics and all sort of things) that often goes unnoticed and some of the photographs below highlight that work.

Right after the keynote, I gave a talk on "Java EE5, GlassFish and Their Future" and the slides are available here. It was great talking about GlassFish to a 560 capacity room full of audience. Leon showed a demo of localized version of GlassFish and how it can be configured in a clustered environment.

Jim Jiang offered to give away 10 copies of his recently published book on GlassFish. You can order it online here. Jim Jiang and Wang Yu are the primary authors with content contributed from Jason Huang, Ada Li, Liang Ye and Evrin Yan. It was great meeting most of these individuals face-to-face. If you missed being one of the lucky winners of the book, then attend GlassFish Day on Saturday, Nov 3 and there will be many more copies distributed.

I also attended Chuk's talk on Metro and REST. He really presented the concept very well and it was fun seeing somebody else present Metro :)

I spent rest of the day talking to people on the GlassFish booth. Once again, Jim Jiang helped me connect with the local audience. I'll prepare a summary of the  questions and then provide answers to them in a subsequent blog. In the meanwhile, here are some links for you to get started:

The evening ended with Yanjing Beer and Beijing Duck dinner. And as always, enjoy the pictures from through out the day:

 

Follow the complete coverage in Sun Tech Days Event blog.

Technorati: conf suntechdays metro webservices jmaki web2.0 glassfish netbeans beijing

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

http://blogs.sun.com/arungupta/date/20071031 Wednesday October 31, 2007

TOTD #15: Delete/Update Row from Database using jMaki Data Table

A Previous Entry explained how a Data Table widget can be populated from a database using Java Persistence API (JPA). This TOTD extends that entry and explains how a selected row from the Data Table can be deleted from the database. This entry is created based upon a requirement from Dave Briccetti at Silicon Valley Code Camp 2007 last weekend.

The first part of the entry is also a re-write of using NetBeans 6 and the latest jMaki NetBeans plugin.

  1. Create the Web application project
    1. In NetBeans 6 IDE, create a new 'Web Application' project and name it as 'jmaki-database'.
    2. Choose GlassFish V2 as the server as shown below:

    3. Click on 'Next' button, add 'jMaki Ajax Framework' and choose 'Standard' layout as shown below:



      and click on 'Finish' button.
  2. Configure the Database
    1. In NetBeans IDE, 'Runtime' tab, expand Databases, connect to the default database (with the URL 'jdbc:derby://localhost:1527/sample [app on APP]'). Specify the username 'app' and password 'app'.
    2. Right-click again on the URL and select 'Execute Command...' and issue the command:

      create table BOOKS (title varchar(255),
                          author varchar(255),
                          isbn varchar(255),
                          description varchar(255),
                          PRIMARY KEY (isbn))


      This will create the database table.
    3. Add data to the newly created table using the following command:

      INSERT INTO BOOKS VALUES('Galloway Book of Running', 'Jeff Galloway', 'ABC001', 'The best book on running');
      INSERT INTO BOOKS VALUES('The Complete Book of Running', 'James Fixx', 'ABC002', 'Oldest book of running');
      INSERT INTO BOOKS VALUES('The Runners Handbook', 'Bob Glover', 'ABC003', 'Bestselling Guide for Beginning and Intermediate Runners');
      INSERT INTO BOOKS VALUES('Daniel Running Formula', 'Jack Tupper Daniels', 'ABC004', 'Proven programs 800m to Marathon');
      INSERT INTO BOOKS VALUES('Chi Running', 'Danny Drever', 'ABC005', 'Revolutionary approach to effortless, injury-free running');
      INSERT INTO BOOKS VALUES('Running for Mortals', 'John Bingham', 'ABC006', 'A common sense plan for changing your life through running');
      INSERT INTO BOOKS VALUES('Marathoning for Mortals', 'John Bingham', 'ABC007', 'Regular person guide to marathon');
      INSERT INTO BOOKS VALUES('Marathon', 'Hal Higdon', 'ABC008', 'The Ultimate Training Guide');


      This will add 8 rows to the table. You can enter additional rows if you like.
  3. Create the JPA Entity class that maps to the database
    1. In the projects window, select the project 'jmaki-database', right-click and select 'New' and choose 'Entity Classes From Database...'.
    2. Select 'jdbc/sample' as 'Data Source'.
    3. Select 'BOOKS' in 'Available Tables' and click on 'Add' and enter the values as shown below:



      and click on 'Next'.
    4. Specify the package name as 'server' as shown below:

    5. Click on 'Create Persistence Unit...' to create the persistence unit and enter the values as shown below:


      and click on 'Create'.

    and click on 'Finish'.

  4. Add the following named query to the generated JPA class:

    @NamedQuery(name = "Books.findAll", query = "SELECT b FROM Books b")
  5. Configure Persistence Unit
    1. In your project, expand 'Configuration Files' and open 'persistence.xml'.
    2. Click on 'Add Class' button and  choose 'server.Books' class and click 'OK'. This will ensure that the generated entity class is explicitly recognized by the EntityManagerFactory.
  6. In your project, right-click on 'Web Pages', select 'New' and then 'JSP...'. Give the name as 'data' as shown:



    and then click on 'Finish'.
  7. Replace the entire content of template 'data.jsp' with the following:

    <%@ page import="java.util.*" %>
    <%@ page import="server.Books" %>
    <%@ page import="javax.persistence.*" %>

    <%
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("jmaki-databasePU");
      EntityManager em = emf.createEntityManager();

      List<Books> list = em.createNamedQuery("Books.findAll").getResultList();

      out.println("{columns : [" +
        "{ label : 'Title', id : 'title'}," +
        "{ label :'Author', id : 'author'}," +
        "{ label :'ISBN', id : 'isbn'}," +
        "{ label :'Description', id : 'description'}" +
        "],");

        out.println("rows: [");
        for (int i=0; i<list.size(); i++) {
          Books b = list.get(i);
          out.print("{ id: '" + b.getIsbn() + "', " +
            "title: '" + b.getTitle() + "'," +
            "author: '" + b.getAuthor() + "'," +
            "isbn: '" + b.getIsbn() + "'," +
            "description: '" + b.getDescription() + "'}");
          if (i < list.size()-1)
            out.println(",");
          else
            out.println();
        }
        out.println("] }");
      %>
  8. Add and Configure a jMaki Data Table widget
    1. In the generated 'index.jsp', drag-and-drop a 'Yahoo Data Table' widget from the jMaki Palette in the 'Main Content Area'.
    2. Change the generated code fragment from:

      <a:widget name="yahoo.dataTable"
          value="{columns :
                 [
                     { label : 'Title', id : 'title'},
                     { label :'Author', id : 'author'},
                     { label : 'ISBN', id : 'isbn'},
                     { label : 'Description', id : 'description'}
                 ],
                  rows :
                 [
                     { title : 'Book Title 1', author : 'Author 1', isbn: '4412', description : 'A Some long description'},
                     { id : 'bar', title : 'Book Title 2', author : 'Author 2', isbn : '4412', description : 'A Some long description'}
                 ]
                 }" />


      to

      <a:widget name="yahoo.dataTable" service="data.jsp" />

      The 'service' attribute tells jMaki runtime to retrieve the data for DataTable widget from 'data.jsp' instead of the using static data.
    3. Click on the Green button in NetBeans IDE to run the project or default keyboard shortcut (F6). And your browser shows the application deployed as:



      This jMaki-wrapped Yahoo Table Table widget is pulling data from JavaDB.
  9. Now update the project to enable deletion of rows from database based upon row selection. Expand 'Source Packages', 'server', edit 'Books.java' and add the following NamedQuery:

    @NamedQuery(name = "Books.deleteByIsbn", query = "DELETE FROM Books b WHERE b.isbn = :isbn")
  10. In your project, right-click on 'Web Pages', select 'New' and then 'JSP...'. Give the name as shown:



    and then click on 'Finish'.
  11. Replace the entire content of template 'delete.jsp' with the following:

    <%@ page import="javax.persistence.*" %>

    <%
      String isbn = request.getParameter("isbn");
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("jmaki-databasePU");
      EntityManager em = emf.createEntityManager();

      em.getTransaction().begin();
      em.createNamedQuery("Books.deleteByIsbn").
        setParameter("isbn", isbn).
        executeUpdate();
      em.getTransaction().commit();
    %>
  12. Expand 'Web pages' and edit 'glue.js' to add the following fragment in '*onSelect' subscribe method:

    jmaki.doAjax({method: "POST",
      url: "delete.jsp?isbn=" + encodeURIComponent(args.value.isbn),
      callback: function(_req) {
        jmaki.publish('/jmaki/table/removeRow', { targetId: args.value.isbn });
      }
    });
  13. Change the generated code fragment in 'index.jsp' as:

    <a:widget name="yahoo.dataTable" service="data.jsp" subscribe="/jmaki/table"/>

That's it! Now clicking on any row of the table will delete that particular row from the database and also from the table. If jMaki Debugger Console is enabled, then the messages are shown as below:

Using the similar steps described in bullet #9-13, a row can be updated in the database.

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

Technorati: totd jmaki glassfish netbeans jpa database

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

http://blogs.sun.com/arungupta/date/20071030 Tuesday October 30, 2007

Silicon Valley Code Camp Trip Report

Rama and I presented on Metro and jMaki in Silicon Valley Code Camp last Saturday. Here are the pictures

It was good to meet Peter Kellner (SVCC Orgaznier, Aaron Houston (Program Coordinator for JUGs), Van Riper (Silicon Valley JUG Founder), Kevin Nelson (Silicon Valley Web JUG Founder), Juval Lowy (of iDesign) and many others.

And here is a recap of the question/answers asked during the two sessions:

  • Takes 2 Tango: Java and .NET Interoperability
    • Are slides available ?

      Yes, very well. They are available here. A link to the demos shown in the talk is available at:
       
    • There are changed signatures when using JAX-WS 2.1.3 with JDK 6. How does it work ?

      JDK 6 U3 contains JAX-WS 2.0 APIs. JAX-WS 2.1.x contains JAX-WS 2.1 APIs. In order to override the default APIs, the endorsed directory mechanism needs as explained here.

    • How can I send PDF files in SOAP messages ?

      Metro implements MTOM/XOP that allows to send any form of binary attachments (including PDF).
    • How do I achieve higher performance in Web services messages ?

      Metro is a high-performance stack. It can be further boosted by using FastInfoset that uses standard binary encoding for the XML Infoset.
    • How does a client know the request expects a String or Integer ?

      The JAXB specification defines Java-to-XML and XML-to-Java mapping. JAX-WS uses JAXB for mapping of all XML schema to Java constructs..
  • jMaki: Multiple Languages, Multiple Toolkits
    • Are slides available ?

      Yes, very well. They are available here. A link to the demos shown in the talk is available at:
       
    • How can the messages in jMaki be localized ?

      Client-side localization is achieved using JSON on the client and is described here. Server-side localization will use property files and will be delivered in the next release.
    • What part of Flash is supported ?

      Flash can be wrapped and the only example we have is jMaki sound. In general, jMaki strives to be 100% plug-in free.
    • How much support is available in Eclipse ?

      The jMaki plugin for Eclipse is available here. A detailed screencast showing all the steps clearly is available here.
    • Why do we use embedded JavaScript instead of keeping it in a separate .js file ?

      Even though jMaki does not promote embedded JavaScript, but in this case we have to use it to get the correct JavaScript parameters in. There is easy way in a platform neutral way around this to allow for multiple calls back to the server. There is a complicated alternative that requires more steps and that's why not followed.
    • Can custom layouts be used for index.jsp ?

      Yes, jMaki layouts are CSS-based and can be replaced with any standard CSS.
    • How much drag/drop support is available in NetBeans/PHP ?

      NetBeans PHP support is available in Daily Build. Once PHP support is baked, jMaki modules will be made available.
    • What are minimum browser requirements for jMaki ?

      jMaki runs on all current generation of browsers as mentioned here.Here is the list:
       
      • IE 6 and 7 on Windows XP and Vista
      • Firefox 1.5 and 2.x on Solaris, Linux, Windows XP/Vista
      • Safari 2.x and Firefox 1.5 on Mac OS X
    • Can jMaki CSS layouts be used instead of Rails layouts ?

      This functionality is not available in jMaki 1.0. However you can create a Stylized RHTML using jMaki CSS layouts.

Next stop, GlassFish Day @ Beijing.

Technorati: conf siliconvalleycodecamp metro webservices interoperability jmaki web2.0 glassfish netbeans

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

http://blogs.sun.com/arungupta/date/20071023 Tuesday October 23, 2007

Metro & jMaki @ Silicon Valley Code Camp - FREE event on Oct 27 & 28

CodeCamp at FootHill College.  Click Here for Details and Registration Metro (Takes 2 to Tango: Java Web services and .NET interoperability) Room 4306 Saturday (10/27) 11:15am
jMaki: Multiple Languages, Multiple Toolkits Room 4204 Saturday (10/27) 1:45pm

Venue: Foothill College, Los Altos Hills, CA

In the first session (Metro), I'll show how Metro enables interoperability with .NET 3.0 platform. The talk shows how a Secure and Reliable Web service deployed on GlassFish V2 can be invoked from Excel 2007 spreadsheet. It also shows how such a Web service can be easily built using NetBeans 6 IDE.

The second talk explains how jMaki provides a light-weight framework to build Ajax-enabled applications using standard practices and using the best toolkits and libraries. Using multiple demos, it shows how this framework spans multiple languages.

Aaron promised to distribute some nice goodies if you attend these two talks :)

Technorati: conf siliconvalleycodecamp metro webservices interoperability jmaki web2.0 glassfish netbeans

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

http://blogs.sun.com/arungupta/date/20071019 Friday October 19, 2007

Mid West Java Tech Days 2007 - Chicago Trip Report

Mid West Java Tech Days concluded in Chicago yesterday.

With approximately 160 participants, the conference attendees were slightly larger in number than the Minneapolis Tech Days. The interaction with the audience was also good. The day started with Tim Bray's key note and it was a repeat of Minneapolis.

I delivered two talks (same as in Minneapolis)- "Metro: Web services interoperability with Microsoft .NET" and  "jMaki: Framework for Ajax-enabled Web 2.0 apps". Here are the questions (with answers) that were asked during the presentation:

Metro: Web services interoperability with Microsoft .NET

  • Are slides available ?
    Yes, very well. They are available here. A link to the demos shown in the talk is available at:
     
  • Can Metro apps be deployed on JBoss ?
    JBoss WS 2.1.0 will support Metro. Read more details here.
  • .NET 2.0  ?
    Metro provides interoperability with .NET 3.0. We have not tested explicitly with .NET 2.0 however it would be nice if you can test and let us know.
  • Can the WAR created by NetBeans be deployed on other containers ?
    Yes, NetBeans IDE allows to configure Tomcat as a container. After Tomcat is Metro-enabled, using the script bundled with the standalone build of Metro (downloadable from http://metro.dev.java.net), a Metro WAR can be easily deployed on Tomcat directly from within the NetBeans IDE. All the Metro features, except Transactional Web services will work on Tomcat.

jMaki: Framework for Ajax-enabled Web 2.0 apps

  • Are slides available ?
    Yes, very well. They are available here. A link to the demos shown in the talk is available at:
     
  • Can jMaki be integrated with other MVC controllers such as Spring ?
    Currently jMaki integrates very well with Rails. Support for other MVC frameworks can be added by community participation. Let us know if you are interested.
  • Are jMaki widgets available as part of standard plugin ?
    Yes, jMaki plugin for NetBeans and Eclipse comes with all the palettes and widgets that are available.
  • Can the jMaki WAR be deployed on any container ?
    The only requirement for jMaki for Java is Servlet 2.4 and JSP 1.2. If you are using JSF then JSF 1.1 support is required as well.
  • Can a jMaki WAR be hosted on a public site ?
    Yes, The ISP need to have WAR hosting capabilities. If the WAR needs to access external services, then the ISP may also need to allow that explicitly.
  • Can I use it in production ?
    jMaki is ready for production. jmaki.com is using jMaki on PHP. Let us know if we can help you in any manner.

Here is the picture album:

And I met one my avid blog readers - Roman Kuzmik. He was pretty excited to meet me and it's great to hear you like the content produced on this blog :)

Next stop Silicon Valley Code Camp (Nov 27-28).

Technorati: conf webservices glassfish metro jmaki netbeans

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

http://blogs.sun.com/arungupta/date/20071016 Tuesday October 16, 2007

Mid West Java Tech Days 2007 - Minneapolis Trip Report

Mid West Java Tech Days concluded in Minneapolis earlier today.

First, here are some facts I learned about Minneapolis:

  • Minneapolis is a Twin City with St Paul
  • Has 20 lakes and wetlands
  • Mall of America - Biggest retail and entertainment complex in the USA
  • Target headquarters is in the downtown
  • Has the First Basilica in USA
  • 7 miles of skyways linking 8 blocks downtown. Really useful for those rainy and snowy times.
  • Has one of the biggest Tibetan populations in the World (read more here)
  • Abundance of public parks - Accessible within 0.5 mile of every home

Second, the Internet connection at the hotel is ridiculously slow (at least for me) as shown here:

I talked to other colleagues staying at the same hotel and it seemed to work fine for them. Anyway, it took 6 calls to the Tech Support to resolve the issue partly. Or may be it's 1:15am in the morning here, the usage is down and that's why I'm seeing a better response time ;-) But when I explained the issue to the hotel, they happily removed the ISP charges for my first day stay @ the hotel.

Now back to the event.

The event kick started with Tim Bray's keynote.

Tim Bray gave the keynote to an audience of approx 125 people and talked about "Business and Cultural aspect of Web 2.0" and "Programming Language and Infrastructure". Everybody in the room raised a hand when asked if they were a developer which was kind of cool because typically we see a mix of IT managers, Engineering Managers, Sys Admins and of course Developers.

One of the key messages in the talk was to start thinking about outside-in (how the community is going to interact/provide feedback about the product) and inside-out (how open the discussions can be) for a product and see how the community can be involved.

Tim presented Tree View of the Programming Languages. It shows how different programming languages are getting adopted year-by-year. The data is created by collecting book purchasing data from different publishers and then taggin each book with language. They point to notice is that only JavaScript and Ruby are growing. Here are some of the points that he mentioned about PHP & Rails:

PHP

Rails

Java is a 3-legged stool comprising of APIs, JVM and Java language. All the scripting languages (Ruby, PHP, JavaScript, etc) are supported in the JVM using JSR 223 APIs.

Tim also compared PHP, Rails and Java in terms of scaling, dev speed, dev tools & maintainability. The talk concluded by stating that Single Architecture IT shop is never going away. PHP, Java, Ruby, .NET - all will continue to exist and live together. REST allows a cleaner integration of these technologies. In my talk on Metro, I discussed an alternate strategy for a heterogeneous systems where Java and .NET can co-exist with each using WS-*-based interoperability achieved in GlassFish.

I delivered two talks - "Metro: Web services interoperability with Microsoft .NET" and  "jMaki: Framework for Ajax-enabled Web 2.0 apps".

The first talk (Metro) was scheduled to start at 11:15 am and there were only 3 people in the room at that time. I started the talk few minutes late giving time for people to show up but even by 11:25 (after I've done the initial introductions) there were only approx 12 people in the room. And then somebody from the audience mentioned that the previous session just finished and I did see a splurge of audience right around that time. On audience's request, I did a recap and then continued with rest of the presentation. I was glad that the room was full in few more minutes :)

The slides are available here. Here is the list of questions asked with their answers:

  • Can Metro apps be deployed on Web Sphere ?
    This is not a tested/supported configuration but Metro apps can be deployed on Web Sphere provided all the libraries are bundled in the WEB-INF/lib directory of the web application itself.
  • Can Metro apps be deployed on JBoss ?
    JBoss WS 2.1.0 will support Metro. Read more details here.
  • How can contract-first endpoint be developed and still utilize interoperability with .NET feature ?
    Use the "New Web Service From WSDL" feature in NetBeans IDE and the enable Security/Reliability/Transactions feature as shown here.
  • Link to demos shown in the talk

The jMaki talk was SRO and we had to borrow multiple chairs from another room to accommodate the audience. The slides are available here. Here is the list of questions asked with their answers:

  • Can jMaki apps be deployed on other containers, such as Tomcat ?
    jMaki web applications are deployed as WAR files and can be easily deployed on any other container.
  • What does it take to create your own widget and make it available in the palette ?
    This page provides low-level details on how to create your own jMaki widgets.
  • What is the total size of jMaki wrapper ?
    18KB
  • Can jMaki apps be developed using JDeveloper ?
    Currently jMaki apps can be developed using NetBeans IDE, Eclipse and Ant-based tasks only. However please send us an email if you are interested in contributing the jMaki plug-in for JDeveloper.
  • Link to demos shown in the talk

And, of course, there were some Hudson enthusiasts.

The evening concluded with a great dinner at Solera along with Charlie, Thomas, Tim and Greg and some interesting discussions about scripting languages.

Here is the picture album so far:

Next step Chicago on Oct 18, there is still time to register!

Technorati: conf webservices glassfish metro jmaki netbeans hudson

del.icio.us | furl | simpy | slashdot | technorati | digg |
|
« Previous page | Main | Next page »

Valid HTML! Valid CSS!

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