Developing a Simple Java Application


The "Using the Google Supplied Code" section of the chapter demonstrates an easy way to create a Google Web Services application using only the features provided with the Google Web Services Kit and your favorite Java development product. In most cases, this setup works fine because you can create a basic application without a lot of extra code or effort. However, this technique doesn't always work for several reasons:

  • You need detailed error information.

  • The application requires precise control over the session, especially communication with Google Web Services.

  • The project uses more than one Web service or introduces other complexities the Google library doesn't support.

  • Google updates its Web Services Description Language (WSDL) file to include other function calls that the library doesn't support.

You really won't run into these problems very often, but it's good to know that you have options when you do run into them. The sections that follow accomplish three tasks . First, you'll learn how to set up an alternate library for Google Web Services that does use the WSDL file directly so you can make use of any new features that Google provides. Second, the chapter demonstrates one of the better Java editors on the market so you can automate at least part of the programming process. Third, you'll see an example that demonstrates the low-level access technique that provides precise control over the communication environment.

Tip  

You may soon have other options for working with Java code. According to an eWeek article (http://www.eweek.com/article2/0,4149,1375757,00.asp), Sun is working on a new editor for Java developers. This editor will feature Visual Basic style functionality that will make it easy to create Java applications.

Using an Alternative Library Setup

The library provided for Java use in the Google Web Services Kit is amazingly complete and usable. In most cases, you won't need to look any further than that library for your Java development needs. However, sometimes you do need the additional flexibility and capability provided by a third party library. This section shows how to create an alternative library setup that relies on the WSDL file provided with the Google Web Services Kit or one that you download from the Google site. You'll find all of the batch files and the resulting library in the \Chapter 08\WSDL2Java folder of the source code located on the Sybex Web site.

Make sure you get the latest versions of the Java Development Kit (JDK) and the Axis Simple Object Access Protocol (SOAP) provider. At the time of this writing, you can obtain the Java 2 Platform, Standard Edition (J2SE) version 1.4.2 at http://java.sun.com/j2se/1.4.2/download.html. All of the Apache Axis versions appear at http://ws.apache.org/axis/.

Warning  

Do not use the Beta 3 version of Apache Axis ”at least not on Windows, where it caused a number of errors including a nonreproducible system reboot. I used the Final 1.1 version for the book with good success.

Once you download all of the required support products, install them on your system. Theoretically, you don't have to worry about the installation order. However, I found that I obtained better results by installing the J2SE first and then the various Apache support files.

Note  

Do not follow the Apache Axis installation instructions unless you plan to create your own Web service. You only need the library files to create the Java files required for the client portion of Google Web Services. With this in mind, you can simply un-Zip the Axis files into a convenient directory of your hard drive.

Java must have access to the files required to build the SOAP stubs. This means that you must place the Axis files in the same folder as the WSDL file or you must create a class path for the library. You can use this second technique by adding the -classpath switch to the command line (edit the Client.Axis.BAT file to include it for Windows developers). The class path must include all of the JAR files located in the \ Axis-1 _ 1\Lib folder. When you receive a java.lang.NoClassDefFoundError message, it means that Java can't find the Axis libraries. If you experience this error, you must fix it before you proceed with the rest of this section.

Java takes a piecemeal approach to SOAP support. In addition to Axis, you also need XML parser support. The Axis documentation recommends using the Xerces-J parser found at http://xml.apache.org/dist/ xerces-j /. You don't need the XML parser to create the SOAP stubs, but you do need it to create the example executable using the javac command. Again, make sure you provide a class path for the XML parser. You can find a sample batch file XercesCompile.BAT located in the \Chapter 08\WSDL2Java folder of the source code on the Sybex Web site that performs this step.

At this point, you might see a listing of errors. These errors occur because the capitalization of functions in the Axis-generated stubs differs from the capitalization of function calls in the Google example files. Generally, you must fix an entry in the Google SOAP files. For example, if you see an error for class com.Google.soap.axis.GoogleSearchBindingStub , you'll need to change the GoogleSearchBindingStub.JAVA file. All you need to do is compare the Axis capitalization to the Google capitalization to fix the error.

Warning  

Don't attempt to change the automatically generated Axis files. These files appear in the \com\Google\soap\axis folder and reflect the current state of the Google WSDL files. When you generate these files again, all the errors you fixed earlier will reappear. Always change the Google example files.

Once the program compiles, you can run it. Make sure you include the class path, as you did for the other steps. The RunExample.BAT file located in the \Chapter 08\WSDL2Java folder of the source code on the Sybex Web site shows how to perform this step.

Configuring the JCreator Editor

The professional version of the JCreator editor can make working with Google Web Services a lot easier because it provides help with the various packages and libraries. You don't have to spend time working with batch files because the application compiles within the IDE. In addition, the debugger makes it easy to see how requests to and responses from Google Web Services work. To obtain all these benefits, you need to perform the following configuration steps.

Note  

The JCreator Web site currently includes two versions of the product: 2.5 and 3.0. In addition, you can download a freeware or professional product of each of these major versions. The examples in this chapter assume you have JCreator 3.0 Professional. The steps will also work with the freeware product, but won't work with either 2.5 product.

  1. Create a new workspace using the File New Project command. You'll see a Project Wizard dialog box shown in Figure 8.3.

    click to expand
    Figure 8.3: Select a project type from the list of options.

  2. Select the Basic Java Application option and click Next. The wizard will ask you to provide a project path .

  3. Type a name for the project (the example uses SimpleApplication) in the Name field and click Next. You'll see the Project ClassPath dialog box shown in Figure 8.4. Notice that this dialog box has two tabs JDK Profiles and Required Libraries.

    click to expand
    Figure 8.4: Define one or more libraries as needed using the Required Libraries tab.

  4. Select the Required Libraries tab so you can add the Axis, Xerces, and custom Google libraries.

  5. Click New. You'll see the Set Library dialog box shown in Figure 8.5. This dialog box can add either archives, such as those used for Axis and Xerces, or library paths, such as the one used for the custom Google library .

    click to expand
    Figure 8.5: Add library paths or archives using the Set Library dialog box.

  6. Select Add Add Path or Add Add Archive as appropriate. In both cases, you'll see a dialog where you can select the required path or archive file. When selecting the custom Google library path, choose the \Chapter 08\WSDL2Java\com folder because it's the top-level folder for the library. When working with Axis and Xerces, select all of the appropriate archive files in the \axis-1_1\lib or \xerces-2_5_0 folder.

    Note  

    You can also add source code and documentation files when available using the Sources and Documentation tabs of the Set Library dialog box. The Axis documentation files appear in the \axis-1_1\docs folder, while the Xerces documentation files appear in the \xerces-2_5_0\docs folder.

  7. Type a name for the library in the Name field of the Set Library dialog box and click OK. JCreator will add the library to the list of available libraries for the project.

  8. Repeat steps 5 through 7 for the custom Google, Axis, and Xerces libraries. When you complete the steps, check each of the library entries in the Project ClassPath dialog box. Figure 8.6 shows a typical library setup for Google Web Services.

    click to expand
    Figure 8.6: Make sure you always check the libraries that you want to use with your project.

  9. Click Finish. JCreator will create a new project and workspace for you.

Tip  

Once you configure the libraries you need for Google Web Services, they're available for every other project you create. All you need to do is check the required libraries as shown in Figure 8.6.

You've configured JCreator for use with Google Web Services at this point. These steps probably seem like a lot more work than simply typing what you need into a batch file, but it's also less error prone and somewhat easier to configure. Generally, you'll find modification and updates are much easier to perform using this editor.

Note  

JCreator includes a package myprojects.databasestore or similar statement in the templates that it uses. In some cases, this statement prevents you from running the application from the command prompt. The examples in this chapter don't include the statement. As a result, you'll find the compiled code and RunExample.BAT file in the classes subfolder, rather than in the classes\myprojects subfolder as usual. Make sure you add this statement back in if you want to run the application from within the JCreator IDE .

Writing the Application

At this point, you have a custom library and a specially configured environment in which to work. The example in Listing 8.2 shows how to create a simple search using Google Web Services. The emphasis of this example (besides creating the search) is the use of a custom library. You'll find the complete source for this example in the \Chapter 08\SimpleApplication folder of the source code located on the Sybex Web site.

Listing 8.2: Using a Custom Library
start example
 // This class handles button click events.    private class ButtonHandler implements ActionListener    {       ... Variable Declarations ...       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 GoogleSearchServiceLocator();                Port = Service.getGoogleSearchPort(                   new URL("http://api.google.com/search/beta2"));                Result =                   Port.doGoogleSearch(                      txtKey.getText(), txtSearch.getText(), 0, 10, false,                      "", false, "", "", "");             }             catch(java.net.MalformedURLException e)             {                System.out.println("MalformedURLException error.");                System.out.println(e);             }             catch(javax.xml.rpc.ServiceException e)             {                System.out.println("A ServiceException error occurred.");                System.out.println(e);             }             catch(java.rmi.RemoteException e)             {                System.out.println("A RemoteException error occurred.");                System.out.println(e);             }             // Clear the response table.             for (int RCount = 0;                  RCount < 10;                  RCount++)                for (int CCount = 0;                    CCount < 4;                    CCount++)                    tblResp.setValueAt("", RCount, CCount);             // Retrieve the result elements.             Elements = Result.getResultElements();             // Output the result.             for (int Count = 0;                 Count < Elements.length;                 Count++)             {                // Print out the information.                tblResp.setValueAt(                   StringToText(Elements[Count].getTitle()), Count, 0);                ... Other Response Table Entries ...             }          }       }    } 
end example
 

The code begins by creating the objects used to access and store Google Web Services data. The Service object makes contact with Google Web Services. The Port object defines the actual conduit for information exchange. The Result object contains all of the data returned by Google Web Services, while the Elements object contains just the individual result elements. This setup is far simpler than many Web services, but it's still a little more complex than using the Google library.

You must create the SOAP objects within a try block. Notice that this example contains more catch clauses than the example in Listing 8.1. As expected, the additional error trapping means you must supply additional code, but you also gain the benefit of better error handling. Now you can determine whether an error is the result of a bad URL or something that has gone wrong with the service.

The code creates three SOAP related objects in this example. The Service object is actually instantiated as a GoogleSearchServiceLocator . The GoogleSearchServiceLocator class contains information about Google Web Services, such as the location of the default port. The code uses the Service object to create a port using the getGoogleSearchPort() method. The GoogleSearchServiceLocator class actually provides two forms of this method. The example shows how you can override the default port by supplying a specific port as part of the call. When you call getGoogleSearchPort() without any arguments, you get a port that uses the default settings. It's possible to check the default port using the getGoogleSearchPort-Address() method.

Once the code creates the Port object, it can make the call to Google Web Services using the doGoogleSearch() method. Unlike the Google library, you must supply values for each of the required arguments, even if the argument is blank. This call returns the GoogleSearch-Result object, Result .

The example doesn't output information contained within the upper level of the SOAP response ”it concentrates instead on the individual search elements. With this in mind, the code clears the response table. It then places the result elements in Elements using the getResultElements() method. The Elements object is actually an array of ResultElement objects. Consequently, the code doesn't have to work very hard to discover the individual property values. As shown, all you need is the correct method call to retrieve the property value. Unfortunately, Google assumes that you want to display the information on a Web page, so you must remove the HTML tags and special characters from the output using the StringToText() method described later in this section. Figure 8.7 shows typical output from this application.

click to expand
Figure 8.7: A standard search works equally well with the Google or a third party library.

One of the interesting things about Google output is that you receive the actual output from the HTML page. This method of data retrieval adds HTML tags that won't render correctly with a desktop application. In addition, Google adds the <b> (bold) tag to highlight the keywords in the output. Listing 8.3 shows one technique you can use to remove the extra characters.

Listing 8.3: Replacing HTML Characters
start example
 public String StringToText(String Input)    {       // Replace the bold tag.       Input = Input.replaceAll("<b>", "");       Input = Input.replaceAll("</b>", "");       // Replace the single quote.       Input = Input.replaceAll("&#39;", "'");       // Replace the <br> tag.       Input = Input.replaceAll("<br>", "");       Input = Input.replaceAll("<br/>", "");       Input = Input.replaceAll("<br/>", "");       // Return the results.       return Input;    } 
end example
 

Fortunately, string replacement is easy in Java. All you need to use is the replaceAll() method in most cases. The problem is discovering how to remove the HTML tags. For example, the <b> tag has both an opening and a closing tag. In some cases, a Web page replaces common characters with special escapes , such as the &#39; sequence used for the single quote. Make sure you also consider permutations of some tags. Not every Web site uses the same form of the <br> tag, so you must replace the variations Web sites are likely to use.




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