Learning Curve Series Journal 5
April 4th, 2006 by WalterExploring Web Services, Part 1: Google Spell Checker
Before this experiment with Google Web Services I had not yet implemented web service applications in my business, though I could clearly see the need for them. Since I started working with Java Studio Creator I saw an opportunity to make current some of the older technology I built to do web services-type jobs before web services came around.
In Part 1 of this 2-part article I’ll explore the terminology and technology around web services. I’ll take a look at how they work within the IDE’s environment and build an application that uses Google’s Web Services to check spelling on a word. Then, in Part 2, I’ll put a live web services application from the National Weather Service into action.
Contents
- The Motivation: My Real World App
- Learning the Terminology and the Technology
- Java Studio Creator’s Preinstalled Google Web Service
- Configuring Google’s Spell Checker Web Service
- Deploying and Running the Web Service
The Motivation: My Real World App
A good example of an application that’s perfect for web services is a feature that I built into a series of sites for a group Vermont realtors. To enhance their real estate listings, they wanted the local weather report to appear on their home pages. I designed it—many years ago—to work like this:
- A script runs hourly on my server that reads the National Weather Service Web page (in HTML) for local weather information in Vermont.
- A series of conditional statements in the script parses the page and finds the weather information.
- This information is then written to a database, which is read by my websites.
It works fine, but you can probably guess what happens when the National Weather Service changes their web page…my whole system crashes because it can’t find the information it is looking for and I have to do a lot of work to fix it, fast. A better solution: Web Services.
Luckily, the National Weather Service now offers a web service for access to their information. So I thought this would be the time to redesign my weather application using Java Studio Creator. But first, I need to explore what web services are all about, and become familiar with how they work. I’ll start by doing some background work on the web.
Learning the Terminology and the Technology
Before beginning work with web services, it is necessary to learn about a set of industry-wide standards for using them across the many programming environments, including Java. Both providers (such as Google Web Services) and clients (my Java Studio Creator application) use these standards. The most important are:
- WSDL—Web Services Description LanguageAn XML-formatted language that provides the communication standard between a web service client and provider.
- SOAP—Simple Object Access Protocol
A protocol used over HTTP to send a request to a service at an URL - UDDI—Universal Description, discovery, and Integration
Enables companies and applications to quickly, easily, and dynamically find and use Web services over the Internet. - XML—Extensible Markup Language
A language that makes data portable and widely used across the Web; also serves as a key technology within Web services.
Read more about web services in this popular article, What’s New in SOA and Web Services? by Ed Ort. Another good resource for information on web services is at java.sun.com/webservices.
Java Studio Creator’s Preinstalled Google Web Service
The Google Web Services API provides a SOAP protocol to allow it to access information from Google. This, working in conjunction with WSDL, allows clients to access Google Web Services from within many programming environments, including the Java Studio Creator IDE.
The following information, which I found via the Sun Developer Network (SDN) for Java Studio Creator, is also very helpful and worth exploring:
- Java Studio Creator Tutorials: Accessing Web Services
- Technical Articles and Tips: Using Java Studio Creator to Consume Web Services
- Bookshelf: Java Studio Creator Field Guide: This guide provides an excellent discussion on setting up Google Web Services to perform a search and display results.
Configuring Google’s Spell Checker Web Service
Figure 1: Locating Web Services |
Java Studio Creator makes the process of setting up a web service quite easy. The IDE comes with seven preconfigured web services, and Google is one of them.
Web services are located in the Servers window under the node labeled Web Services (see Figure 1). Inside this node lives another node called Samples where I find the Google Web Service (listed as GoogleSearch). Other choices include web services for news, weather, quotes, world time, and Amazon access.
In Part 2, I’ll add a new web service for the National Weather Service, but for now I just want to experiment with Google’s spell checker feature. Here are the steps:
- Create the user interface: Add components to the Visual Designer
- Add the Google Web Service to the Application
- Add an action to the Check Spelling button
- Obtain a Google license key
- Add the code to the Page Bean
1. Create the user interface: Add components to the Visual Designer
To create the user interface I need to open a new project in Java Studio Creator and populate it with components.
I add a Text Field and a Button component for entering and submitting a spell check to Google. This is easily accomplished by dragging the components from the Basic palette onto the Visual Designer.
Then, I change the text field components id to “spellString” and the button components id to “search” by clicking the appropriate component and changing the value in the Properties window. While I’m at it, I also change the text attribute of my button to “Check Spelling”—this is the button label.
I add a Static Text component and change the id to “result” in the Properties window. My correctly spelled word will get populated here by the Java bean and the Google Web Service.
Finally, I format and size the various components to my liking, adding several Static Text components to give the page some juice, as shown in Figure 2.
Figure 2: My User Interface Design |
2. Add the Google Web Service to the Application
Figure 3: Outline window with |
Java Studio Creator makes my life quite easy, here. To add the service to my application I simply move my mouse to the Server window (see Figure 1) and drag the node, GoogleSearch, onto my design canvas. This is all it takes to add the web service component to my application.
Though this web service is not visible on the Visual Designer, I can see it listed as googleSearchClient1 in the Outline window. The Outline window is typically located below the Servers and Palette windows in the left side of the IDE. It provides an overview of my application’s structure, and also shows the components I have dropped onto the Visual Designer. You may need to go to the View drop-down menu and select Outline to open it, as shown in Figure 3.
To see what functions (that is, methods) are available to me, I go back to the Servers window and expand the GoogleSearch web service one more level as follows:
Web Services > Samples > GoogleSearch
Then I click the “+” one more time and see that three methods were available:
doGetCachedPage
doSpellingSuggestion
doGoogleSearch
For this application, I’ll use the doSpellingSuggestion method. Setting up Google web services for checking spelling is a bit easier than using the Search methods because the spelling method returns a string. When using the doGoogleSearch or doGetCachedPage, an object is returned that requires some additional parsing in Java. But I’ll work with objects in the next article.
I also see that I can click on one of the methods, such as doSpellingSuggestion, to view both Method Information and Method Parameters in the Properties window. In this case, when I look at the Signature under Method Information (Figure 4), it tells me exactly how to interact with this method. When I click on [...]to view the whole line, a new window opens that shows me the following code:
java.lang.String doSpellingSuggestion(java.lang.String key, java.lang.String phrase)
I can see that two Strings are passed to the Web service (key and phrase) and a String is also returned. Here’s how code completion helps me even further:
Figure 4: The Properties window and Signature detail |
3. Adding an action to the Check Spelling button
Now that the page looks the way I want, and the Google Web Service is installed in my application, I need to instruct my Java Studio Creator application what to do when the end user clicks my Check Spelling button. Because I want it to start the Google Web Services API, I have to add an action to this button.
By double-clicking on the button inside the Visual Designer I am put right into the Java Page Bean, which lets me insert the action to be performed when my application runs and the user clicks the button. So, from the Visual Designer, I double-click the Check Spelling button and my cursor lands exactly where the code needs to be inserted in the method, as shown below. I like that Java Studio Creator makes it this easy for me to see what line needs my own code!
public String search_action() {
// TODO: Process the button click action. Return value is a navigation
// case name where null will return to the same page.
return null;
}
4. Obtaining a Google License Key
Before my application will work, I need to register with Google and obtain a license key from them. Luckily, this is about as easy as it gets for a registration. Here’s how it works:
- I visit the home page for the Google Web Services API at http://www.google.com/apis/
- A lot of information is provided here, including documentation and a developer’s kit, but I’ll go directly to the option: Create a Google Account.
- I register and receive my license key by email moments later. Google only requires an email address and password (which I already had from using Google Groups and Google Alerts).
- I’ll also download the Google developer’s kit. This provides good documentation about the query terms allowed within Google (both through their website and through web services), such as how I can use Google to control my searches by limiting to subsets of the Google Web Index or particular languages.
- Besides the three methods mentioned above, the documentation also provides information on all the methods available for use.
5. Add the code to the Page Bean
Now that I have my license key, I’ll go back to the Page Bean and start writing a few lines of code. I can access my Page Bean by clicking on the Java tab above my editor pane. But instead, I double-click on my Check Spelling button, which puts me in the page bean at the exact point of the button’s action.
Now in the Page Bean, I notice that the IDE has already added the following line of code to the top of my Page Bean:
import webservice.googlesearchservice.googlesearch.GoogleSearchClient;
This code imports the Google Web Services package, and allows me to use the code-completion feature contained within Java Studio Creator to help me build Java as I type.
Step 1: Add a private instance variable
First, I need to add the following private instance variable above my search_action() method:
private String mySearchResult;
The above statement declares that the returned results will be a string called mySearchResult. If I were using the Google Search feature, I would instead declare an object, as the results would contain many variables. This is how Google Web Services packages them.
Step 2: Add variables
Then I add some variables to my method, starting by replacing the line // TODO: Process the button click action with the following:
String spellCheckWord = null; String myKey = "EnterYourKeyHere";
The variables spellCheckWord and myKey will be passed to the Google Web Services (explained in more detail below). I need to initiate them both as type String. Then I enter the key I received by e-mail from Google.
Step 3: Add code to search_action() method
Here’s the code I added to my search_action() method:
if (this.spellString.getValue() != null) {
spellCheckWord = (String)this. spellString.getValue();
}
try {
mySearchResult =
googleSearchClient1.doSpellingSuggestion(
myKey,spellCheckWord);
if (mySearchResult != "") {
result.setValue(mySearchResult);;
} else{
result.setValue("No Results Found");
}
catch (Exception e) {
log("Remote Connect Failure", e);
throw new FacesException(e);
}
return null;
}
It’s worth taking a look at the code piece by piece. This code first tests whether the user entered text into the text box prior to pressing the button. (Ideally, I’d include an else statement in case the user did not enter anything.)
if (this.spellString.getValue() != null) {
spellCheckWord = (String)this. spellString.getValue();
}
The following try/catch statement allows me to catch an error on connecting with the Google Web Services. The catch section can be expanded to advise the user of what happened in the case of a connection failure.
try {code lines}
catch (Exception e) {
log("Remote Connect Failure", e);
throw new FacesException(e);
}
The code below is the core of my application, as it allows the user to connect with the Google Web Service. MySearchResult is the value returned to my application, in this case, as a correctly spelled word.
mySearchResult = googleSearchClient1.doSpellingSuggestion(myKey,spellCheckWord);
Google documentation tells me that MySearchResult is a type String. I can also see that this is the case by viewing Return Type under Method Information. To see this, I click on doSpellingSuggestion in the Servers window, and then take a look in the Properties window (as shown in Figure 4 above).
To produce the code after the equal sign, I need to enter googleSearchClient1 (which is what the web service was named when I dragged it into my application). If I follow this by a period, code completion shows me my options. Since I’m using Google’s spell checker, I choose the doSpellingSuggestion option and notice that two variables (both strings) need to be passed to check spelling on: myKey and spellCheckWord. These I declared above as type String.
Note that I must call my method as follows:
googleSearchClient1.doSpellingSuggestion
and not just this:
doSpellingSuggestion
In both the Code and the Properties window (shown in Figure 4) I can confirm that this is the case. The longer method is Java Studio Creator’s way of ensuring that I use a unique method name. I have the ability to install more than one instance of Google Web Services, and this allows me to use several instances independently. In learning more about this, I found that the WSDL language allows for this complex model hierarchy, and so within the Java Studio Creator IDE (including multiple port names), I still need to fully qualify my method calls.
The code below instructs the application to make sure that results have been returned. If the word is spelled correctly, or Google is unable to find a correctly spelled word, an empty string is returned. Rather than showing no results at all I want it to display a No Results Found message.
Prepending the Portname to the Method
Java Studio Creator prepends the portname to the method automatically to prevent possible duplication, so the developer doesn’t need to manually address potential conflicts. Every web service has one or more ports, and each port can be a different wire protocol. If a WSDL has multiple ports, and two ports have a method with the same name, a name clash occurs and an error results in the compilation of the convenience. Note that the prepended method is in a convenience class that hides the details of JAX-RPC. The method names you see in the Test Method pop-up window are different than the actual Java code generated because of the need for the convenience wrapper class.
if (mySearchResult != "") {
result.setValue(mySearchResult);
}
else{
result.setValue("No Results Found");
}
Note that result.setValue(mySearchResult); causes my text box—which I named result when I designed my application—to get the value returned by the Google Web Service.
Here is the final method for my button action, including all of the Java I needed to write:
private String mySearchResult;
public String search_action() {
String spellCheckWord = null;
String myKey = "My key provided by Google went here";
if (this.spellString.getValue() != null) {
spellCheckWord = (String)this.spellString.getValue();
}
try {
mySearchResult =
googleSearchClient1.doSpellingSuggestio(myKey,spellCheckWord);
if (mySearchResult != "") {
result.setValue(mySearchResult);
}
else{
result.setValue("No Results Found");
}
}
catch (Exception e) {
log("Remote Connect Failure", e);
throw new FacesException(e);
}
return null;
}
Deploying and Running the Web Service
Now it’s time to test the Google web service in my application. From the menu bar I selected Run > Run Main Project. A few moments later, my application loads in a Web window, and I enter misspelled words. Results are returned to me through the Google Web Services API.
Coming up in Part 2: An application using the National Weather Service Web Service
In Part 2, I’ll build a more advanced application using the National Weather Service web service, and include more advanced output using validators.
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 /jscreator/.
Tags: Creator, IDE, Java, Sun, Technology







