Java Examples in a Nutshell: A Tutorial Companion to Java in a Nutshell

Java Examples in a Nutshell: A Tutorial Companion to Java in a Nutshell

Java Examples in a Nutshell: A Tutorial Companion to Java in a Nutshell

Java Examples in a Nutshell: A Tutorial Companion to Java in a Nutshell

Paperback(Third Edition)

$39.95 
  • SHIP THIS ITEM
    Qualifies for Free Shipping
  • PICK UP IN STORE
    Check Availability at Nearby Stores

Related collections and offers


Overview

The author of the best-selling Java in a Nutshell has created an entire book of real-world Java programming examples that you can learn from. If you learn best "by example," this is the book for you. This third edition covers Java 1.4 and contains 193 complete, practical examples: over 21,900 lines of densely commented, professionally written Java code, covering 20 distinct client-side and server-side APIs. It includes new chapters on the Java Sound API and the New I/O API. The chapters on XML and servlets have been rewritten to cover the latest versions of the specifications and to demonstrate best practices for Java 1.4. New and updated examples throughout the book demonstrate many other new Java features and APIs. Java Examples in a Nutshell is a companion volume to Java in a Nutshell, Java Foundation Classes in a Nutshell, and Java Enterprise in a Nutshell. It picks up where those quick references leave off, providing a wealth of examples for both novices and experts. This book doesn't hold your hand; it simply delivers well-commented working examples with succinct explanations to help you learn and explore Java and its APIs. Java Examples in a Nutshell contains examples that demonstrate:
  • Core APIs, including I/O, New I/O, threads, networking, security, serialization, and reflection
  • Desktop APIs, highlighting Swing GUIs, Java 2D graphics, preferences, printing, drag-and-drop, JavaBeans, applets, and sound
  • Enterprise APIs, including JDBC (database access), JAXP (XML parsing and transformation), Servlets 2.4, JSP 2.0 (JavaServer Pages), and RMI
The book begins with introductory examples demonstrating structured and object-oriented programming techniques for new Java programmers. A special index at the end of the book makes it easy to look up examples that use a particular Java class or accomplish a desired task. In between, each chapter includes exercises that challenge readers and suggest further avenues for exploration.

Product Details

ISBN-13: 9780596006204
Publisher: O'Reilly Media, Incorporated
Publication date: 01/09/2004
Series: In a Nutshell (O'Reilly)
Edition description: Third Edition
Pages: 718
Sales rank: 729,408
Product dimensions: 5.92(w) x 8.94(h) x 1.24(d)

About the Author

David Flanagan is a computer programmer who spends most of his time writing about JavaScript and Java. His books with O'Reilly include Java in a Nutshell, Java Examples in a Nutshell, Java Foundation Classes in a Nutshell, JavaScript: The Definitive Guide, and JavaScript Pocket Reference. David has a degree in computer science and engineering from the Massachusetts Institute of Technology. He lives with his wife and son in the U.S. Pacific Northwest bewteen the cities of Seattle, Washington and Vancouver, British Columbia. David has a simple website at http://www.davidflanagan.com.

Read an Excerpt


Chapter 19: XML

Contents:

    Parsing with JAXP and SAX 1
    Parsing with SAX 2
    Parsing and Manipulating with JAXP and DOM
    Traversing a DOM Tree
    Traversing a Document with DOM Level 2
    The JDOM API
    Exercises

XML, or Extensible Markup Language, is a meta-language for marking up text documents with structural tags, similar to those found in HTML and SGML documents. XML has become popular because its structural markup allows documents to describe their own format and contents. XML enables "portable data," and it can be quite powerful when combined with the "portable code" enabled by Java.

Because of the popularity of XML, there are a number of tools for parsing and manipulating XML documents. And because XML documents are becoming more and more common, it is worth your time to learn how to use some of those tools to work with XML. The examples in this chapter introduce you to simple XML parsing and manipulation. If you are familiar with the basic structure of an XML file, you should have no problem understanding them. Note that there are many subtleties to working with XML; this chapter doesn't attempt to explain them all. To learn more about XML, try Java and XML, by Brett McLaughlin, or XML Pocket Reference, by Robert Eckstein, both from O'Reilly & Associates.

The world of XML and its affiliated technologies is moving so fast that it can be hard just keeping up with the acronyms, standards, APIs, and version numbers. I'll try to provide an overview of the state of various technologies in this chapter, but be warned that things may have changed, sometimes radically, by the time you read this material.

Parsing with JAXP and SAX 1

The first thing you want to do with an XML document is parse it. There are two commonly used approaches to XML parsing: they go by the acronyms SAX and DOM. We'll begin with SAX parsing; DOM parsing is covered later in the chapter. At the very end of the chapter, we'll also see a new, but very promising, Java-centric XML API known as JDOM.

SAX is the Simple API for XML. SAX is not a parser, but rather a Java API that describes how a parser operates. When parsing an XML document using the SAX API, you define a class that implements various "event" handling methods. As the parser encounters the various element types of the XML document, it invokes the corresponding event handler methods you've defined. Your methods take whatever actions are required to accomplish the desired task. In the SAX model, the parser converts an XML document into a sequence of Java method calls. The parser doesn't build a parse tree of any kind (although your methods can do this, if you want). SAX parsing is typically quite efficient and is therefore your best choice for most simple XML processing tasks.

The SAX API was created by David Megginson (http://www.megginson.com/SAX/). The Java implementation of the API is in the package org.xml.sax and its subpackages. SAX is a defacto standard but has not been standardized by any official body. SAX Version 1 has been in use for some time; SAX 2 was finalized in May 2000. There are numerous changes between the SAX 1 and SAX 2 APIs. Many Java-based XML parsers exist that conform to the SAX 1 or SAX 2 APIs.

With the SAX API, you can't completely abstract away the details of the XML parser implementation you are using: at a minimum, your code must supply the classname of the parser to be used. This is where JAXP comes in. JAXP is the Java API for XML Parsing. It is an "optional package" defined by Sun that consists of the javax.xml.parsers package. JAXP provides a thin layer on top of SAX (and on top of DOM, as we'll see) and standardizes an API for obtaining and using SAX (and DOM) parser objects. The JAXP package ships with default parser implementations but allows other parsers to be easily plugged in and configured using system properties. At this writing, the current version of JAXP is 1.0.1; it supports SAX 1, but not SAX 2. By the time you read this, however, JAXP 1.1, which will include support for SAX 2, may have become available.

Example 19.1 is a listing of ListServlets1.java, a program that uses JAXP and SAX to parse a web application deployment descriptor and list the names of the servlets configured by that file. If you haven't yet read Chapter 18, Servlets and JSP, you should know that servlet-based web applications are configured using an XML file named web.xml. This file contains <servlet> tags that define mappings between servlet names and the Java classes that implement them. To help you understand the task to be solved by the ListServlets1.java program, here is an excerpt from the web.xml file developed in Chapter 18:

  <servlet>   </servlet>   <servlet>   </servlet>   <servlet>   </servlet>

ListServlets1.java includes a main() method that uses the JAXP API to obtain a SAX parser instance. It then tells the parser what to parse and starts the parser running. The remaining methods of the class are invoked by the parser. Note that ListServlets1 extends the SAX HandlerBase class. This superclass provides dummy implementations of all the SAX event handler methods. The example simply overrides the handlers of interest. The parser calls the startElement() method when it reads an XML tag; it calls endElement() when it finds a closing tag. characters() is invoked when the parser reads a string of plain text with no markup. Finally, the parser calls warning(), error(), or fatalError() when something goes wrong in the parsing process. The implementations of these methods are written specifically to extract the desired information from a web.xml file and are based on a knowledge of the structure of this type of file.

Note that web.xml files are somewhat unusual in that they don't rely on attributes for any of the XML tags. That is, servlet names are defined by a <servlet-name> tag nested within a <servlet> tag, instead of simply using a name attribute of the <servlet> tag itself. This fact makes the example program slightly more complex than it would otherwise be. The web.xml file does allow id attributes for all its tags. Although servlet engines are not expected to use these attributes, they may be useful to a configuration tool that parses and automatically generates web.xml files. For completeness, the startElement() method in Example 19.1 looks for an id attribute of the <servlet> tag. The value of that attribute, if it exists, is reported in the program's output.

Example 19.1: ListServlets1.java
 package com.davidflanagan.examples.xml; import javax.xml.parsers.*;                   // The JAXP package import org.xml.sax.*;                         // The main SAX package import java.io.*; /**  * Parse a web.xml file using JAXP and SAX1.  Print out the names  * and class names of all servlets listed in the file.  *  * This class implements the HandlerBase helper class, which means  * that it defines all the "callback" methods that the SAX parser will  * invoke to notify the application.  In this example we override the  * methods that we require.  *  * This example uses full package names in places to help keep the JAXP  * and SAX APIs distinct.  **/ public class ListServlets1 extends org.xml.sax.HandlerBase { 

Compiling and Running the Example

To run the previous example, you need the JAXP package from Sun. You can download it by following the download links from http://java.sun.com/xml/. Once you've downloaded the package, uncompress the archive it is packaged in and install it somewhere convenient on your system. In Version 1.0.1 of JAXP, the download bundle contains two JAR files: jaxp.jar, the JAXP API classes, and parser.jar, the SAX and DOM APIs and default parser implementations. To compile and run this example, you need both JAR files in your classpath. If you have any other XML parsers, such as the Xerces parser, in your classpath, remove them or make sure that the JAXP files are listed first; otherwise you may run into version-skew problems between the different parsers. Note that you probably don't want to permanently alter your classpath, since you'll have to change it again for the next example. One simple solution with Java 1.2 and later is to temporarily drop copies of the JAXP JAR files into the jre/lib/ext/ directory of your Java installation.

With the two JAXP JAR files temporarily in your classpath, you can compile and run ListServlets1.java as usual. When you run it, specify the name of a web.xml file on the command line. You can use the sample file included with the downloadable examples for this book or specify one from your own servlet engine.

There is one complication to this example. Most web.xml files contain a <!DOCTYPE> tag that specifies the document type (or DTD). Despite the fact that Example 19.1 specifies that the parser should not validate the document, a conforming XML parser must still read the DTD for any document that has a <!DOCTYPE> declaration. Most web.xml have a declaration like this:

<!DOCTYPE web-app 

Parsing with SAX 2

Example 19.1 showed how you can parse an XML document using the SAX 1 API, which is what is supported by the current version of JAXP (at this writing). The SAX 1 API is out of date, however. So Example 19.2 shows how you can accomplish a similar parsing task using the SAX 2 API and the open-source Xerces parser available from the Apache Software Foundation.

Example 19.2 is a listing of the program ListServlets2.java. Like the ListServlets1.java example, this program reads a specified web.xml file and looks for <servlet> tags, so it can print out the servlet name-to-servlet class mappings. This example goes a little further than the last, however, and also looks for <servlet-mapping> tags, so it can also output the URL patterns that are mapped to named servlets. The example uses two hashtables to store the information as it accumulates it, then prints out all the information when parsing is complete.

The SAX 2 API is functionally similar to the SAX 1 API, but a number of classes and interfaces have new names and some methods have new signatures. Many of the changes were required for the addition of XML namespace support in SAX 2. As you read through Example 19.2, pay attention to the API differences from Example 19.1.

Example 19.2: ListServlets2.java
 package com.davidflanagan.examples.xml; import org.xml.sax.*;             // The main SAX package import org.xml.sax.helpers.*;     // SAX helper classes import java.io.*;                 // For reading the input file import java.util.*;               // Hashtable, lists, and so on /**  * Parse a web.xml file using the SAX2 API and the Xerces parser from the  * Apache project.  *  * This class extends DefaultHandler so that instances can serve as SAX2  * event handlers, and can be notified by the parser of parsing events.  * We simply override the methods that receive events we're interested in  **/ public class ListServlets2 extends org.xml.sax.helpers.DefaultHandler { 

Compiling and Running the Example

The ListServlets2 example uses the Xerces-J parser from the Apache XML Project. You can download this open-source parser by following the download links from http://xml.apache.org/. Once you have downloaded Xerces-J, unpack the distribution in a convenient location on your system. In that distribution, you should find a xerces.jar file. This file must be in your classpath to compile and run the ListServlets2.java example. Note that the xerces.jar file and the parsers.jar file from the JAXP distribution both contain versions of the SAX and DOM classes; you should avoid having both files in your classpath at the same time....

Table of Contents

Preface; New in This Edition; Java Examples Online; Related Books from O'Reilly; Conventions Used in This Book; Request for Comments; Acknowledgments; Part I: Learning Java; Chapter 1: Java Basics; 1.1 Hello World; 1.2 FizzBuzz; 1.3 The Fibonacci Series; 1.4 Using Command-Line Arguments; 1.5 Echo in Reverse; 1.6 FizzBuzz Switched; 1.7 Computing Factorials; 1.8 Recursive Factorials; 1.9 Caching Factorials; 1.10 Computing Big Factorials; 1.11 Handling Exceptions; 1.12 Interactive Input; 1.13 Using a StringBuffer; 1.14 Sorting Numbers; 1.15 Computing Primes; 1.16 Exercises; Chapter 2: Objects, Classes, and Interfaces; 2.1 A Rectangle Class; 2.2 Testing the Rect Class; 2.3 A Rect Subclass; 2.4 Another Subclass; 2.5 Complex Numbers; 2.6 Computing Statistics; 2.7 An Integer List; 2.8 Tokenizing Text; 2.9 Exercises; Part II: Core Java APIs; Chapter 3: Input/Output; 3.1 Files and Streams; 3.2 Working with Files; 3.3 Copying File Contents; 3.4 Reading and Displaying Text Files; 3.5 Listing Directory and File Information; 3.6 Compressing Files and Directories; 3.7 Filtering Character Streams; 3.8 Tokenizing a Character Stream; 3.9 Random Access to Files; 3.10 Exercises; Chapter 4: Threads; 4.1 Thread Basics; 4.2 Thread-Safe Classes; 4.3 Threads and Thread Groups; 4.4 Deadlock; 4.5 Timers; 4.6 Exercises; Chapter 5: Networking; 5.1 Downloading the Contents of a URL; 5.2 Using a URLConnection; 5.3 Sending Email Through a URLConnection; 5.4 A Simple Network Client; 5.5 A Generic Client; 5.6 An HTTP Client; 5.7 A POP Client; 5.8 A Simple Web Server; 5.9 A Proxy Server; 5.10 A Generic Multithreaded Server; 5.11 Sending Datagrams; 5.12 Receiving Datagrams; 5.13 Exercises; Chapter 6: New I/O; 6.1 Locking Files; 6.2 Copying Files; 6.3 Regular Expressions and Character Decoding; 6.4 File Copying with Buffers; 6.5 Advanced Byte-to-Character Conversion; 6.6 Tokenizing Byte Buffers; 6.7 A Simple HTTP Client; 6.8 The Daytime Service; 6.9 A Multiplexed Server; 6.10 A Multiplexed Network Client; 6.11 Exercises; Chapter 7: Security and Cryptography; 7.1 Running Untrusted Code; 7.2 Loading Untrusted Code; 7.3 Message Digests and Digital Signatures; 7.4 Cryptography; 7.5 Exercises; Chapter 8: Internationalization; 8.1 A Word About Locales; 8.2 Unicode; 8.3 Character Encodings; 8.4 Handling Local Customs; 8.5 Localizing User-Visible Messages; 8.6 Formatted Messages; 8.7 Exercises; Chapter 9: Reflection; 9.1 Obtaining Class and Member Information; 9.2 Invoking a Named Method; 9.3 Proxy Objects; 9.4 Exercises; Chapter 10: Object Serialization; 10.1 Simple Serialization; 10.2 Custom Serialization; 10.3 Externalizable Classes; 10.4 Serialization and Class Versioning; 10.5 Exercises; Part III: Desktop Java APIs; Chapter 11: Graphical User Interfaces; 11.1 Components; 11.2 Containers; 11.3 Layout Management; 11.4 Event Handling; 11.5 A Complete GUI; 11.6 Actions and Reflection; 11.7 Custom Dialogs; 11.8 An Error Handler Dialog; 11.9 Displaying Tables; 11.10 Displaying Trees; 11.11 A Simple Web Browser; 11.12 Describing GUIs with Properties; 11.13 Themes and the Metal Look-and-Feel; 11.14 Look-and-Feel Preferences; 11.15 The ShowBean Program; 11.16 Exercises; Chapter 12: Graphics; 12.1 Graphics Before Java 1.2; 12.2 The Java 2D API; 12.3 Drawing and Filling Shapes; 12.4 Transforms; 12.5 Line Styles with BasicStroke; 12.6 Stroking Lines; 12.7 Filling Shapes with Paint; 12.8 Antialiasing; 12.9 Combining Colors with AlphaComposite; 12.10 Image Processing; 12.11 Image I/O; 12.12 Custom Shapes; 12.13 Custom Strokes; 12.14 Custom Paint; 12.15 Advanced Animation; 12.16 Displaying Graphics Examples; 12.17 Exercises; Chapter 13: Printing; 13.1 Printing with the Java 1.1 API; 13.2 Printing with the Java 1.2 API; 13.3 Printing with the Java 1.4 API; 13.4 Printing Multipage Text Documents; 13.5 Advanced Printing with Java 1.4; 13.6 Exercises; Chapter 14: Data Transfer; 14.1 Simple Swing Data Transfer; 14.2 A Clock with Drag and Copy Support; 14.3 Data Transfer Architecture; 14.4 Dropping Multiple Datatypes; 14.5 A Transferable Shape; 14.6 Custom Data Transfer; 14.7 Exercises; Chapter 15: JavaBeans; 15.1 Bean Basics; 15.2 A Simple Bean; 15.3 A More Complex Bean; 15.4 Custom Events; 15.5 Specifying Bean Information; 15.6 Defining a Simple Property Editor; 15.7 Defining a Complex Property Editor; 15.8 Defining a Bean Customizer; 15.9 Manipulating Beans; 15.10 Exercises; Chapter 16: Applets; 16.1 Introduction to Applets; 16.2 A First Applet; 16.3 A Clock Applet; 16.4 A Timer Applet; 16.5 Applets and the Java 1.0 Event Model; 16.6 Exercises; Chapter 17: Sound; 17.1 Ringing the Bell; 17.2 Swing Aural Cues; 17.3 Playing Sounds with AudioClip; 17.4 Playing Sounds with javax.sound; 17.5 Streaming Sounds with javax.sound; 17.6 Synthesizing a MIDI Sequence; 17.7 Real-Time MIDI Sounds; 17.8 Exercises; Part IV: Enterprise Java APIs; Chapter 18: Database Access with SQL; 18.1 Accessing a Database; 18.2 Using Database Metadata; 18.3 Building a Database; 18.4 Using the API Database; 18.5 Atomic Transactions; 18.6 Exercises; Chapter 19: XML; 19.1 Parsing with JAXP and SAX; 19.2 Parsing and Manipulating with JAXP and DOM; 19.3 Transforming XML with XSLT; 19.4 An XML Pull Parser; 19.5 Exercises; Chapter 20: Servlets and JavaServer Pages; 20.1 Servlet Setup; 20.2 A Hello World Servlet; 20.3 Another Simple Servlet; 20.4 Servlet Initialization and Persistence: A Counter Servlet; 20.5 Hello JSP; 20.6 Hello JSP2; 20.7 Hello XML; 20.8 The MVC Paradigm for Web Applications; 20.9 ListManager Model Classes; 20.10 ListManager Controller; 20.11 ListManager Views; 20.12 Custom Tags in JSP 2.0; 20.13 Packaging a Web Application; 20.14 Exercises; Chapter 21: Remote Method Invocation; 21.1 Remote Banking; 21.2 A Bank Server; 21.3 A Persistent Bank Server; 21.4 A Multiuser Domain; 21.5 Remote MUD Interfaces; 21.6 The MUD Server; 21.7 The MudPlace Class; 21.8 The MudPerson Class; 21.9 A MUD Client; 21.10 Advanced RMI; 21.11 Exercises; Chapter 22: Example Index; 22.1 Symbols; 22.2 A; 22.3 B; 22.4 C; 22.5 D; 22.6 E; 22.7 F; 22.8 G; 22.9 H; 22.10 I; 22.11 J; 22.12 K; 22.13 L; 22.14 M; 22.15 N; 22.16 O; 22.17 P; 22.18 Q; 22.19 R; 22.20 S; 22.21 T; 22.22 U; 22.23 V; 22.24 W; 22.25 X; 22.26 Y; 22.27 Z; Colophon;
From the B&N Reads Blog

Customer Reviews