Sun Java Solaris Communities My SDN Account Join SDN
 
Installing and Using BluePrints Sample Ajax Components in Sun Java Studio Creator 2
 
By Steve Fleming and Beth Stearns, April 2006  
This article describes sample Java BluePrints components for Ajax (which you may also see written as Ajax elsewhere) that are available via auto-update to the Sun Java Studio Creator 2 IDE and the Sun Java Studio Creator 2 Update 1 IDE. Please see the Ajax and Java Studio Creator article for a general overview of  Ajax and how it fits in with Java Studio Creator. You can also read a detailed tutorial for an Ajax sample component  shown in a keynote (Monday AM) address at JavaOne 2005. A newer version of the tutorial's sample component is provided with the set of samples described here.
 
Contents
 
Overview of the BluePrints Ajax Components
Ajax "Test Drive"
Creating a Sample Application
Other BluePrints Ajax Components
Learning More About the Java BluePrints Components
 

Please note that these Java BluePrints components are provided with the IDE to help you learn about Ajax and demonstrate how it fits well with Java Studio Creator 2.  The sample components are intended to show examples of what is possible when Ajax and JavaServer Faces are used together. Please understand that these components may change as we respond to your welcome feedback.

Overview of the BluePrints Ajax Components
 

The sample Java BluePrints Ajax components update includes the following components:

A more recent update (released April, 2006) adds these three sample components:
Version 3 release includes this additional sample component:
Auto-Complete Text Field: uses Ajax requests to provide a list of  clickable suggestions as the user types.
 
Figure 1: Auto-Complete Text Field
Figure 1: Auto-Complete Text Field
 

Progress Bar
: uses Ajax requests to update the display of progress for a long-running operation.
 
Figure 2: Progress Bar
Figure 2: Progress Bar
 


Map Viewer: uses Ajax requests to the Google Maps API to display a map, and to pan, zoom, show different views, and add balloon markers to the map.
 

Figure 3: Map Viewer
Figure 3: Map Viewer
 


Select Value Text Field: is similar to Auto-Complete Text Field, but displays the list of suggestions in a dropdown component.
The image labelled #1 shows the display as the user types, while the image labelled #2 shows the display as the user interacts with the dropdown list.
 

Figure 4: Select Value Text Field
Figure 4: Select Value Text Field
 

Rich Textarea Editor:
is a text area with a toolbar that lets the user apply formatting ( such as bold, italics, bullets, and so forth) similar to a word processing application.  (Currently, it is best to use Firefox when working with the sample Rich Textarea Editor component because of problems displaying the toolbar correctly in Internet Explorer and Safari browser.)
Figure 5: Rich Textarea component
Figure 5: Rich Textarea component
 
Buy Now Button: a button that initiates a single-order PayPal transaction and posts payment information to the PayPal web site.
Figure 6: Buy Now Button
Figure 6: Buy Now Button
 
Rating: presents a row of stars indicating a rating assigned to an item. When the user assigns a new rating to an item, an Ajax request transmits the rating to the server.
Figure 7: Rating component
Figure 7: Rating component
 
Pop-up Calendar: presents a pop-up calendar from which a date can be selected. The component lets users enter a date or bring up a pop-up calendar from which a date may be selected.
Figure 8: Pop-up calendar component   Figure 8: Pop-up calendar component
Figure 8a: Pop-up calendar component
Figure 8b: Pop-up calendar in browser
 
Ajax "Test Drive"
 

Let's take a quick "test drive" with these components.

Installation

The BluePrints Sample Ajax Components are available via a download from the Java Studio Creator update center.  To launch the update center wizard, start the Java Studio Creator IDE and, from  the main menu bar's Tools menu,  select Update Center.  (If you are working behind a firewall, you will need to configure the proxy server. To do so, click the Proxy Configuration button in the middle of the wizard panel.) After you connect to the update center, step through the wizard and select the update that includes the "BluePrints Ajax Components", then finish the wizard steps. For more information on installing the sample components, see the tutorial Downloading and Importing Ajax Components Into the IDE.

After the auto-update download of the complib completes, a complib is added to a samples directory.  If you are using Java Studio Creator 2, the complib is placed in the $installDir/ nb4.1/samples/complib directory, which is a subdirectory within the directory where you installed Java Studio Creator 2. If you are using Java Studio Creator 2 Update 1, the complib is placed in the $installDir/samples directory.   (To see the  version of the IDE you are running,  click About Java Studio Creator from the Help pull-down menu.)

To add the components to the palette, we import the complib file into the Java Studio Creator IDE using these steps:

1.  If needed, display the Palette by selecting it from within the View menu from the menu bar. Or, if Code Clips are showing, click the Components tab at the bottom of the Palette window.

2.  Position the mouse over any Palette section name, such as Basic, and right click for a context menu. From the context menu, choose Manage Component Libraries.

3.  The Component Library Manager dialog pops up.  Click the Import button, which you'll see in the dialog's lower left corner.

4.  The Import Component Library dialog opens.  Click the Browse button and, depending on your IDE version, navigate to either the nb4.1/samples/complib folder or the samples folder within your IDE installation directory.  Select the file ui.complib, then click ok through the remaining dialogs.  The image below shows an example of the dialog screen that displays after you have selected the complib file.

 

import dialog
Figure 9: Import Dialog
 

After you import the component library, you should see two new sections at the bottom of the Palette.

Creating the Test Drive Web Application

To get started, let's create a minimal application with the Rating component and run it with HTTP monitoring.  (Note: This component was not available with the sample components initially made available in January, 2006. If you do not see the Rating component on the Palette you should update again. Or, if you prefer, skip to the next section.)  To test drive the Rating component, follow this outline:

1. Create a new web application

2. Locate the Rating component in the Palette section BluePrints Sample Ajax Components, one of two new sections added to the Palette after the complib import.  Add a Rating component to your web page.

3.  Turn on the HTTP Monitor, a debugging tool. (To do this, right click the Deployment Server node in the Servers window and open its Properties sheet. Set the Enable HTTP Monitor property to true. It is not necessary to restart the server after you make this change or explicitly open the monitor; the HTTP Monitor display appears automatically when you return to the IDE.)  For help on setting up the HTTP Monitor, open Help Contents from the Help pull-down menu, then search for HTTP monitor.

4.  Add a property called  stars of type int to the Application Bean.  In the Designer, select the Rating component on the web page and click the ... button for
its grade property.  Bind grade to the stars property you created on the Application Bean.

5.  Click the Green Arrow toolbar button to build, deploy, and execute the project in a browser.  You should see a display for the rating component like that shown above. It's possible to watch the HTTP monitor actions while you click on the rating in the browser. To see the HTTP monitor, make your browser window very narrow and position to the left of your display. Then, move your IDE window to the right of the browser.

Figure 9: Rating Component in the Browser
Figure 10: Rating Component in the Browser
 

6.  Switch back to the IDE and examine the HTTP monitor.  Now select different star ratings in your browser.  Notice that the server receives new HTTP requests  every time you click a star rating even though your browser's page is not submitted.  This is Ajax in action.   Select a request in the IDE's HTTP monitor. Notice that the value of the request parameter grade sent to the server corresponds to the number of stars you selected in the browser.

14.  Since the HTTP monitor is no longer required, you may turn it off if you wish.

In addition to sending data to the server without submitting the page, Ajax also allows us to return data from the server to the browser and update a portion of the browser without redisplaying the entire page.  We'll see this next.

Creating a Sample Application
 

Let's learn about more Ajax and Creator by building a sample application.  If you have trouble with any of this drop us a note on the forum.

1.  If you haven't already, first perform the installation described above.

2.  Create a new project.  We're going to create a mini-application that lets you auto-complete the name of a part from the Part database table of the JumpStart Cycles Sample Application. We're just prototyping, so we won't actually integrate this with the JumpStart application.

3.  Drag and drop an Auto-Complete Text Field component onto the Design window.  The Auto-Complete Text Field works a lot like the Ajax functionality in Google Suggest, described in Ajax and Java Studio Creator article. In the Design window, your auto-complete component looks just like a regular text field.  However if you look in the Properties window you can see some interesting differences. In particular, the auto-complete component has a property called completionMethod in the Events section.  We'll work with this next.

4.  The Auto-Complete component has an associated Ajax request for the list of suggested items.  We'll take the option of coding our own Ajax event handler. (See the article Ajax and Java Studio Creator for a general discussion about this.)  Double click the auto-complete component you added to the Design window.  Just like for non-Ajax event handlers, the view switches to display the Java source code with a new method added that corresponds to our Ajax event handler.

5.  You'll see some interesting comments and parameters for this new method.  The prefix parameter corresponds to the string in the component's text field in the browser after a user's input.  The result parameter let's you return a suggested list of items.  This result list is sent back to the browser in response to the Ajax request.  Let's keep it simple and just remove the comment markers from the two lines with result.addItem... (that is, delete the // from the start of the line). 

6.  Click the Green Arrow to build, deploy, and execute your application in the browser.

7.  Now, in the browser, click the text input field to set the focus with the mouse.  You'll see something like this:
 

Figure 10: Result of input focus
Figure 11: Result of input focus
 

Here is what is happening.  The component has been implemented to make an Ajax request when the component receives input focus in addition to when a key is typed.  Thus, your code's Ajax event handler adds "Hello" to the results regardless of the value of prefix.

8.  In honor of all software developers, type the string "world" into the input field.  You can see that the list continuously changes based on what you type.  The second addItem in our event handler simply echoes back the prefix input parameter converted to upper case as shown below.
 
Figure 11: Result of keyboard input
Figure 12: Result of keyboard input
 

As you can see, the IDE and Ajax work very well together.  If you want extra credit, you can follow the roadmap below for enhancing your Ajax web application to auto complete the name of a part from a database table.  Now Ajax can enhance a user interface provided it works quickly.  If you need more speed, take a look.  Since this is a sample application, the roadmap describes the steps for the embedded database.  However you can easily adjust the steps for your database of choice.

Advanced Roadmap for an Ajax Event Handler Returning Database Query Results

This roadmap presents a set of development phases, where each phase adds something new to your sample application. To get the most from this roadmap, plan on iteratively enhancing your sample application one phase at a time.   A good related tutorial is:  Using Databound Components to Access Databases.

Development Phase I: Execute a Query Within the Ajax Event Handler

  1. Make sure the embedded database server is running. Or, setup the database of your choice.

  2. Drop the Part table from the Server window (under JumpStart Cycles) onto the Design window web page.

  3. Edit the query to return all part names starting with the letter 'B'.  Test the edited query by running it in the Query Editor.  For a hint as to how to edit the query, see the first sample query used at the end of this roadmap.

  4. In the Ajax event handler, add code to execute the query.  For a hint, see the sample code below, which shows the final version.

  5. For now, keep the lines of code that add "Hello" and "prefix" to the results list. Put your code to execute the query between these two "Hello" and "prefix" lines.  For debugging, add code to catch SQLException and, in the catch block, have your code look something like this: result.AddItem(e.toString()) where e is the identifier for the exception that is caught.

  6. Build, deploy, and test this first iteration of your sample application.  At this point we are checking that our query did not throw an
    exception. Next, we'll send back query data.

Development Phase II: Pull Data From the Query and Place in the Results

  1. Here we need to take the data returned by the query and add it to the results object.  We use the Data Provider associated with our query's rowset to access the data. To simplify things, you can adjust the query to only return the columns of interest.  For this sample application we will have the query return just the name of the part.  Again, for hints see the code below.

  2. Build, deploy, and test this new iteration of the sample application.

Development Phase III: Adjust the Query to Use the prefix Parameter From the Ajax Request

  1. Change the query to make it a parameterized query. That is, in the Query Editor change the query so that the PART.NAME column accepts a parameter.

  2. Enhance the Java code to set a value for the query parameter.  I recommend just using the letter 'B' to start.  For a hint, see the final version SQL hint below.

  3. Build, deploy, and test this portion of the third iteration of the sample application.

  4. Change the Java code to set the query parameter using the prefix property value.  

  5. If you are using the embedded database sample table, you'll want to convert the leading character of the prefix string to upper case.  See the code for prefixLeadingCap below.

  6. Build, deploy, and test the application again.
Sample SQL and Event Code

Development Phase I SQL hint:

SELECT ALL JSC.PART.NAME
FROM JSC.PART
WHERE JSC.PART.NAME <> 'Not Configured'
   AND JSC.PART.NAME  LIKE  ?


public void autoComplete1_complete(FacesContext context, String prefix, CompletionResult result) {
	// TODO: Return your own list of items here based on the prefix, like this:

	if (prefix == null ||  prefix.length() < 1) {
		return;
	}
	result.addItem("start");
	try {
		String prefixLeadingCap = prefix.substring(0,1).toUpperCase() + prefix.substring(1)
									+ '%';   // phase 3
		result.addItem(prefixLeadingCap);
		// % means match any string starting with prefix, convert to leading
		// caps for better matching

		try {   // phase 1
			CachedRowSetX partRowSet = getSessionBean1().getPartRowSet();   // phase 1
			partRowSet.setObject(1, prefixLeadingCap);   // phase 3, first parameter is 1
			// partRowSet.execute();                  // uncomment for development phase I,
							// later replaced by refresh below

		} catch (SQLException e) {
			result.addItem("Exception: " + e);      // for debugging, otherwise comment out
							// or change for security purposes
			return;
		}
		try {   // phase 2
			partDataProvider.refresh();             // executes the query
			if (!partDataProvider.cursorFirst()) {
				result.addItem("Empty");            // for debugging, comment out otherwise
				return;                             // the query returned no rows
			}
			do {
				String partName = (String) partDataProvider.getValue("PART.NAME");
				result.addItem(partName);
			} while (partDataProvider.cursorNext());
		} catch (DataProviderException e) {
			result.addItem("Exception: " + e);      // for debugging, otherwise comment out
							// or change for security purposes
		}
	} catch (Exception se) {                        // remove this catch after you have
							// finished debugging
		result.addItem("UnknownException: " + se);
	}
	result.addItem("end");

}
 
Other BluePrints Ajax Components
 

The complib file includes a Map View component for developing web applications with the Google Maps API  using Sun Java Studio Creator 2.  There is also a Select Value Text Field component which, while it is general purpose, is particularly useful with mapping web applications.

For tutorials on the different Ajax components, including the Map Viewer and Progress Bar components, see the Sun Java Creator Studio Learning page.

For other technical articles and tips on Ajax components, see the Sun Java Creator Studio Reference page.
 

Learning More About the Java BluePrints Components
 

If you are a component developer and want to learn more about components, you should check out the Java BluePrints components and their associated documents.  Follow these links for more information:

The Java BluePrints Ajax BluePrints web page:
http://java.sun.com/blueprints/ajax.html

The Java BluePrints Solutions Catalog, particularly their Ajax components:
https://bpcatalog.dev.java.net/nonav/ajax/index.html
and
https://bpcatalog.dev.java.net/nonav/ajax/jsf-ajax/frames.html

More Developer Resources

For more tech tips, articles, and expert advice for developers, visit the Java Studio Creator developer resources on the Sun Developer Network (SDN) at http://developers.sun.com/jscreator/.



Return to the Sun Java Studio Creator developer resources page.

Oracle is reviewing the Sun product roadmap and will provide guidance to customers in accordance with Oracle's standard product communication policies. Any resulting features and timing of release of such features as determined by Oracle's review of roadmaps, are at the sole discretion of Oracle. All product roadmap information, whether communicated by Sun Microsystems or by Oracle, does not represent a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. It is intended for information purposes only, and may not be incorporated into any contract.