Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Building Research Tools With Google For Dummies (2005).pdf
Скачиваний:
32
Добавлен:
17.08.2013
Размер:
11.68 Mб
Скачать

Appendix C

Using the Google APIs with Java

The appendix tells you what you need to know to get started working with the Google APIs using the Java programming language and the tools pro-

vided in the SDK (software development kit). In this appendix, you’ll find information about

Where to go for more information about Java

The tools you need to work with Java

Running the test Java program that is part of the Google APIs SDK

Building Java programs that use the Java library file included in the SDK

This book doesn’t cover Java programming, the .NET Framework, or any other programming language. It assumes that you already have a background in programming.

Getting Your Java Ducks in a Row

As a first step in evaluating whether you want to write applications that use the Java programming language to access the Google APIs, you should consider the advantages and disadvantages of using Java as opposed to C# .NET or Visual Basic .NET.

Understanding issues with Java

There are differences of opinion about whether programmers should use Java instead of one of the .NET languages (such as C# or Visual Basic .NET) for creating applications that use Web services (such as the Google APIs).

TEAM LinG - Live, Informative, Non-cost and Genuine !

340 Part VI: Appendixes

Visual Studio .NET certainly provides tools that make using Web services (like the Google APIs) easier and more intuitive to use than using the same Web services from a Java program. However, Java programs can be run on almost any operating system that has the correct Java Virtual Machine running on it — you’re not stuck with running programs that run only on Microsoft Windows.

Of course, coexistence seems to be the watchword of the day with large enterprise applications. Many shops use both Java and .NET, as appropriate for a given situation.

For more information about the Java versus .NET controversy, search Google for Java versus .NET and browse the interesting results you get for this search.

Java applications are run using a Java Virtual Machine (JVM). You should know that not all JVMs are identical; the way they work depends on the operating system and vendor. A notorious example is the Microsoft JVM, which is not identical to the Sun Microsystems JVM. In a much-publicized lawsuit, Sun (the creator of Java) forced Microsoft to stop distributing its version of the JVM.

From a programmer’s perspective, the upshot is that you cannot be entirely sure which JVM users have installed on their systems, or even whether they have a JVM at all (some older versions of Windows XP were shipped without the JVM as a result of the Sun Microsystems lawsuit). This is a downside to distributing programs written in Java because you can’t be entirely sure whether they will run on a given system unless the individual downloads and installs the version of the JVM that you used to write the Web service.

A good place to learn more about JVMs is www.java-virtual-machine.net.

Java compilers and editors

In order to compile programs written in Java, you need a Java compiler. You can download the current version (1.5.0) of the Java 2 Platform, Standard Edition (J2SE), which includes javac.exe, the Java compiler, from Sun Microsystems at http://java.sun.com/j2se/1.5.0/download.html.

Theoretically, you can create Java source code in a text editor (such as Windows Notepad or TextEdit on the Mac OS X). A little more realistically, to be productive creating Java applications you should have a decent programming environment. This environment should provide both a code editor with syntax help and a way to visually create user interfaces (as Visual Studio

.NET does in the .NET world).

TEAM LinG - Live, Informative, Non-cost and Genuine !

Appendix C: Using the Google APIs with Java 341

One possible programming environment you can use is the NetBeans IDE (Integrated Development Environment). You can download the NetBeans IDE from www.netbeans.org. You can also download NetBeans as part of a bundle from Sun Microsystems.

NetBeans has the (rather large in my mind) virtue of being completely free to use. It’s got some decent tools for visual development. In fact, I used NetBeans to create the user interface for the application I outline in the section “Using the Google Library,” later in this appendix.

Sun Microsystems also makes its rather more sophisticated development environment, Sun Java Studio, available in an evaluation edition. If you want to use Sun Java Studio beyond the evaluation period, you need to purchase a license.

You can download your evaluation copy of Sun Java Studio from www.sun. com/software/sundev/jde/.

You have a number of other appealing Java development environments to choose from. You might also want to consider:

Eclipse, available for free download from www.eclipse.org/, an excellent development environment that can be used with a variety of languages, including Java.

JBuilder, from Borland, a sophisticated cross-platform Java development environment. You can download an evaluation version of JBuilder from www.borland.com/jbuilder/.

JCreator, which has some nice (read: easy to use) code editor features. You can download a freeware (or light) version of the product from www.jcreator.com/download.htm. (You can get a professional version of the product; however, the professional version requires a licensing fee after the 30-day evaluation period.)

If you’re into one-stop shopping, you can download both JCreator and J2SE — this may be everything you need for Java development — from the JCreator site. However, if you’re new to Java, I would recommend a visit to the Sun site. For example, if you would like to learn more about Java, a good place to start is the Sun Microsystems New to Java Center:

http://java.sun.com/learning/new2java/index.html

TEAM LinG - Live, Informative, Non-cost and Genuine !

342 Part VI: Appendixes

Running the Test

The Google APIs SDK provides a library file, googleapi.jar, which you can use to test, or demonstrate, that you can communicate with the Google APIs from your computer. (See Appendix A for more information about the contents of the SDK.)

You can also use the googleapi.jar file in your own applications that use the Google APIs. See the section, later in this appendix, “Using the Google Library,” for more details.

The googleapi.jar file provides a method, GoogleAPIDemo(), especially made for the purpose of running tests. You call the method from the command line of your computer using the Java interpreter.

The googlapi.jar file contains a compiled version of the GoogleAPIDemo class, which is a demonstration provided by Google showing you how to use the Google API in a Java program.

To run the test, you need to know where googleapi.jar is located. This depends upon where you unzipped the SDK files. A likely location is

C:\googleapi.

To run the test in Windows, follow these steps:

1.Open a Command Prompt window.

The Command Prompt window can be opened from the Windows Start menu in All Programs Accessories Command Prompt.

2.Using the actual location of the googleapi.jar file, type in a command like this all on one line:

java -cp c:\googleapi\googleapi.jar

com.google.soap.search.GoogleAPIDemo

3.When you are finished entering the code, press the Enter key.

When you don’t provide any command-line parameters beyond the class name, you get back a quick response showing the three possible usages for the test of the APIs, corresponding to the three individual APIs described in Chapter 13 (search Google, return a cached page, do a spell check):

Usage: java com.google.soap.search.GoogleAPIDemo <clientkey>

(search <query> | cached <url> | spell <phrase>)

TEAM LinG - Live, Informative, Non-cost and Genuine !

Appendix C: Using the Google APIs with Java 343

This output tells you how to submit an actual query to the googleapi.jar Java library. You have to be a little careful (and not only about not making typos when you enter your developer key); enter searches exactly in the order specified.

For example, to search for the phrase ambidextrous armadillo, you could enter the following at the command prompt (replacing xxxxxxxxxxx in the command with your own developer key):

java -cp c:\googleapi\googleapi.jar com.google.soap.search.GoogleAPIDemo xxxxxxxxxxx search “ambidextrous armadillo” | More

The | More I put at the end of the command displays results one page at a time.

To avoid going stark-raving mad entering commands (including your developer key) over and over again, you can copy text in and out of the Command Prompt window by clicking the title bar and choosing Edit Copy or Edit Paste from the context menu.

When a command such as the search for the keywords ambidextrous armadillo is entered and run against the Java library file, the results are displayed in the Command Prompt window, as shown in Figure C-1.

Figure C-1:

The results of the search are shown in the Command Prompt window.

TEAM LinG - Live, Informative, Non-cost and Genuine !

344 Part VI: Appendixes

To see the code that is used in the demonstration program to call the Google APIs, you can open the source code file GoogleAPIDemo.java in your Java editor (or any text editor). Looking at this code can help you figure out how to call the APIs in your own programs.

Now that you know that you can speak to the Google APIs using Java, it’s time to create your own Google API application in Java.

Using the Google Library

The Java library file that is part of the SDK — googleapi.jar — provides code that encapsulates (makes it easier to call) the Google APIs in your own programs. To access this functionality, you have to import the library com. google.soap.search.* (this includes the classes used to work with the Google APIs) into your application.

An easy way to understand the syntax used to call the APIs using this library is to browse the documentation in the javadoc folder of the SDK. Start with index.html. Click the GoogleSearch class in the frame on the left side of the screen. The methods of the GoogleSearch class — for example, doGet CachedPage — are displayed in the frame on the right side.

Building a Java application in NetBeans

I use the NetBeans Integrated Development Environment (IDE) to create Java applications that use the googleapi.jar library file. But, of course, you can use any Java development environment you’d like (see the section “Java compilers and editors,” earlier in this appendix, for details).

To access the classes that you can use to call the Java APIs with NetBeans, you need to add the googleapi.jar file to your project. After you add this file to your project, you can view the classes (and class methods) that the library file contains in the Filesystems window, as shown in Figure C-2.

The classes and methods in the googleapi.jar library don’t correspond exactly to Google APIs themselves (see Chapter 13) as defined in the Google WSDL file or to the .NET versions of the APIs (see Chapter 16).

Unlike the .NET proxy class, which is generated directly from the Google WSDL file (see Chapter 15 for more information about WSDL files), the classes within the googleapi.jar file were created by Google programmers to make calling the APIs easier. The functionality is identical to the APIs as defined in the WSDL file — and as they appear to .NET applications — but the syntax and names of the methods are a little bit different.

TEAM LinG - Live, Informative, Non-cost and Genuine !

Appendix C: Using the Google APIs with Java 345

Figure C-2:

The google api.jar classes (and some

Google

Search methods) in the NetBeans Filesystems window.

From a programmer’s viewpoint, this means working with them is a little different than working with the Google APIs in .NET (see Chapters 16 through 18 for .NET examples).

To show you how to use the googleapi.jar library classes, I created an application that searches Google and displays the snippet associated with the first return result. Obviously, in your own research applications, you might want to perform more complex actions, but this application shows you the mechanics you need to use to get started.

Creating the visual interface

NetBeans provides facilities for creating a visual user interface using components supplied by the Java swing or AWT (Abstract Window Toolkit) libraries. Both libraries are part of the JFC (Java Foundation Classes). You can find more information about swing at

http://java.sun.com/products/jfc/index.jsp

and AWT at

http://java.sun.com/products/jdk/awt/

I added the swing components shown in Table C-1 to create the user interface for my application.

TEAM LinG - Live, Informative, Non-cost and Genuine !

346 Part VI: Appendixes

Table C-1

Components for the User Interface

Component Type

Name

What It Does

JtextField

jTextDevKey

Google developer key

 

 

 

JtextField

jTextSearchTerm

Search term or phrase

 

 

 

Jbutton

jButtonSearch

Used to initiate Google search

 

 

 

JtextArea

jTextResult

Displays snippet

 

 

 

Using the NetBeans visual development environment, you can add support for a MouseClicked event, fired when the search button is clicked. The code that is executed when this event is processed will go in the jButtonSearchMouseClicked procedure.

The NetBeans development environment generates the code necessary to create an instance of these visual components, the form they are contained on, and to support the MouseClicked event. I omit the generated code in this section, but you can download the entire Java class that contains it from www.braintique.com/research/.

Coding the application

In code, first you need to import the classes from the googleapi.jar library file:

import com.google.soap.search.*;

The class that is used to create the form for the user interface is based on the swing JFrame class. Within the framework code that has been generated for this class, specifically, within the search button’s MouseClicked event, you should add the code to perform the Google search.

This code needs to go within a try . . . catch block so that any error messages Google sends back can be captured and displayed. For example, suppose there’s a problem with a search because the Google developer key has been incorrectly entered. The user of the application would certainly want to know why the search failed, so that the problem can be corrected. Here’s the framework for the try . . . catch block:

try {

...

}

catch (GoogleSearchFault f) {

jTextResult.setText(“There has been a problem: “ + f);

}

TEAM LinG - Live, Informative, Non-cost and Genuine !

Appendix C: Using the Google APIs with Java 347

The text of the GoogleSearchFault f argument passed to the catch block describes the error that occurred.

Within the try block, you need to create an instance of the GoogleSearch class:

GoogleSearch s = new GoogleSearch();

Set the developer key, the maximum number of results (in my case I set the max to one because I am only interested in the first snippet), and the search string:

s.setKey(jTextDevKey.getText());

s.setMaxResults(1);

s.setQueryString(jTextSearchTerm.getText());

I call the doSearch method of the GoogleSearch instance and store the result in a GoogleSearchResult variable:

GoogleSearchResult r = s.doSearch()

Using the getSnippet method of the first element in the GetResultElements array that is a member of the GoogleSearchResult, you then assign the text of the snippet to a String variable, str:

java.lang.String str = r.getResultElements()[0].getSnippet();

The snippets that Google returns tend to have nasty bits of HTML embedded in the text, such as <b> tags to mark the keywords that were found. You can easily get rid of these using Java’s excellent string-handling capabilities (using the replaceAll method of the String class):

str = str.replaceAll (“<b>”, “”); str = str.replaceAll (“</b>”, “”); str = str.replaceAll (“<br>”, “”);

Finally, to display the cleaned-up snippet, enter the following code:

jTextResult.setText(str);

Listing C-1 shows the code for searching Google and returning the first snippet. This listing offers a pretty good idea of how to go about coding a Java application that calls the googleapi.jar Java classes to use the Google APIs.

In Listing C-1, I’ve omitted the generated code that NetBeans used to create the user interface for me. You can see the code, including the generated code omitted from the listing, by downloading the entire Java formGoogleSearch class from www.braintique.com/research/.

TEAM LinG - Live, Informative, Non-cost and Genuine !

348 Part VI: Appendixes

Listing C-1: Searching Google and Returning the First Snippet

import com.google.soap.search.*; import javax.swing.JFrame;

public class formGoogleSearch extends JFrame { /** Creates new form formGoogleSearch */ public formGoogleSearch() {

initComponents();

}

//Generated form and component code omitted

//...

private void jButtonSearchMouseClicked (java.awt.event.MouseEvent evt) { try {

GoogleSearch s = new GoogleSearch(); s.setKey(jTextDevKey.getText()); s.setMaxResults(1); s.setQueryString(jTextSearchTerm.getText()); GoogleSearchResult r = s.doSearch(); java.lang.String str =

r.getResultElements()[0].getSnippet(); str = str.replaceAll (“<b>”, “”);

str = str.replaceAll (“</b>”, “”); str = str.replaceAll (“<br>”, “”); jTextResult.setText(str);

}

catch (GoogleSearchFault f) { jTextResult.setText(“There has been a problem: “

+ f);

}

}

/** Exit the Application */

private void exitForm(java.awt.event.WindowEvent evt) { System.exit(0);

}

public static void main(java.lang.String[] args) { new formGoogleSearch().show();

}

}

If you run this code to display the form, you must enter a Google developer key and a search term, and then click Search. The first snippet displays in the results box, as shown in Figure C-3.

TEAM LinG - Live, Informative, Non-cost and Genuine !

Appendix C: Using the Google APIs with Java 349

Figure C-3:

This Google APIs Java application displays the snippet associated with the first search result.

You can run the class containing the code to search Google from within the

NetBeans IDE by selecting Execute from the Build menu.

Moving on

As the example in this chapter demonstrates, you can use the Google APIs by working with the classes in the googleapi.jar library file (supplied by Google as part of the SDK).

As with any application that uses the Google APIs, the key issue is the query string you use with your GoogleSearch class instance. (See Chapters 4 and 5 for information about constructing sophisticated query strings.)

So go to town, and use the power of Java to create great Google API research applications that

Perform customized searches.

Remember and compare search results.

Track changing results over time.

Display search results in unusual and useful ways.

TEAM LinG - Live, Informative, Non-cost and Genuine !

350 Part VI: Appendixes

TEAM LinG - Live, Informative, Non-cost and Genuine !