Using the Google-Supplied Code


The Google Web Services Kit provides a Java example as part of the package. This example helps you understand how to use Google Web Services, but isn't the best example of the power of Google Web Services. Even so, you'll want to view the example and the accompanying code to make your development experience easier. Using this example also helps you create a working Google Web Services setup on your machine so that you know any errors you see in your application aren't setup related . The following sections discuss the pre-setup requirements for the example and discuss how to use the Google-supplied example to your benefit.

Running the Demonstration Program

Google doesn't leave you out in the cold if you use Java ”in fact, the Java support provided by Google is better than any other programming language. Google Web Services comes with an unassuming library in a file named GoogleAPI.jar. You'll find this file in the \GoogleAPI folder. The documentation for this library appears in the \GoogleAPI\javadoc folder. In general, you'll want to begin with the help-doc.html file to learn about the library and move on to the index.html file for reference purposes. The usage instructions for the demonstration portion of this library appear in ReadMe.txt , but the instructions are so difficult to understand that this section provides some pointers on trying the demonstration program.

The googleapi.jar file contains a number of interesting features ”the most important of which is the Google Java wrapper located in com.google.soap.search.* . The documentation doesn't make the point clear, but this wrapper also includes a method you can use to test the API called GoogleAPIDemo() . You call the method from the command line using the Java interpreter. To learn what tasks the demonstration program can perform, you call the method by itself using a command line such as this one:

 java -cp googleapi.jar com.google.soap.search.GoogleAPIDemo 

In the current version of the API, you get a usage statement in return that includes the three request types: search, cached (page), and spell. Here's a typical usage line:

 Usage: java com.google.soap.search.GoogleAPIDemo <client-key> (search <query>  cached <url>  spell <phrase>) 

The order of the information is important. For example, you can't place your developer license after the request type. In addition, the request type must appear before the request information, such as a list of keywords. You could use this command line entry to request a cached version of my home Web page:

 java -cp googleapi.jar com.google.soap.search.GoogleAPIDemo Your-Developer- License cached http://www.mwt.net 

Note that you must replace Your-Developer-License with the license that Google provides. Because this example runs at the command line, the output also appears in the command window as text. Figure 8.1 shows typical output for the example application. Notice the application repeats all of the input information, along with the Google response. The Client Key field shown in Figure 8.1 is blanked, in this case, but you'll see your key as one of the request values.

click to expand
Figure 8.1: The Google example program outputs text to the command window.

Using the Examples for Your Own Applications

The library that Google supplies doesn't just demonstrate the utility of Google Web Services ”you can also use it to build your own applications. A big benefit of using the library is that you don't have to reinvent the wheel. Google has already created the essential pieces for you. All you need to do is create a reference to the library within your application as shown in Listing 8.1. You'll find the complete source for this example in the \Chapter 08\UseGoogleAPI folder of the source code located on the Sybex Web site. This code comes from the UseGoogleAPIFrame.Java source file. Note that there's additional code for starting the application that appears in the UseGoogleAPI.Java source, but not in this listing.

Listing 8.1: Spelling Check with the Google Library
start example
 import java.awt.*;    import java.awt.event.*;    import java.net.*;    import javax.swing.*;    import javax.swing.table.*;    import com.google.soap.search.*;    public class UseGoogleAPIFrame extends JFrame    {       ... Variable Declarations ...       public UseGoogleAPIFrame()       {          // Get the display information.          Display = getContentPane();          Display.setLayout(new GridBagLayout());          // Define the panel grid bag constants.          ... See Listing for Details...          // Define the component grid bag constants.          ... See Listing for Details...          // Create the Request panel.          ... See Listing for Details ...          // Create the Spelling input.          lblSpell = new JLabel("Spelling Request:");          lblSpell.setDisplayedMnemonic('S');          pnlRequest.add(lblSpell, gbcComp);          gbcComp.gridx = 1;          txtSpell = new JTextField(20);          txtSpell.setText("Soem Tetx is Misppelled");          txtSpell.setToolTipText("Type the word or phrase to check.");          txtSpell.setFocusAccelerator('S');          pnlRequest.add(txtSpell, gbcComp);          ... Other Request Display Items ...          // Create the button handler.          BtnHndl = new ButtonHandler();          // Create the Response panel.          ... See Listing for Details ...          // Create the Correct Spelling output.          ... See Listing for Details ...          // Add the request and response setup to the main form.          Display.add(pnlRequest, gbcPanel);          gbcPanel.gridy = 1; Display.add(pnlResponse, gbcPanel);       }       // This class handles button click events.       private class ButtonHandler implements ActionListener       {          GoogleSearch Service; // Google Search Service Object.          String        Result; // Result of request.          public void actionPerformed(ActionEvent AE)          {             // End the program.             if (AE.getSource() == btnQuit)                System.exit(0);             // Issue a request and receive a response.             if (AE.getSource() == btnTest)             {                try                {                   // Create the required SOAP objects.                   Service = new GoogleSearch();                   // Insert the request data.                   Service.setKey(txtKey.getText());                   // Get the result.                   txtCorrect.setText(                      Service.doSpellingSuggestion(txtSpell.getText()));                }                catch (GoogleSearchFault f)                {                   System.out.println("Error making spelling check.");                   System.out.println(f.toString());                }             }          }       }    } 
end example
 

The code begins with the UseGoogleAPIFrame class code. The main() method creates an instance of this class and displays the result on screen. Most of the code in this class displays objects on screen that the user interacts with to call Google Web Services. Generally, you want to create a form that lets the user enter all of the required input information, along with a developer license when necessary. (You can also embed this information as needed.)

Along with the various inputs, the code defines a button handler of the ButtonHandler class that takes care of calling Google Web Services. The ButtonHandler class interacts with the response objects so the user can see the Google Web Services output. Finally, the UseGoogleAPIFrame class adds these objects to the display area. Figure 8.2 shows a typical example of output from this application.

click to expand
Figure 8.2: The Google API works well for many of the requests you'll make.

To use the Google-supplied library, the ButtonHandler class code begins by creating a GoogleSearch object . The definition for this object appears in the com.google.soap.search library imported at the beginning of the code listing. Because the code is making a simple spelling request, it can use a string as output. The library also defines appropriate objects for other requests.

The actionPerformed() method begins by checking the type of button the user clicked. When the user clicks Quit, the system simply exits.

When the user clicks Test, the code begins by instantiating the GoogleSearch object, Service. This object includes entries for all of the Google Web Services request information ”you won't use every property for every call. Most properties have default values so that you don't need to worry about providing a specific value for properties that your call doesn't use. The only property that you must define is the Key property that the code sets using the setKey() method. In this case, the code uses the doSpellingSuggestion() method to request a spelling check from Google Web Services and to return that value to the application using the txtCorrect.setText() method.

Notice that you must catch any errors that Google Web Services can generate. The library encapsulates all of the possible errors into a single GoogleSearchFault object. In most cases, this single fault approach works fine and you'll never need to do anything more. However, this approach is less explicit than using a low-level call where you can retrieve object-specific fault information. The "Developing a Simple Java Application" section describes an alternative approach that provides better fault information. The trade-off is that you must also perform more coding.

Note  

Your experiences with Google spell checking could vary depending on where you live. For example, many people spell color as colour. Google will always correct the spelling to color , even though both spellings are correct.




Mining Google Web Services
Mining Google Web Services: Building Applications with the Google API
ISBN: 0782143334
EAN: 2147483647
Year: 2004
Pages: 157

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net