FeaturesPluginsDocs & SupportCommunityPartners

Creating RESTful Web Service Client Stubs

Download the sample

In this tutorial you will learn how to develop Web 2.0 client applications using the "RESTful Web Service Remoting feature" in NetBeans IDE 6.0 or 6.1. The feature consists of a wizard that lets you generate JavaScript client stubs from RESTful Web Service resource classes. When you do this, you are simplifying the process by which client applications access RESTful web services. The wizard lets you select a project from a list of projects containing RESTful web services. Once you have selected the project and completed the wizard, you will have JavaScript client stubs that will form the basis of your client application. In this tutorial, a complete scenario is presented around this feature.

Contents

Content on this page applies to NetBeans IDE 6.0 or 6.1

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE Web & Java EE version 6.1 or 6.0
Java Developer Kit (JDK) version 6 or
version 5
Java EE-compliant web or application server

Tomcat web server 6.0 and/or
GlassFish application server v2
Important: If you use Tomcat with this Tutorial, see
the NetBeans Wiki on Tomcat with REST

Database The Java DB included with NetBeans IDE or the latest version of MySQL
The musicdb.sql scriptDownload

Both Tomcat and GlassFish can be installed with the Web and Java EE distribution of NetBeans IDE. Alternatively, you can visit the GlassFish downloads page or the Apache Tomcat downloads page.

Optionally, for troubleshooting purposes, you can download the completed sample and inspect the sources.

This tutorial also requires the RESTful Web Services plugin. In the IDE, go to the Plugin Manager, under the Tools menu, and check whether the RESTful Web Services Plugin is installed, under the Installed tab. If it is not, install it from the Available Plugins tab, as shown below:

RESTful services plugin from plugin manager

Creating the Music Database

In this section, we create a new database, called "music". We populate it with data about songs.

  1. Create the database.
    • On NetBeans IDE 6.0, Choose Tools > Java DB Database > Create Database.
    • On NetBeans IDE 6.1, open the Services tab and right-click either the Java DB or MySQL node. (See Connecting to a MySQL Database for instructions on setting up MySQL in NetBeans.) Start the server. Then right-click the database node again and select Create Database.

    Name the database music. On Java DB, give it the username music and password music. On MySQL, type in the root user credentials and do not enter a schema name.

  2. Download the musicdb.sql script.
  3. Open the music script and then select the Music connection in the toolbar at the top of the SQL Editor:
    Music db SQL script in editor, showing Music connection
  4. Click Run in the SQL Editor's toolbar and the script is loaded into the database. You may get some errors reported because the MUSIC schema does not exist, but this does not affect the outcome of the tutorial. If the script runs successfully, the database structure becomes visible in the database connection node in the Services view.
    Services tab showing the database tables created by the music db sql script, for both Java DB and My SQL

Generating Entity Classes from the Music Database

In this section, we use a wizard to generate entity classes from the data in our database.

  1. Choose File > New Project. Under Categories, select Web. Under Projects, select Web Application and click Next.

    Creating a project in NetBeans 6.1 includes new options which can be left at the default. For example, the Use Dedicated Folder for Storing Libraries checkbox may be left unselected.

  2. Under Project Name, enter MusicDB.
  3. Under Server, select a server, such as GlassFish. Click Finish.
  4. Right-click the MusicDB project node and choose New -> Entity Classes from Database

    The New Entity Classes from Database wizard appears.

  5. In the Data Source drop down list, choose New Data Source. The Create Data Source dialog box opens.

  6. Under Data Source, choose New Data Source. The Create Data Source dialog appears.
  7. In JNDI Name, type "jdbc/music". In Database Connection, select either the derby or mysql /music connection from the drop-down list. You should now see the following. Click OK if you do.
    createDataSource.png
  8. From the Available Tables list, select PLAYLIST, SONG, and PLAYLIST_SONG. Click Add and then click Next.
  9. Click Create Persistence Unit. Accept all the default values, shown below, anc click Create.
    Create Persistence Unit dialog
  10. In package name, type org.music. Click Finish.

The IDE creates two entity classes, Playlist.java and Song.java.

Generating RESTful Web Services from Entity Classes

In this section, we use a wizard to create RESTful web services from the entity classes we created in the previous section.

  1. Right-click the project and choose New > RESTful Web Services from Entity Classes,

    Note: If the above item is not available, you need to install the RESTful WebServices plugin, as described at the start of this tutorial.

  2. In the New RESTful Web Services from Entity Classes wizard, click Add All and then click Next. The Generated Classes page opens. You may have to add org.music to the beginning of package names. The correctly completed page follows:
    Generated Classes page showing classes and packages

    Click Finish.

    The classes generated by the wizard are shown below:

    Projects view showing generated RESTful services

Testing the RESTful Web Services

In this section, we use the GlassFish Tester application as a test client for the RESTful web services we created in the previous section.

  1. Right-click the project node and choose Test RESTful Web Services.

    The web application is built, deployed, and the default browser opens showing the test client page.

  2. Click a link to see information from the database, as shown below:
    RESTful service test page in browser
  3. Close the browser.

Creating RESTful Web Service Client Stubs

In this section, we create a new web application. We then use a wizard to create JavaScript client stubs that will interact with our RESTful web services.

  1. Choose File > New Project. Under Categories, select Web. Under Projects, select Web Application and click Next.
  2. Under Project Name, enter MusicApp.
  3. Under Server, select a server, such as GlassFish. Click Finish.
  4. Right-click the MusicApp node and choose New > RESTful Web Service Client Stubs.
  5. Uncheck Create jMaki Rest Components, because we are only going to use base Javascript stubs.
  6. Click Add Project and then add the MusicDB project that we created earlier, as shown below: New RESTful client stubs wizard showing Music DB project selected

    Click Finish.

  7. Run the MusicApp project. A browser opens. Change the browser URL to the page http://localhost:8080/MusicApp/rest/TestStubs.html.

    If the client stubs are generated correctly,

    the playlist URIs are listed in the Playlists row and the song URIs are displayed in the Songs row.

    Test page in browser for music application RESTful services

Displaying the Play Lists

In this section, we create the application's index.html page. Then we download the CSS Stylesheet and related images.

  1. In the Music Application, within the Web Pages folder, create a subfolder called music. Create the subfolder by choosing the Folder template in the Other category in the New wizard. Within this new subfolder, create an index.html page.
  2. Paste the following HTML code into the new file:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html>
    
        <head>
    
            <title>DeeJay - PlayList Community</title>
            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
            <link rel="stylesheet" href="./style.css" type="text/css"/>
    
            <!-- Add the location of the MusicDB remoting scripts generated earlier:-->
            <script type="text/javascript" src="../rest/Support.js"></script>
            <script type="text/javascript" src="../rest/musicdb/MusicDB.js"></script>
            <script type="text/javascript" src="../rest/musicdb/Playlists.js"></script>
            <script type="text/javascript" src="../rest/musicdb/Playlist.js"></script>
            <script type="text/javascript" src="../rest/musicdb/Songs.js"></script>
            <script type="text/javascript" src="../rest/musicdb/Song.js"></script>
            <script type="text/javascript" src="./main.js"></script>
    
        </head>
    
        <body>
    
           <div class="outerBorder">
    
                <div class="border2">
    
                <div class="header">
                    <!-- Add a banner for our application:-->
                    <div class="banner2"><img src="./images/b.gif" width="500" height="100"/></div>
                </div> <!-- header -->
    
                <!-- Add a menu to the left side of the page:-->
                <div id="main" class="main">
                    <table>
                        <tr>
    
                            <td id="leftSidebar" class="leftSidebar bkgclr" class="valign-top">
                                <br/>
                                <span class="ml5">Welcome 'Geertjan'</span>
                                <br/>
                                <br/>
                                <table width="150">
                                    <tr>
                                       <td class="cell ht">
                                            <a href="javascript:showPlayLists()" class="links">
                                               <span class="text2">Playlists</span>
                                            </a>
                                       </td>
                                    </tr>
                                </table>
                            </td>
    
                            <td class="seperator" class="valign-top"></td>
    
                            <!-- Add three DIV tags, with the with id "vw_pl".
                            This is a hook to show all playlists. The id "vw_pl_item"
                            is a hook to show all songs in a playlist, while "cr_pl"
                            is not used in this tutorial. It is left for you
                            an excerise to user to create a playlist.-->
                            <td id="content" class="content  bkgclr" class="valign-top">
                                <div id="vw_pl" class="hide">
                                    <div class="clr"></div>
                                    <div class="heading mglf">Playlists</div>
                                    <div id="vw_pl_content" class="form-container"></div>
                                </div>
                                <div id="cr_pl" class="hide">
                                    <div class="clr"></div>
                                    <div class="heading mglf">Create Playlist</div>
                                    <div id="cr_pl_content" class="form-container"></div>
                                </div>
                                <div id="vw_pl_item" class="hide">
                                    <div class="clr"></div>
                                    <div class="heading mglf">Playlists</div>
                                    <div id="vw_pl_item_content" class="form-container"></div>
                                    <br/><br/>
                                    <div id="add_song_content" class="form-container"></div>
                                </div>
                            </td>
    
                        </tr>
                    </table>
    
                </div> <!-- main -->
              </div> <!-- border2 -->
            </div> <!-- outerborder -->
    
             <!-- Finally we add a hook to invoke a javascript function
             "showPlaylists()":-->
            <script language="Javascript">
                showPlaylists();
            </script>
    
        </body>
    
    </html>
  3. Download the style.css into the music subfolder.
  4. Download the images.zip and unzip its content into a new music/images subfolder.

Using Javascript to Handle Events

In this section, we let the application display playlists from the database. To do this, we write a script that reads all the playlists, using the scripts generated previously in the rest/musicdb folder.

  1. In the Music Application's music folder, create a Javascript file called main.js. Create it by choosing the JavaScript template from the Other category in the New File wizard.
  2. Note: To save time, or if you encounter problems, download main.js here.

  3. Paste the following Javascript snippet into the main.js file:
    var playlistsObj;
    
    function showPlaylists() {
        var app = new MusicDB();
        var resources = app.getResources();
        for(i=0;i<resources.length;i++) {
            var resource = resources[i];
            if(resource instanceof Playlists) {
                playlistsObj = resource;
                var style = 'otab';
                var str = '<div><table class="result"><tr>';
                str += '<td class="tab '+style+'"><a class="links" href="javascript:createPlayList()">\
                   <span class="text2">Create Playlist</span></a></td></tr></table></div>';
                var playlists = playlistsObj.getItems();
                for(i=0;i<playlists.length;i++) {
                    var playlist = playlists[i];
                    var uri = playlist.getUri();
                    var playlistId = playlist.getPlaylistId();
                    var title = playlist.getTitle();
                    var desc = playlist.getDescription();
                    //alert(uri+' '+playlistId+' '+title+' '+desc);
                    str += "<div id='playListsTable'><a href=\"javascript:showPlayList("+i+")\" >"+title+"</a>\
                         <br/>"+desc+"</div>";
                }
                var node = document.getElementById('vw_pl_content');
                node.innerHTML = str ;
                doShowContent('vw_pl');
            }
        }
    }
    
                

    Above, we first create the playlistsObj global variable, so that we can share it across other functions. Next, we create a Playlists object and set its uri. Then we create a button with the text Create Playlist for creating a playlist. The Playlists object uses a function called getChildren that returns a list of Playlist objects, each initialized with its uri. A Playlist object has functions such as getTitle() and getDescription() that help display each playlist's information. To help the user of the music application to see all the songs in a playlist, we provide a link (javascript:showPlaylist(index)) along with the playlist information. Finally, we update the <div> tag with the vw_pl id with the contents we collected so far for displaying all the playlists.

  4. Paste the following Javascript snippet into the main.js file:

    In the following code, the line var uri = playlist.getUri('http://localhost:8080/MusicDB/resources'); assumes you have GlassFish running on the default port, 8080. If GlassFish is using a different port, insert that port number instead of 8080! See also Issue 137922.

    function showPlayList(index) {
        var playlist = playlistsObj.getItems()[index];
        var uri = playlist.getUri('http://localhost:8080/MusicDB/resources');
        var playlistId = playlist.getPlaylistId();
        var title = playlist.getTitle();
        var desc = playlist.getDescription();
        //alert(desc);
        var songsObj = playlist.getSongs();
        //alert(songsObj.toString());
        var songs = songsObj.getItems();
        //alert(songs.length);
        var c = '<div><table class="result"><tr>';
        c += '<td class="tab otab">\
            <a class="links" href="javascript:addSong(\''+playlistId+'\', \'playlist\', \''+uri+'\')">\
                <span class="text2">Add Song</span></a></td>';
        c += '<td class="tab otab">\
            <a class="links" href="javascript:editPlayList(\''+playlistId+'\', \''+uri+'\', \'1\')">\
                <span class="text2">Edit</span></a></td>';
        c += '<td class="tab otab">\
            <a class="links" href="javascript:deletePlayList(\''+playlistId+'\', \''+uri+'\', \'1\')">\
                <span class="text2">Delete</span></a></td>';
        c += '</tr></table></div>';
        var s = '<div><b>'+title+'</b></div><br/>'+c;
        var i = 0;
        var str = '';
        for(i=0;i<songs.length;i++) {
            var song = songs[i];
            //alert(song.toString());
            var uri = song.getUri();
            var songId = song.getSongId();
            var title = song.getTitle();
            var sourceUrl = song.getSourceUrl();
            //alert(uri+' : '+songId+' : '+title+' : '+desc);
            str += "<div id='songsTable'>\
                 <a href=\"javascript:showSong('"+songId+"', '"+title+"', '"+sourceUrl+"')\" >"+title+"</a>\
                     <br/>"+sourceUrl+"</div>";
        }
        var node = document.getElementById('vw_pl_item_content');
        node.innerHTML = s + str;
        doShowContent('vw_pl_item');
    }
    
                

    The showPlaylist(index) function takes an argument that identifies the playlist the user has selected in the playlistsObj array. After retreiving playlist details, we invoke playlist.getSongs(), which returns a Songs object. The Songs object is a container for all the songs in a playlist. After creating buttons to add a song to the playlist, edit playlist, and delete playlist, we need to iterate through the list of songs in the Songs object. To do this, we invoke songsObj.getChildren(). A Songs object has functions getTitle() and getSourceUrl(). These functions let us display song details along with the song source URL. We add a link, javascript:showSong(songId, title, sourceUrl) for each song, to let the user play the music. Finally, we update the <div> tag with the vw_pl_item_content id, with the contents we collected so far for displaying all the songs in the playlist.

  5. Paste the following Javascript snippet into the main.js file, to show a selected song from the playlist:
    function showSong(id, title, songURL) {
        var songContent = getSongOverlay(id, title, songURL);
        var c = '<div><table class="result"><tr>';
        var style = 'otab';
        c += '</tr></table></div>';
        c += songContent;
        var f = document.getElementById('add_song_content');
        f.innerHTML = c;
    
        doShowContent('vw_pl_item');
    }
    
    function getSongOverlay(songId, title, songURL) {
        var songContent = title;
        if(songURL != '') {
            if(songURL.length > 7 && songURL.substring(0, 7) == '<object') {
                songContent = '<div id="video_content_'+songId+'"><br/>' + songURL+ '<br/></div>';
            } else {
                songContent = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"'+
                'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0"'+
                'width="400" height="15" >'+
                '<param name="allowScriptAccess" value="sameDomain"/>'+
                '<param name="movie" value="./xspf/xspf_player_slim.swf"/>'+
                '<param name="quality" value="high"/>'+
                '<param name="bgcolor" value="#E6E6E6"/>'+
                '<embed src="./xspf/xspf_player_slim.swf?playlist_url='+getPlayfile(songId)+'&autoplay=true"'+
                    'quality="high" bgcolor="#E6E6E6" name="xspf_player" allowscriptaccess="sameDomain"'+
                    'type="application/x-shockwave-flash"'+
                    'pluginspage="http://www.macromedia.com/go/getflashplayer"'+
                    'class="align-center" height="15" width="330"> </embed>'+
                '</object>';
            }
        }
        var sid = 'song_overlay_'+songId;
        return '<div id="'+sid+'" class="songOverlay">'+songContent+'</div>';
    }
    
    function getPlayfile(songId) {
        return './xspf/songs/playlist'+songId+'.xspf';
    }
    
    function doShowContent(id) {
        var nodes = new Array();
        nodes[0] = 'vw_pl';
        nodes[1] = 'cr_pl';
        nodes[2] = 'vw_pl_item';
        for(i=0;i<nodes.length;i++)
        {
            doHideContent(nodes[i]);
        }
        var node = document.getElementById(id).style;
        node.display="block";
    }
    
    function doHideContent(id) {
        document.getElementById(id).style.display="none";
    }
    
                

    The showSong() function creates a song overlay based on the song type. If the song source url content is non-url (i.e., an <object> tag), then that content from the source URL is embedded in the HTML page. The plugin in the browser lets us run the content. If the song URL is a URL, we display XSPF Music Player, which needs a metadata file to play a song. You create the metadata files in the next section. Finally, above we add the doShowContent() and doHideContent() functions to show and hide <div> tags.

Adding the XSPF Music Player

In this section, we integrate a Music Player into our application.

  1. In the Music Application's Web Pages folder, create the subfolders /music/songs.
  2. Use the Empty File template in the New File wizard's Other category to create a file called playlist1.xspf.
  3. Add the following content in your new file:
    <?xml version="1.0" encoding="UTF-8"?>
    <playlist version="0" xmlns = "http://xspf.org/ns/0/">
        <trackList>
          <track>
            <location>http://magnatune.com/all/07-Motorway-Nova%20Express.mp3</location>
            <image>http://he3.magnatune.com/artists/img/nova_express2.jpg</image>
            <annotation>Motorway</annotation>
          </track>
        </trackList>
    </playlist>
  4. Create five more playlists, from playlist2.xspf to playlist6.xspf.

    To find the information for fillling the location and image elements for playlists 2 to 6, see the musicdb.sql file or open the Music Database and look for the Song table content for songs 2-6:
    music db SQL script showing song list

  5. Download the XSPF MP3 Player.
  6. In the Music Application's Web Pages folder, create the subfolders /music/xspf. Unzip the download into music/xspf. The player itself is provided by the xspf_player_slim.swf file.

Running the Music Application

In this section, we check our application and then deploy it.

  1. Check that the Music Application looks as follows:
    Project View showing complete Music Application
  2. Right-click the project node, choose Properties, click Run and type music/index.html in the Relative URL field.
  3. Right-click the project node and choose Run.
  4. The application is deployed to http://localhost:8080/MusicApp/music/index.html.

    The application is shown in the browser:

    Application showing playlists
  5. Click the "Nova" playlist and all the songs under "Nova" are shown: Application showing Nova playlist
  6. Click on Motorway or Sonic Youth to play the song.

See Also

For more information about using NetBeans IDE to develop Java EE applications, see the following resources:

  1. NetBeans Wiki: RESTful Web Service Client Stub
  2. Creating and Consuming RESTful Web Service jMaki Components
  3. Getting Started with JAX-WS Web Services in NetBeans IDE 6.0
  4. Developing JAX-WS Web Service Clients
  5. Binding WSDL to Java with JAXB in NetBeans IDE 6.1/6.0
  6. Getting Started with RESTful Web Services
  7. Consuming StrikeIron Web Services in Web Applications
  8. Web Service "Quality of Service" in NetBeans IDE 6.0
  9. EJB & Web Service Applications Learning Trail
  10. YouTube: NetBeans 6.0, Building an End-to-End RESTful Web Application

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE Java EE development features, join the mailing list.

Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by