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
To follow this tutorial, you need the following software and resources.
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
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:
In this section, we create a new database, called "music". We populate it with data about songs.
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.
Download the musicdb.sql script. In the IDE, click File > Open File. Navigagte to where you downloaded the musicdb.sql script, and open it in the editor. Select the Music connection in the toolbar at the top of the SQL Editor:
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. Refresh the Tables node if the database structure does not appear.
In this section, we use a wizard to generate entity classes from the data in our database.
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.
Under Project Name, enter MusicDB. Click Next. Under Server, select a server, such as GlassFish. Click Finish. Right-click the MusicDB project node and choose New > Entity Classes from Database. (If this option is not there, choose New > Other > Persistence > Entity Classes from Database.)The New Entity Classes from Database wizard appears.
In the Data Source drop down list, choose New Data Source. The Create Data Source dialog box opens. 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.
From the Available Tables list, select PLAYLIST, SONG, and PLAYLIST_SONG. Click Add and then click Next. Click Create Persistence Unit. Accept all the default values, shown below, anc click Create.
In package name, type org.music. Click Finish.The IDE creates two entity classes, Playlist.java and Song.java.
In this section, we use a wizard to create RESTful web services from the entity classes we created in the previous section.
Note: If the above item is not available, you need to install the RESTful WebServices plugin, as described at the start of this tutorial.
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:
Click Finish.
The classes generated by the wizard are shown below:

In this section, we use the GlassFish Tester application as a test client for the RESTful web services we created in the previous section.
The web application is built, deployed, and the default browser opens showing the test client page.
Click a link to see information from the database, as shown below:
Close the browser.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.
Click Finish.
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.

In this section, we create the application's index.html page. Then we download the CSS Stylesheet and related images.
<!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>
Download the style.css into the music subfolder. Download the images.zip and unzip its content into a new music/images subfolder.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.
Note: To save time, or if you encounter problems, download main.js here.
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.
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.
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.
In this section, we integrate a Music Player into our application.
<?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>
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:

In this section, we check our application and then deploy it.
Right-click the project node, choose Properties, click Run and type music/index.html in the Relative URL field. Right-click the project node and choose Run.
The application is deployed to http://localhost:8080/MusicApp/music/index.html.
The application is shown in the browser:
Click the "Nova" playlist and all the songs under "Nova" are shown:
Click on Motorway or Sonic Youth to play the song.For more information about using NetBeans IDE to develop Java EE applications, see the following resources:
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.
You are viewing a mobilized version of this site...
View original page here