IN A NUTSHELL - NTUA

17 downloads 16729 Views 5MB Size Report
IN A NUTSHELL A Desktop Quick Reference Fourth Edition David Flanagan Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo
,TITLE.17168 Page iii Thursday, March 7, 2002 11:47 AM



IN A NUTSHELL A Desktop Quick Reference Fourth Edition

David Flanagan

Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo

,COPYRIGHT.16888 Page iv Thursday, March 7, 2002 11:46 AM

Java ™ in a Nutshell, Fourth Edition by David Flanagan Copyright © 2002, 1999, 1997, 1996 O’Reilly & Associates, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly & Associates, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly & Associates books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information contact our corporate/institutional sales department: (800) 998-9938 or [email protected].

Editors: Paula Ferguson and Robert Eckstein Production Editor: Matt Hutchinson Cover Designer: Edie Freedman Printing History: February 1996:

First Edition.

May 1997:

Second Edition.

November 1999: Third Edition. March 2002:

Fourth Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks and The Java™ Series is a trademark of O’Reilly & Associates, Inc. The association of the image of a Javan tiger with the topic of Java is a trademark of O’Reilly & Associates, Inc. Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. O’Reilly & Associates, Inc. is independent of Sun Microsystems. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly & Associates, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

ISBN: 0-596-00283-1 [M]

,AUTHOR.COLO.16750 Page 970 Thursday, March 7, 2002 11:46 AM

About the Author David Flanagan is a computer programmer who spends most of his time writing about Java and JavaScript. His other books with O’Reilly include Java Examples in a Nutshell, Java Foundation Classes in a Nutshell, and JavaScript: The Definitive Guide. 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 between the cities of Seattle, Washington and Vancouver, British Columbia.

Colophon Our look is the result of reader comments, our own experimentation, and feedback from distribution channels. Distinctive covers complement our distinctive approach to technical topics, breathing personality and life into potentially dry subjects. The animal on the cover of Java in a Nutshell, Fourth Edition is a Javan tiger. It is the smallest of the eight subspecies of tiger and has the longest cheek whiskers, which form a short mane across the neck. The encroachment of the growing human population, along with increases in poaching, have led to the near-extinction of the Javan tiger. The Indonesian government has become involved in trying to preserve the tiger. It is to be hoped that the remaining subspecies of tiger will be helped by increasing awareness and stricter protections. Tigers are the largest of all cats, weighing up to 660 pounds and with a body length of up to 9 feet. They are solitary animals and, unlike lions, hunt alone. Tigers prefer large prey, such as wild pigs, cattle, or deer. Tigers rarely attack humans, although attacks on humans have increased as the increasing human population more frequently comes into contact with tigers. Tiger attacks usually occur when the tiger feels that it or its young are being threatened. In such cases, the tiger almost never eats its human victim. There are some tigers, however, who have developed a taste for human flesh. This is a particularly bad problem in an area of India and Bangladesh called the Sunderbans. Matt Hutchinson was the production editor and copyeditor for Java in a Nutshell, Fourth Edition. Rachel Wheeler and Emily Quill provided quality control. Ellen Troutman-Zaig and Brenda Miller wrote the index. Lenny Muellner provided XML support. Edie Freedman designed the cover of this book, using a 19th-century engraving from the Dover Pictorial Archive. David Futato designed the interior layout based on a series design by Nancy Priest. The print version of this book was created by translating the DocBook XML markup of its source files into a set of gtroff macros using a filter developed at O’Reilly & Associates by Norman Walsh. Steve Talbott designed and wrote the underlying macro set on the basis of the GNU troff –gs macros; Lenny Muellner adapted them to XML and implemented the book design. The GNU groff text formatter Version 1.11.1 was used to generate PostScript output. The text and heading fonts are ITC Garamond Light and Garamond Book; the code font is Constant Willison. The hierarchy diagrams that appear in the quick-reference section of this book were produced in encapsulated PostScript format by a Java program written by David Flanagan. This colophon was written by Clairemarie Fisher O’Leary.

Table of Contents

Pr eface ............................................................................................... xiii

Part I: Introducing Java Chapter 1 —Intr oduction ................................................................. 3 What Is Java? ........................................................................................... 3 Key Benefits of Java ............................................................................... 6 An Example Program ............................................................................. 9

Chapter 2 —Java Syntax from the Ground Up ......................... 19 The Unicode Character Set ................................................................... Comments ............................................................................................. Identifiers and Reserved Words ........................................................... Primitive Data Types ............................................................................ Expressions and Operators .................................................................. Statements ............................................................................................. Methods ................................................................................................. Classes and Objects .............................................................................. Array Types ........................................................................................... Reference Types ................................................................................... Packages and the Java Namespace ...................................................... Java File Structure ................................................................................. Defining and Running Java Programs ................................................. Differences Between C and Java .........................................................

vii

7 March 2002 11:43

20 20 21 22 29 43 64 66 69 74 81 83 84 85

Chapter 3 —Object-Oriented Programming in Java ............... 88 The Members of a Class ....................................................................... 88 Creating and Initializing Objects .......................................................... 94 Destroying and Finalizing Objects ....................................................... 98 Subclasses and Inheritance ................................................................. 101 Data Hiding and Encapsulation ......................................................... 110 Abstract Classes and Methods ............................................................ 115 Interfaces ............................................................................................. 117 Inner Class Overview ......................................................................... 122 Static Member Classes ......................................................................... 124 Member Classes .................................................................................. 125 Local Classes ....................................................................................... 129 Anonymous Classes ............................................................................ 133 How Inner Classes Work .................................................................... 136 Modifier Summary ............................................................................... 138 C++ Features Not Found in Java ........................................................ 140

Chapter 4 —The Java Platform .................................................. 142 Java Platform Overview ...................................................................... Strings and Characters ........................................................................ Numbers and Math ............................................................................. Dates and Times ................................................................................. Arrays ................................................................................................... Collections ........................................................................................... Types, Reflection, and Dynamic Loading .......................................... Threads ................................................................................................ Files and Directories ........................................................................... Input and Output Streams .................................................................. Networking .......................................................................................... Properties and Preferences ................................................................. Logging ................................................................................................ The New I/O API ................................................................................ XML ...................................................................................................... Processes ............................................................................................. Security ................................................................................................ Cryptography ......................................................................................

viii

7 March 2002 11:43

Table of Contents

142 145 151 154 155 156 158 160 165 166 171 176 178 179 191 196 196 199

Chapter 5 —Java Security ............................................................ 202 Security Risks ...................................................................................... Java VM Security and Class File Verification ..................................... Authentication and Cryptography ...................................................... Access Control .................................................................................... Security for Everyone ......................................................................... Permission Classes ..............................................................................

202 203 204 204 207 209

Chapter 6 —JavaBeans ................................................................. 211 Bean Basics ......................................................................................... 212 JavaBeans Conventions ...................................................................... 214 Bean Contexts and Services ............................................................... 221

Chapter 7 —Java Programming and Documentation Conventions .............................................................................. 222 Naming and Capitalization Conventions ........................................... 222 Portability Conventions and Pure Java Rules .................................... 223 Java Documentation Comments ......................................................... 225

Chapter 8 —Java Development Tools ........................................ 234

7 March 2002 11:43

appletviewer ........................................................................................ extcheck .............................................................................................. jar ......................................................................................................... jarsigner ............................................................................................... java ....................................................................................................... javac ..................................................................................................... javadoc ................................................................................................ javah .................................................................................................... javap .................................................................................................... jdb ........................................................................................................ keytool ................................................................................................. native2ascii .......................................................................................... policytool ............................................................................................. serialver ...............................................................................................

234 238 238 241 242 248 251 257 259 260 265 268 269 270

Table of Contents

ix

Part II: API Quick Reference How to Use This Quick Reference ............................................... 273 Finding a Quick-Reference Entry ....................................................... 273 Reading a Quick-Reference Entry ...................................................... 274

Chapter 9 —java.beans and java.beans.beancontext .......... 282 Chapter 10 —java.io ..................................................................... 323 Chapter 11 —java.lang, java.lang.ref, and java.lang.reflect .............................................................. 374 Chapter 12 —java.math ............................................................... 444 Chapter 13 —java.net ................................................................... 448 Chapter 14 —java.nio and Subpackages ................................ 481 Chapter 15 —java.security and Subpackages ........................ 533 Chapter 16 —java.text .................................................................. 609 Chapter 17 —java.util and Subpackages ................................ 635 Chapter 18 —javax.crypto and Subpackages ......................... 738 Chapter 19 —javax.net and javax.net.ssl ............................... 762 Chapter 20 —javax.security.auth and Subpackages ............ 782 Chapter 21 —javax.xml.parsers, java.xml.transform, and Subpackages ..................................................................... 805 Chapter 22 —org.ietf.jgss ............................................................. 826

x

7 March 2002 11:43

Table of Contents

Chapter 23 —org.w3c.dom ......................................................... 833 Chapter 24 —org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers ......................................................... 848 Chapter 25 —Class, Method, and Field Index ........................ 871 Index ................................................................................................. 919

Table of Contents

7 March 2002 11:43

xi

7 March 2002 11:43

Preface

This book is a desktop quick reference for Java™ programmers, designed to sit faithfully by your keyboard while you program. Part I of the book is a fast-paced, “no-fluff” introduction to the Java programming language and the core APIs of the Java platform. Part II is a quick-reference section that succinctly details most classes and interfaces of those core APIs. The book covers Java 1.0, 1.1, 1.2, 1.3, and 1.4.

Changes in the Fourth Edition Once again, the Java platform has grown dramatically larger with the release of Java 1.4, and this book has grown in response. Some of the important new features of Java 1.4 (and of this book) are: Assert statement The Java language has been extended to support assertions with the assert statement. This new statement is documented in Chapter 2. JavaBeans persistence JavaBeans and related objects can now be serialized to XML documents. See java.beans.XMLEncoder in Chapter 9 for more information. New I/O API Java 1.4 includes a new API for high-performance, nonblocking file and network input and output. See the java.nio package and its subpackages in Chapter 14. Chapter 4 contains a number of examples of this important new API. Certification path API The java.security.cert package has been extended with new classes and interfaces for creating certificate chains, or “certification paths,” which are commonly used in network authentication.

xiii

7 March 2002 11:17

Logging API The new java.util.logging package defines a powerful and flexible logging framework for Java applications. Pr efer ences API java.util.prefs defines an API that allows applications to persistently store

and query user preference values and systemwide configuration options. Patter n matching with regular expressions One more new utility package, java.util.regex, provides support for textual pattern matching with Perl-style regular expressions. Secur e network sockets The Java Secure Sockets Extension (JSSE) API defined by the new javax.net and javax.net.ssl packages provides support for secure networking with the SSL and TLS protocols. Network authentication and authorization The Java Authentication and Authorization Service (JAAS) is defined by the javax.security.auth package and its subpackages. JAAS enables a Java application to securely establish the identity of a user and run code under a security policy based on the set of permissions granted to that user. XML parsing and transformations The Java API for XML Processing (JAXP) is defined by the javax.xml.parsers package and the javax.xml.transform package and subpackages. JAXP provides facilities for parsing XML documents using the SAX and DOM APIs and for transforming the content of those documents using XSLT. Along with JAXP, the DOM and SAX APIs have also been made part of the Java 1.4 platform. You’ll find them in the org.w3c.dom package in Chapter 23 and in the org.xml.sax package and subpackages in Chapter 24. You’ll find examples illustrating how to use most of these new APIs in Chapter 4. In addition to all the new content, there have been a few organizational changes to the book. In previous editions, the quick reference was organized with one package to a chapter. This edition documents 46 distinct packages, which would make for an excessive number of chapters. In this edition, therefore, related packages (those with a common prefix) are grouped into a single chapter, shortening the quick reference to a more manageable 15 chapters. Because the quick reference has a purely alphabetical organization, however, the chapter boundaries are largely irrelevant, and you can find what you need simply by flipping through the quick reference as you would flip through a dictionary or phone book. Another change caused by the dramatically increased number of packages is that I was forced to cut the package hierarchy figures that appeared at the start of each chapter in previous editions. These figures were all carefully hand-drawn and have become an increasingly large burden on the technical illustration staff at O’Reilly & Associates, Inc. Furthermore, the figures simply haven’t proven to be as useful as they once seemed. In this edition, I decided that the figures’ benefit simply didn’t justify their cost. If you are one of the minority of readers who was fond of those diagrams, I apologize for their removal.

xiv

7 March 2002 11:17

Preface

There are two new features of the quick reference that should compensate for the loss of the package hierarchy diagrams. First, the reference entry for each package now includes a listing of all interfaces and classes in the package. The entries in this list are grouped by category (interfaces, classes, and exceptions, for example) and by hierarchy. This listing, while not graphical, provides exactly the same information as the old hierarchy diagrams. Second, the class hierarchy subsection of each class and interface quick reference has been converted from an awkward textual format to an improved graphical format.

Contents of This Book The first eight chapters of this book document the Java language, the Java platform, and the Java development tools that are supplied with Sun’s Java SDK (software development kit). The first four chapters are essential; the next four cover topics of interest to some, but not all Java programmers. Chapter 1: Introduction This chapter is an overview of the Java language and the Java platform that explains the important features and benefits of Java. It concludes with an example Java program and walks the new Java programmer through it line by line. Chapter 2: Java Syntax From the Ground Up This chapter explains the details of the Java programming language. It is a long and detailed chapter. Experienced Java programmers can use it as a language reference. Programmers with substantial experience with languages such as C and C++ should be able to pick up Java syntax by reading this chapter. The chapter does not assume years of programming experience, however, and does not even require familiarity with C or C++. Even beginning programmers, with only a modest amount of experience should be able to learn Java programming by studying this chapter carefully. Chapter 3: Object-Oriented Programming in Java This chapter describes how the basic Java syntax documented in Chapter 2 is used to write object-oriented programs in Java. The chapter assumes no prior experience with OO programming. It can be used as a tutorial by new programmers or as a reference by experienced Java programmers. Chapter 4: The Java Platform This chapter is an overview of the essential Java APIs covered in this book. It contains numerous short examples that demonstrate how to perform common tasks with the classes and interfaces that comprise the Java platform. Programmers who are new to Java, and especially those who learn best by example, should find this a valuable chapter. Chapter 5: Java Security This chapter explains the Java security architecture that allows untrusted code to run in a secure environment from which it cannot do any malicious damage to the host system. It is important for all Java programmers to have at least a passing familiarity with Java security mechanisms.

Pr eface

7 March 2002 11:17

xv

Chapter 6: JavaBeans This chapter documents the JavaBeans™ component framework and explains what programmers need to know to create and use the reusable, embeddable Java classes known as beans. Chapter 7: Java Programming and Documentation Conventions This chapter documents important and widely adopted Java programming conventions and also explains how you can make your Java code self-documenting by including specially formatted documentation comments. Chapter 8: Java Development Tools The Java SDK shipped by Sun includes a number of useful Java development tools, most notably the Java interpreter and the Java compiler. This chapter documents those tools. These first eight chapters teach you the Java language and get you up and running with the Java APIs. The bulk of the book, however, is the API quick reference, Chapters 9 through 24, which is a succinct but detailed API reference formatted for optimum ease of use. Please be sure to read Chapter 1, which appears at the beginning of the reference section; it explains how to get the most out of this section. Also, please note that the quick-reference chapters are followed by one final chapter entitled “Class, Method, and Field Index”. This special index allows you to look up the name of a class and find the package it is defined in or look up the name of a method or field and find the class it is defined in.

Related Books O’Reilly publishes an entire series of books on Java programming, including several companion books to this one. The companion books are: Java Enterprise in a Nutshell This book is a succinct tutorial and quick reference for the Java “Enterprise” APIs such as JDBC, RMI, JNDI, and CORBA. Java Foundation Classes in a Nutshell This book is a tutorial and quick reference for the graphics, graphical user interface, and related APIs of the Java platform. It includes coverage of Applets, AWT, Java2D, and Swing. Java Examples in a Nutshell This book contains hundreds of complete, working examples illustrating many common Java programming tasks using the core, enterprise, and foundation classes APIs. Java Examples in a Nutshell is like Chapter 4 of this book, greatly expanded in breadth and depth, and with all the code snippets fully fleshed out into working examples. This is a particularly valuable book for readers who learn well by experimenting with existing code. J2ME in a Nutshell This book is a tutorial and quick reference for the graphics, networking, and database APIs of the Java 2 Micro Edition (J2ME) platform.

xvi

7 March 2002 11:17

Preface

You can find a complete list of Java books from O’Reilly at http://java.or eilly.com/. Books that focus on the core Java APIs, as this one does, include: Lear ning Java, by Pat Niemeyer and Jonathan Knudsen A comprehensive tutorial introduction to Java, with an emphasis on client-side Java programming. Java Threads, by Scott Oaks and Henry Wong Java makes multithreaded programming easy, but doing it right can still be tricky. This book explains everything you need to know. Java I/O, by Elliotte Rusty Harold Java’s stream-based input/output architecture is a thing of beauty. This book covers it in the detail it deserves. Java Network Programming, by Elliotte Rusty Harold This book documents the Java networking APIs in detail. Java Security, by Scott Oaks This book explains the Java access-control mechanisms in detail and also documents the authentication mechanisms of digital signatures and message digests. Java Cryptography, by Jonathan Knudsen Thorough coverage of the Java Cryptography Extension, the javax.crypto.* packages, and everything you need to know about cryptography in Java. Developing Java Beans, by Robert Englander A complete guide to writing components that work with the JavaBeans API.

Java Programming Resources Online This book is a quick reference designed for speedy access to frequently needed information. It does not, and cannot, tell you everything you need to know about Java. In addition to the books listed earlier, there are several valuable (and free) electronic sources of information about Java programming. Sun’s main web site for all things related to Java is http://java.sun.com/. The web site specifically for Java developers is http://developer.java.sun.com/. Much of the content on this developer site is password-protected, and access to it requires (free) registration. Sun distributes electronic documentation for all Java classes and methods in its javadoc HTML format. Although this documentation is somewhat difficult to navigate and is rough or outdated in places, it is still an excellent starting point when you need to know more about a particular Java package, class, method, or field. If you do not already have the javadoc files with your Java distribution, see http://java.sun.com/docs/ for a link to the latest available version. Sun also distributes its excellent Java Tutorial online. You can browse and download it from http://java.sun.com/docs/books/tutorial/. For Usenet discussion (in English) about Java, try the comp.lang.java.programmer and related comp.lang.java.* newsgroups. You can find the very comprehensive

Pr eface

7 March 2002 11:17

xvii

comp.lang.java.pr ogrammer FAQ by Peter van der Linden at http://www.afu.com/ javafaq.htm. Finally, don’t forget O’Reilly’s Java web site. http://java.or eilly.com/ contains Java news and commentary. The O’Reilly Network (www.or eillynet.com) includes the onjava.com site which has a focus on Enterprise Java.

Examples Online The examples in this book are available online and can be downloaded from the home page for the book at http://www.or eilly.com/catalog/javanut4. You also may want to visit this site to see if any important notes or errata about the book have been published there.

Conventions Used in This Book We use the following formatting conventions in this book: Italic Used for emphasis and to signify the first use of a term. Italic is also used for commands, email addresses, web sites, FTP sites, file and directory names, and newsgroups. Bold Occasionally used to refer to particular keys on a computer keyboard or to portions of a user interface, such as the Back button or the Options menu. Constant Width

Used in all Java code and generally for anything that you would type literally when programming, including keywords, data types, constants, method names, variables, class names, and interface names. Constant Width Italic

Used for the names of function arguments and generally as a placeholder to indicate an item that should be replaced with an actual value in your program. Franklin Gothic Book Condensed Used for the Java class synopses in the quick-reference section. This very narrow font allows us to fit a lot of information on the page without a lot of distracting line breaks. This font is also used for code entities in the descriptions in the quick-reference section. Franklin Gothic Demi Condensed Used for highlighting class, method, field, property, and constructor names in the quick-reference section, which makes it easier to scan the class synopses. Franklin Gothic Book Condensed Italic Used for method parameter names and comments in the quick-reference section.

xviii

7 March 2002 11:17

Preface

Request for Comments Please address comments and questions concerning this book to the publisher: O’Reilly & Associates, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international or local) (707) 829-1014 (fax) There is a web page for this book, which lists errata, examples, and any additional information. You can access this page at: http://www.or eilly.com/catalog/javanut4/ To ask technical questions or comment on this book, send email to: bookquestions@or eilly.com For more information about books, conferences, Resource Centers, and the O’Reilly Network, see the O’Reilly web site at: http://www.or eilly.com/

How the Quick Reference Is Generated For the curious reader, this section explains a bit about how the quick-reference material in Java in a Nutshell and related books is created. As Java has evolved, so has my system for generating Java quick-reference material. The current system is part of a larger commercial documentation browser system I’m developing (visit http://www.davidflanagan.com/Jude/ for more information about it). The program works in two passes: the first pass collects and organizes the API information, and the second pass outputs that information in the form of quick-reference chapters. The first pass begins by reading the class files for all of the classes and interfaces to be documented. Almost all of the API information in the quick reference is available in these class files. The notable exception is the names of method arguments, which are not stored in class files. These argument names are obtained by parsing the Java source file for each class and interface. Where source files are not available, I obtain method argument names by parsing the API documentation generated by javadoc. The parsers I use to extract API information from the source files and javadoc files are created using the Antlr parser generator developed by Terrence Parr of the Magelang Institute. (See http://www.antlr.org/ for details on this very powerful programming tool.) Once the API information has been obtained by reading class files, source files, and javadoc files, the program spends some time sorting and cross-referencing everything. Then it stores all the API information into a single large data file. The second pass reads API information from that data file and outputs quick-reference chapters using a custom XML doctype. Once I’ve generated the XML output, I

Pr eface

7 March 2002 11:17

xix

hand it off to the production team at O’Reilly. They process it and convert it to troff source code. The troff source is processed with the GNU groff program (ftp://ftp.gnu.org/gnu/groff/ ) and a custom set of troff macros to produce PostScript output that is shipped directly to the printer.

Acknowledgments Many people helped in the creation of this book, and I am grateful to them all. I am indebted to the many, many readers of the first three editions who wrote in with comments, suggestions, bug reports, and praise. Their many small contributions are scattered throughout the book. Also, my apologies to those who made the many good suggestions that could not be incorporated into this edition. Paula Ferguson, a friend and colleague, was the editor of the first three editions of this book. Her careful reading and always-practical suggestions have made the book stronger, clearer, and more useful. Paula’s editorial duties have moved her away from Java books and into Web programming books, and this fourth edition was edited by Bob Eckstein, a careful editor with a great sense of humor. The new material I wrote for this edition has been reviewed by a number of engineers at Sun, and often these engineers were the very ones who created or worked on the APIs for which they were reviewers. I am fortunate to have been able to go “straight to the source” for these reviews, and am very grateful to these engineers, who made time in their very busy schedules to read and comment on my drafts. In alphabetical order, the reviewers were: •

Josh Bloch, author of the excellent book Effective Java Programming Language Guide, reviewed the new material on assertions and the Preferences API.



Graham Hamilton reviewed the Logging API material.



Jonathan Knudsen (who is also an O’Reilly author) reviewed the JSSE and Certification Path material.



Charlie Lai reviewed the JAAS material.



Ram Marti reviewed the JGSS material.



Philip Milne, a former Sun employee, now at Dresdner Kleinwort Wasserstein, reviewed the material on the Java Beans persistence mechanism.



Mark Reinhold reviewed the java.nio material. Mark deserves special thanks for having been a reviewer for the second, third, and fourth editions of this book.



Andreas Sterbenz and Brad Wetmore reviewed the JSSE material.

In addition to these reviewers from Sun, Ron Hitchens reviewed my New I/O material, and my editor, Bob Eckstein, did double duty as the technical reviewer for the XML material. My sincere thanks to each of these gentlemen for their careful work. Any mistakes that remain in this book are, of course, my own.

xx

7 March 2002 11:17

Preface

The third edition also benefited greatly from the contributions of reviewers who are intimately familiar with the Java platform. Joshua Bloch, one of the primary authors of the Java collections framework, reviewed my descriptions of the collections classes and interfaces. Joshua was also helpful in discussing the Timer and TimerTask classes of Java 1.3 with me. Mark Reinhold, creator of the java.lang.ref package, explained the package to me and reviewed my documentation of it. Scott Oaks reviewed my descriptions of the Java security and cryptography classes and interfaces. Joshua, Mark, and Scott are all engineers with Sun Microsystems, and I’m very grateful for their time. The documentation of the javax.crypto package and its subpackages was also reviewed by Jon Eaves. Jon worked on a clean-room implementation of the Java Cryptography Extension (which is available from http://www.aba.net.au/ ), and his comments were quite helpful. Jon now works for Fluent Technologies (http://www.fluent.com.au/ ) consulting in Java and electronic commerce. Finally, Chapter 1 was improved by the comments of reviewers who were not already familiar with the Java platform: Christina Byrne reviewed it from the standpoint of a novice programmer, and Judita Byrne of Virginia Power offered her comments as a professional COBOL programmer. For the second edition, John Zukowski reviewed my Java 1.1 AWT quick-reference material, and George Reese reviewed most of the remaining new material. The second edition was also blessed with a “dream team” of technical reviewers from Sun. John Rose, the author of the Java inner class specification, reviewed the chapter on inner classes. Mark Reinhold, author of the new character stream classes in java.io, reviewed my documentation of these classes. Nakul Saraiya, the designer of the new Java Reflection API, reviewed my documentation of the java.lang.reflect package. I am very grateful to these engineers and architects; their efforts made this a stronger, more accurate book. Mike Loukides provided high-level direction and guidance for the first edition of the book. Eric Raymond and Troy Downing reviewed that first edition—they helped spot my errors and omissions and offered good advice on making the book more useful to Java programmers. The O’Reilly production team has done its usual fine work of creating a book out of the electronic files I submit. My thanks to them all. As always, my thanks and love to Christie. David Flanagan http://www.davidflanagan.com/ January 2002

Pr eface

7 March 2002 11:17

xxi

7 March 2002 11:17

PART I

Introducing Java Part I is an introduction to the Java language and the Java platform. These chapters provide enough information for you to get started using Java right away. Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter

7 March 2002 11:42

1, 2, 3, 4, 5, 6, 7, 8,

Intr oduction Java Syntax from the Ground Up Object-Oriented Programming in Java The Java Platform Java Security JavaBeans Java Programming and Documentation Conventions Java Development Tools

7 March 2002 11:42

Introduction

Welcome to Java. This chapter begins by explaining what Java is and describing some of the features that distinguish it from other programming languages. Then, as a tutorial introduction to the language, it walks you through a simple Java program you can type in, compile, and run.

What Is Java? In discussing Java, it is important to distinguish between the Java programming language, the Java Virtual Machine, and the Java platform. The Java programming language is the language in which Java applications (including applets, servlets, and JavaBeans components) are written. When a Java program is compiled, it is converted to byte codes that are the portable machine language of a CPU architecture known as the Java Virtual Machine (also called the Java VM or JVM). The JVM can be implemented directly in hardware, but it is usually implemented in the form of a software program that interprets and executes byte codes. The Java platform is distinct from both the Java language and Java VM. The Java platform is the predefined set of Java classes that exist on every Java installation; these classes are available for use by all Java programs. The Java platform is also sometimes referred to as the Java runtime environment or the core Java APIs (application programming interfaces). The Java platform can be extended with optional standard extensions. These extension APIs exist in some Java installations, but are not guaranteed to exist in all installations.

The Java Programming Language The Java programming language is a state-of-the-art, object-oriented language that has a syntax similar to that of C. The language designers strove to make the Java language powerful, but, at the same time, they tried to avoid the overly complex features that have bogged down other object-oriented languages, such as C++. By keeping the language simple, the designers also made it easier for programmers to write robust, bug-free code. As a result of its elegant design and next-generation

3

7 March 2002 11:17

Introduction

CHAPTER 1

features, the Java language has proved popular with programmers, who typically find it a pleasure to work with Java after struggling with more difficult, less powerful languages.

The Java Virtual Machine The Java Virtual Machine, or Java interpreter, is the crucial piece of every Java installation. By design, Java programs are portable, but they are only portable to platforms to which a Java interpreter has been ported. Sun ships VM implementations for its own Solaris operating system and for Microsoft Windows and Linux platforms. Many other vendors, including Apple and various commercial Unix vendors, provide Java interpreters for their platforms. The Java VM is not only for desktop systems, however. It has been ported to set-top boxes, and scaled-down versions are even available for hand-held devices that run Windows CE and PalmOS. Although interpreters are not typically considered high-performance systems, Java VM performance is remarkably good and has been improving steadily. Of particular note is a VM technology called just-in-time ( JIT) compilation, whereby Java byte codes are converted on-the-fly into native-platform machine language, boosting execution speed for code that is run repeatedly. Sun’s new Hotspot technology is a particularly good implementation of JIT compilation.

The Java Platform The Java platform is just as important as the Java programming language and the Java Virtual Machine. All programs written in the Java language rely on the set of predefined classes* that comprise the Java platform. Java classes are organized into related groups known as packages. The Java platform defines packages for functionality such as input/output, networking, graphics, user-interface creation, security, and much more. The Java 1.2 release was a major milestone for the Java platform. This release almost tripled the number of classes in the platform and introduced significant new functionality. In recognition of this, Sun named the new version the Java 2 Platform. This is a trademarked name created for marketing purposes; it serves to emphasize how much Java has grown since its first release. However, most programmers refer to the Java platform by its official version number, which, at the time of this writing, is 1.4. It is important to understand what is meant by the term platform. To a computer programmer, a platform is defined by the APIs he or she can rely on when writing programs. These APIs are usually defined by the operating system of the target computer. Thus, a programmer writing a program to run under Microsoft Windows must use a different set of APIs than a programmer writing the same program for the Macintosh or for a Unix-based system. In this respect, Windows, Macintosh, and Unix are three distinct platforms. * A class is a module of Java code that defines a data structure and a set of methods (also called procedures, functions, or subroutines) that operate on that data.

4

7 March 2002 11:17

Chapter 1 – Introduction

It also explains why companies like Microsoft might feel threatened by Java. The Java platform is not an operating system, but for programmers, it is an alternative development target and a very popular one at that. The Java platform reduces programmers’ reliance on the underlying operating system, and, by allowing programs to run on top of any operating system, it increases end users’ freedom to choose an operating system.

Versions of Java As of this writing, there have been five major versions of Java. They are: Java 1.0 This was the first public version of Java. It contained 212 classes organized in 8 packages. It was simple and elegant but is now completely outdated. Java 1.1 This release of Java doubled the size of the Java platform to 504 classes in 23 packages. It introduced inner classes, an important change to the Java language itself, and included significant performance improvements in the Java VM. There is a large installed base of web browsers that run Java 1.1, so although this version is outdated, it is still used for writing simple applets— Java programs that are included in web pages. See Java Foundation Classes in a Nutshell (O’Reilly) for a discussion of applets. Java 1.2 This was a very significant release of Java; it tripled the size of the Java platform to 1,520 classes in 59 packages. Important additions included the new Swing GUI API and a powerful and flexible Collections API for working with sets, lists, and maps of objects. Because of the many new features included in the 1.2 release, the platform was rebranded as “the Java 2 Platform.” Java 1.3 This was primarily a maintenance release, focused on bug fixes, stability, and performance improvements (including the high-performance “HotSpot” virtual machine). New additions to the platform included the JNDI and Java Sound APIs, which were previously available as extensions to the platform. The most interesting new classes are probably java.util.Timer and java.lang.reflect.Proxy. In total, Version 1.3 of the Java platform contains 1,842 classes in 76 packages.

What Is Java?

7 March 2002 11:17

5

Introduction

Java is not an operating system. Nevertheless, the Java platform provides APIs with a comparable breadth and depth to those defined by an operating system. With the Java platform, you can write applications in Java without sacrificing the advanced features available to programmers writing native applications targeted at a particular underlying operating system. An application written on the Java platform runs on any operating system that supports the Java platform. This means you do not have to create distinct Windows, Macintosh, and Unix versions of your programs, for example. A single Java program runs on all these operating systems, which explains why “Write once, run anywhere” is Sun’s motto for Java.

Java 1.4 This is another big release, adding important new functionality and increasing the size of the platform by 62% to 2,991 classes and interfaces in 135 packages. New features include a high-performance, low-level I/O API; support for pattern matching with regular expressions; a logging API; a user preferences API; new Collections classes; an XML-based persistence mechanism for JavaBeans; support for XML parsing using both the DOM and SAX APIs; user authentication with the JAAS API; support for secure network connections using the SSL protocol; support for cryptography; a new API for reading and writing image files; an API for network printing; a handful of new GUI components in the Swing API; and a simplified drag-and-drop architecture for Swing. In addition to these platform changes, the Java 1.4 release introduces an assert statement to the Java language. To work with Java 1.0 or Java 1.1, you must obtain the Java Development Kit ( JDK) for that release. As of Java 1.2, the JDK has been renamed and is now called a Software Development Kit (SDK), so we have the Java 2 SDK or, more precisely, the Java 2 SDK, Standard Edition, Version 1.4. Despite the new name, many programmers still refer to the development kit as the JDK. Don’t confuse the JDK (or SDK) with the Java Runtime Environment ( JRE). The JRE contains everything you need to run Java programs, but it does not contain the tools you need to develop Java programs (primarily the compiler). You should also be aware of the Java Plug-in, a version of the JRE that is designed to be integrated into the Netscape Navigator and Microsoft Internet Explorer web browsers. In addition to the Standard Edition of Java used by most Java developers and documented in this book, Sun has also released the Java 2 Platform, Enterprise Edition (or J2EE) for enterprise developers and the Java 2 Platform, Micro Edition (J2ME) for consumer electronic systems, such as handheld PDAs and cellular telephones. See Java Enterprise in a Nutshell and Java Micro Edition in a Nutshell (both by O’Reilly) for more information on these other editions.

Key Benefits of Java Why use Java at all? Is it worth learning a new language and a new platform? This section explores some of the key benefits of Java.

Write Once, Run Anywhere Sun identifies “Write once, run anywhere” as the core value proposition of the Java platform. Translated from business jargon, this means that the most important promise of Java technology is that you only have to write your application once— for the Java platform—and then you’ll be able to run it anywher e. Anywhere, that is, that supports the Java platform. Fortunately, Java support is becoming ubiquitous. It is integrated, or being integrated, into practically all major operating systems. It is built into the popular web browsers, which places it on virtually every Internet-connected PC in the world. It is even being built into consumer electronic devices, such as television set-top boxes, PDAs, and cell phones.

6

7 March 2002 11:17

Chapter 1 – Introduction

Security

Java 1.2 took the security model a step further. It made security levels and restrictions highly configurable and extended them beyond applets. As of Java 1.2, any Java code, whether it is an applet, a servlet, a JavaBeans component, or a complete Java application, can be run with restricted permissions that prevent it from doing harm to the host system. The security features of the Java language and platform have been subjected to intense scrutiny by security experts around the world. In the earlier days of Java, security-related bugs, some of them potentially serious, were found and promptly fixed. Because of the strong security promises Java makes, it is big news when a new security bug is found. No other mainstream platform can make security guarantees nearly as strong as those Java makes. No one can say that Java security holes will not be found in the future, but if Java’s security is not yet perfect, it has been proven strong enough for practical day-to-day use and is certainly better than any of the alternatives.

Network-Centric Programming Sun’s corporate motto has always been “The network is the computer.” The designers of the Java platform believed in the importance of networking and designed the Java platform to be network-centric. From a programmer’s point of view, Java makes it easy to work with resources across a network and to create network-based applications using client/server or multitier architectures.

Dynamic, Extensible Programs Java is both dynamic and extensible. Java code is organized in modular object-oriented units called classes. Classes are stored in separate files and are loaded into the Java interpreter only when needed. This means that an application can decide as it is running what classes it needs and can load them when it needs them. It also means that a program can dynamically extend itself by loading the classes it needs to expand its functionality. The network-centric design of the Java platform means that a Java application can dynamically extend itself by loading new classes over a network. An application that takes advantage of these features ceases to be a monolithic block of code. Instead, it becomes an interacting collection of independent software components. Thus, Java enables a powerful new metaphor of application design and development.

Key Benefits of Java

7 March 2002 11:17

7

Introduction

Another key benefit of Java is its security features. Both the language and the platform were designed from the ground up with security in mind. The Java platform allows users to download untrusted code over a network and run it in a secure environment in which it cannot do any harm: untrusted code cannot infect the host system with a virus, cannot read or write files from the hard drive, and so forth. This capability alone makes the Java platform unique.

Internationalization The Java language and the Java platform were designed from the start with the rest of the world in mind. When it was created, Java was the only commonly used programming language that had internationalization features at its core, rather than tacked on as an afterthought. While most programming languages use 8-bit characters that represent only the alphabets of English and Western European languages, Java uses 16-bit Unicode characters that represent the phonetic alphabets and ideographic character sets of the entire world. Java’s internationalization features are not restricted to just low-level character representation, however. The features permeate the Java platform, making it easier to write internationalized programs with Java than it is with any other environment.

Performance As described earlier, Java programs are compiled to a portable intermediate form known as byte codes, rather than to native machine-language instructions. The Java Virtual Machine runs a Java program by interpreting these portable byte-code instructions. This architecture means that Java programs are faster than programs or scripts written in purely interpreted languages, but they are typically slower than C and C++ programs compiled to native machine language. Keep in mind, however, that although Java programs are compiled to byte code, not all of the Java platform is implemented with interpreted byte codes. For efficiency, computationally intensive portions of the Java platform—such as the string-manipulation methods — are implemented using native machine code. Although early releases of Java suffered from performance problems, the speed of the Java VM has improved dramatically with each new release. The VM has been highly tuned and optimized in many significant ways. Furthermore, most current implementations include a just-in-time (JIT) compiler, which converts Java byte codes to native machine instructions on the fly. Using sophisticated JIT compilers, Java programs can execute at speeds comparable to the speeds of native C and C++ applications. Java is a portable, interpreted language; Java programs run almost as fast as native, non-portable C and C++ programs. Performance used to be an issue that made some programmers avoid using Java. Now, with the improvements made in Java 1.2, 1.3 and 1.4, performance issues should no longer keep anyone away.

Programmer Efficiency and Time-to-Market The final, and perhaps most important, reason to use Java is that programmers like it. Java is an elegant language combined with a powerful and (usually) welldesigned set of APIs. Programmers enjoy programming in Java and are often amazed at how quickly they can get results with it. Because Java is a simple and elegant language with a well-designed, intuitive set of APIs, programmers write better code with fewer bugs than for other platforms, again reducing development time.

8

7 March 2002 11:17

Chapter 1 – Introduction

An Example Program

Example 1−1. Factorial.java: a program to compute factorials 1 /** 2 * This program computes the factorial of a number 3 */ 4 public class Factorial { // Define a class 5 public static void main(String[] args) { // The program starts here 6 int input = Integer.parseInt(args[0]); // Get the user's input 7 double result = factorial(input); // Compute the factorial 8 System.out.println(result); // Print out the result 9 } // The main() method ends here 10 11 public static double factorial(int x) { // This method computes x! 12 if (x < 0) // Check for bad input 13 return 0.0; // If bad, return 0 14 double fact = 1.0; // Begin with an initial value 15 while(x > 1) { // Loop until x equals 1 16 fact = fact * x; // Multiply by x each time 17 x = x - 1; // And then decrement x 18 } // Jump back to start of loop 19 return fact; // Return the result 20 } // factorial() ends here 21 } // The class ends here

Compiling and Running the Program Before we look at how the program works, we must first discuss how to run it. In order to compile and run the program, you need a Java software development kit (SDK) of some sort. Sun Microsystems created the Java language and ships a free Java SDK for its Solaris operating system and also for Linux and Microsoft Windows platforms. At the time of this writing, the current version of Sun’s SDK is entitled Java 2 SDK, Standard Edition, Version 1.4 and is available for download from http://java.sun.com/. Be sure to get the SDK and not the Java Runtime Environment. The JRE enables you to run existing Java programs, but not to write and compile your own. Sun supports its SDK only on Solaris, Linux, and Windows platforms. Many other companies have licensed and ported the SDK to their platforms, however. Contact your operating-system vendor to find if a version of the Java SDK is available for your system. The Sun SDK is not the only Java programming environment you can use. Companies such as Borland, Inprise, Metrowerks, Oracle, Sybase, and Symantec offer commercial products that enable you to write Java programs. This book assumes * The factorial of an integer is the product of the number and all positive integers less than the number. So, for example, the factorial of 4, which is also written 4!, is 4 times 3 times 2 times 1, or 24. By definition, 0! is 1.

An Example Program

7 March 2002 11:17

9

Introduction

Example 1-1 shows a Java program to compute factorials.* The numbers at the beginning of each line are not part of the program; they are there for ease of reference when we dissect the program line-by-line.

that you are using Sun’s SDK. If you are using a product from some other vendor, be sure to read that vendor’s documentation to learn how to compile and run a simple program, like that shown in Example 1-1. Once you have a Java programming environment installed, the first step towards running our program is to type it in. Using your favorite text editor, enter the program as it is shown in Example 1-1. Omit the line numbers, as they are just there for reference. Note that Java is a case-sensitive language, so you must type lowercase letters in lowercase and uppercase letters in uppercase. You’ll notice that many of the lines of this program end with semicolons. It is a common mistake to forget these characters, but the program won’t work without them, so be careful! If you are not a fast typist, you can omit everything from // to the end of a line. Those are comments ; they are there for your benefit and are ignored by Java.* When writing Java programs, you should use a text editor that saves files in plaintext format, not a word processor that supports fonts and formatting and saves files in a proprietary format. My favorite text editor on Unix systems is emacs. If you use a Windows system, you might use Notepad or WordPad, if you don’t have a more specialized programmer’s editor. If you are using a commercial Java programming environment, it probably includes an appropriate text editor; read the documentation that came with the product. When you are done entering the program, save it in a file named Factorial.java. This is important; the program will not work if you save it by any other name. After writing a program like this one, the next step is to compile it. With Sun’s SDK, the Java compiler is known as javac. javac is a command-line tool, so you can only use it from a terminal window, such as an MS-DOS window on a Windows system or an xter m window on a Unix system. Compile the program by typing the following command line:† C:\> javac Factorial.java

If this command prints any error messages, you probably got something wrong when you typed in the program. If it does not print any error messages, however, the compilation has succeeded, and javac creates a file called Factorial.class. This is the compiled version of the program. Once you have compiled a Java program, you must still run it. Unlike some other languages, Java programs are not compiled into native machine language, so they cannot be executed directly by the system. Instead, they are run by another program known as the Java interpreter. In Sun’s SDK, the interpreter is a commandline program named, appropriately enough, java. To run the factorial program, type: C:\> java Factorial 4

* I recommend that you type this example in by hand, to get a feel for the language. If you really don’t want to, however, you can download this, and all examples in the book, from http://www.or eilly.com/ catalog/javanut4/. † The “C:\>” characters represent the command-line prompt; don’t type these characters yourself.

10

7 March 2002 11:17

Chapter 1 – Intr oduction

C:\> java Factorial 4 24.0

Congratulations! You’ve just written, compiled, and run your first Java program. Try running it again to compute the factorials of some other numbers.

Analyzing the Program Now that you have run the factorial program, let’s analyze it line by line, to see what makes a Java program tick.

Comments The first three lines of the program are a comment. Java ignores them, but they tell a human programmer what the program does. A comment begins with the characters /* and ends with the characters */. Any amount of text, including multiple lines of text, may appear between these characters. Java also supports another type of comment, which you can see in lines 4 through 21. If the characters // appear in a Java program, Java ignores those characters and any other text that appears between those characters and the end of the line.

Defining a class Line 4 is the beginning of the program. It says that we are defining a class named Factorial. This explains why the program had to be stored in a file named Facto-

rial.java. That filename indicates that the file contains Java source code for a class named Factorial. The word public is a modifier ; it says that the class is publicly available and that anyone may use it. The open curly-brace character ({) marks the beginning of the body of the class, which extends all the way to line 21, where we find the matching close curly-brace character (}). The program contains a number of pairs of curly braces; the lines are indented to show the nesting within these braces. A class is the fundamental unit of program structure in Java, so it is not surprising that the first line of our program declares a class. All Java programs are classes, although some programs use many classes instead of just one. Java is an objectoriented programming language, and classes are a fundamental part of the objectoriented paradigm. Each class defines a unique kind of object. Example 1-1 is not really an object-oriented program, however, so I’m not going to go into detail about classes and objects here. That is the topic of Chapter 3. For now, all you need to understand is that a class defines a set of interacting members. Those members may be fields, methods, or other classes. The Factorial class contains two members, both of which are methods. They are described in upcoming sections.

An Example Program

7 March 2002 11:17

11

Introduction

java is the command to run the Java interpreter, Factorial is the name of the Java program we want the interpreter to run, and 4 is the input data—the number we want the interpreter to compute the factorial of. The program prints a single line of output, telling us that the factorial of 4 is 24:

Defining a method Line 5 begins the definition of a method of our Factorial class. A method is a named chunk of Java code. A Java program can call, or invoke, a method to execute the code in it. If you have programmed in other languages, you have probably seen methods before, but they may have been called functions, procedures, or subroutines. The interesting thing about methods is that they have parameters and retur n values. When you call a method, you pass it some data you want it to operate on, and it returns a result to you. A method is like an algebraic function: y = f(x)

Here, the mathematical function f performs some computation on the value represented by x and returns a value, which we represent by y. To return to line 5, the public and static keywords are modifiers. public means the method is publicly accessible; anyone can use it. The meaning of the static modifier is not important here; it is explained in Chapter 3. The void keyword specifies the return value of the method. In this case, it specifies that this method does not have a return value. The word main is the name of the method. main is a special name. When you run the Java interpreter, it reads in the class you specify, then looks for a method named main().* When the interpreter finds this method, it starts running the program at that method. When the main() method finishes, the program is done, and the Java interpreter exits. In other words, the main() method is the main entry point into a Java program. It is not actually sufficient for a method to be named main(), however. The method must be declared public static void exactly as shown in line 5. In fact, the only part of line 5 you can change is the word args, which you can replace with any word you want. You’ll be using this line in all of your Java programs, so go ahead and commit it to memory now!† Following the name of the main() method is a list of method parameters, contained in parentheses. This main() method has only a single parameter. String[] specifies the type of the parameter, which is an array of strings (i.e., a numbered list of strings of text). args specifies the name of the parameter. In the algebraic equation f(x), x is simply a way of referring to an unknown value. args serves the same purpose for the main() method. As we’ll see, the name args is used in the body of the method to refer to the unknown value that is passed to the method.

* By convention, when this book refers to a method, it follows the name of the method by a pair of parentheses. As you’ll see, parentheses are an important part of method syntax, and they serve here to keep method names distinct from the names of classes, fields, variables, and so on. † All Java programs that are run directly by the Java interpreter must have a main() method. Programs of this sort are often called applications. It is possible to write programs that are not run directly by the interpreter, but are dynamically loaded into some other already running Java program. Examples are applets, which are programs run by a web browser, and servlets, which are programs run by a web server. Applets are discussed in Java Foundation Classes in a Nutshell (O’Reilly), while servlets are discussed in Java Enterprise in a Nutshell (O’Reilly). In this book, we consider only applications.

12

7 March 2002 11:17

Chapter 1 – Intr oduction

C:\> java Factorial 4

the string “4” is passed to the main() method as the value of the parameter named args. More precisely, an array of strings containing only one entry, “4”, is passed to main(). If we invoke the program like this: C:\> java Factorial 4 3 2 1

then an array of four strings, “4”, “3”, “2”, and “1”, are passed to the main() method as the value of the parameter named args. Our program looks only at the first string in the array, so the other strings are ignored. Finally, the last thing on line 5 is an open curly brace. This marks the beginning of the body of the main() method, which continues until the matching close curly brace on line 9. Methods are composed of statements, which the Java interpreter executes in sequential order. In this case, lines 6, 7, and 8 are three statements that compose the body of the main() method. Each statement ends with a semicolon to separate it from the next. This is an important part of Java syntax; beginning programmers often forget the semicolons.

Declaring a variable and parsing input The first statement of the main() method, line 6, declares a variable and assigns a value to it. In any programming language, a variable is simply a symbolic name for a value. We’ve already seen that in this program the name args refers to the parameter value passed to the main() method. Method parameters are one type of variable. It is also possible for methods to declare additional “local” variables. Methods can use local variables to store and reference the intermediate values they use while performing their computations. This is exactly what we are doing on line 6. That line begins with the words int input, which declare a variable named input and specify that the variable has the type int; that is, it is an integer. Java can work with several different types of values, including integers, real or floating-point numbers, characters (e.g., letters and digits), and strings of text. Java is a strongly typed language, which means that all variables must have a type specified and can refer only to values of that type. Our input variable always refers to an integer; it cannot refer to a floating-point number or a string. Method parameters are also typed. Recall that the args parameter had a type of String[]. Continuing with line 6, the variable declaration int input is followed by the = character. This is the assignment operator in Java; it sets the value of a variable. When reading Java code, don’t read = as “equals,” but instead read it as “is assigned the value.” As we’ll see in Chapter 2, there is a different operator for “equals.” The value being assigned to our input variable is Integer.parseInt(args[0]). This is a method invocation. This first statement of the main() method invokes another method whose name is Integer.parseInt(). As you might guess, this

An Example Program

7 March 2002 11:17

13

Introduction

As I’ve just explained, the main() method is a special one that is called by the Java interpreter when it starts running a Java class (program). When you invoke the Java interpreter like this:

method “parses” an integer; that is, it converts a string representation of an integer, such as “4”, to the integer itself. The Integer.parseInt() method is not part of the Java language, but it is a core part of the Java API or Application Programming Interface. Every Java program can use the powerful set of classes and methods defined by this core API. The second half of this book is a quick reference that documents that core API. When you call a method, you pass values (called arguments) that are assigned to the corresponding parameters defined by the method, and the method returns a value. The argument passed to Integer.parseInt() is args[0]. Recall that args is the name of the parameter for main(); it specifies an array (or list) of strings. The elements of an array are numbered sequentially, and the first one is always numbered 0. We only care about the first string in the args array, so we use the expression args[0] to refer to that string. Thus, when we invoke the program as shown earlier, line 6 takes the first string specified after the name of the class, “4”, and passes it to the method named Integer.parseInt(). This method converts the string to the corresponding integer and returns the integer as its return value. Finally, this returned integer is assigned to the variable named input.

Computing the result The statement on line 7 is a lot like the statement on line 6. It declares a variable and assigns a value to it. The value assigned to the variable is computed by invoking a method. The variable is named result, and it has a type of double. double means a double-precision floating-point number. The variable is assigned a value that is computed by the factorial() method. The factorial() method, however, is not part of the standard Java API. Instead, it is defined as part of our program, by lines 11 through 19. The argument passed to factorial() is the value referred to by the input variable, which was computed on line 6. We’ll consider the body of the factorial() method shortly, but you can surmise from its name that this method takes an input value, computes the factorial of that value, and returns the result.

Displaying output Line 8 simply calls a method named System.out.println(). This commonly used method is part of the core Java API; it causes the Java interpreter to print out a value. In this case, the value that it prints is the value referred to by the variable named result. This is the result of our factorial computation. If the input variable holds the value 4, the result variable holds the value 24, and this line prints out that value. The System.out.println() method does not have a return value, so there is no variable declaration or = assignment operator in this statement, since there is no value to assign to anything. Another way to say this is that, like the main() method of line 5, System.out.println() is declared void.

The end of a method Line 9 contains only a single character, }. This marks the end of the method. When the Java interpreter gets here, it is done executing the main() method, so it

14

7 March 2002 11:17

Chapter 1 – Intr oduction

Blank lines Line 10 is a blank line. You can insert blank lines, spaces, and tabs anywhere in a program, and you should use them liberally to make the program readable. A blank line appears here to separate the main() method from the factorial() method that begins on line 11. You’ll notice that the program also uses spaces and tabs to indent the various lines of code. This kind of indentation is optional; it emphasizes the structure of the program and greatly enhances the readability of the code.

Another method Line 11 begins the definition of the factorial() method that was used by the main() method. Compare this line to line 5 to note its similarities and differences. The factorial() method has the same public and static modifiers. It takes a single integer parameter, which we call x. Unlike the main() method, which had no return value (void), factorial() returns a value of type double. The open curly brace marks the beginning of the method body, which continues past the nested braces on lines 15 and 18 to line 20, where the matching close curly brace is found. The body of the factorial() method, like the body of the main() method, is composed of statements, which are found on lines 12 through 19.

Checking for valid input In the main() method, we saw variable declarations, assignments, and method invocations. The statement on line 12 is different. It is an if statement, which executes another statement conditionally. We saw earlier that the Java interpreter executes the three statements of the main() method one after another. It always executes them in exactly that way, in exactly that order. An if statement is a flowcontrol statement; it can affect the way the interpreter runs a program. The if keyword is followed by a parenthesized expression and a statement. The Java interpreter first evaluates the expression. If it is true, the interpreter executes the statement. If the expression is false, however, the interpreter skips the statement and goes to the next one. The condition for the if statement on line 12 is x < 0. It checks whether the value passed to the factorial() method is less than zero. If it is, this expression is true, and the statement on line 13 is executed. Line 12 does not end with a semicolon because the statement on line 13 is part of the if statement. Semicolons are required only at the end of a statement. Line 13 is a return statement. It says that the return value of the factorial() method is 0.0. return is also a flow-control statement. When the Java interpreter sees a return, it stops executing the current method and returns the specified value immediately. A return statement can stand alone, but in this case, the

An Example Program

7 March 2002 11:17

15

Introduction

stops running. The end of the main() method is also the end of the variable scope for the input and result variables declared within main() and for the args parameter of main(). These variable and parameter names have meaning only within the main() method and cannot be used elsewhere in the program, unless other parts of the program declare different variables or parameters that happen to have the same name.

return statement is part of the if statement on line 12. The indentation of line 13

helps emphasize this fact. (Java ignores this indentation, but it is very helpful for humans who read Java code!) Line 13 is executed only if the expression on line 12 is true. Before we move on, we should pull back a bit and talk about why lines 12 and 13 are necessary in the first place. It is an error to try to compute a factorial for a negative number, so these lines make sure that the input value x is valid. If it is not valid, they cause factorial() to return a consistent invalid result, 0.0.

An important variable Line 14 is another variable declaration; it declares a variable named fact of type double and assigns it an initial value of 1.0. This variable holds the value of the factorial as we compute it in the statements that follow. In Java, variables can be declared anywhere; they are not restricted to the beginning of a method or block of code.

Looping and computing the factorial Line 15 introduces another type of statement: the while loop. Like an if statement, a while statement consists of a parenthesized expression and a statement. When the Java interpreter sees a while statement, it evaluates the associated expression. If that expression is true, the interpreter executes the statement. The interpreter repeats this process, evaluating the expression and executing the statement if the expression is true, until the expression evaluates to false. The expression on line 15 is x > 1, so the while statement loops while the parameter x holds a value that is greater than 1. Another way to say this is that the loop continues until x holds a value less than or equal to 1. We can assume from this expression that if the loop is ever going to terminate, the value of x must somehow be modified by the statement that the loop executes. The major difference between the if statement on lines 12–13 and the while loop on lines 15–18 is that the statement associated with the while loop is a compound statement. A compound statement is zero or more statements grouped between curly braces. The while keyword on line 15 is followed by an expression in parentheses and then by an open curly brace. This means that the body of the loop consists of all statements between that opening brace and the closing brace on line 18. Earlier in the chapter, I said that all Java statements end with semicolons. This rule does not apply to compound statements, however, as you can see by the lack of a semicolon at the end of line 18. The statements inside the compound statement (lines 16 and 17) do end with semicolons, of course. The body of the while loop consists of the statements on line 16 and 17. Line 16 multiplies the value of fact by the value of x and stores the result back into fact. Line 17 is similar. It subtracts 1 from the value of x and stores the result back into x. The * character on line 16 is important: it is the multiplication operator. And, as you can probably guess, the – on line 17 is the subtraction operator. An operator is a key part of Java syntax: it performs a computation on one or two operands to produce a new value. Operands and operators combine to form expr essions, such as fact * x or x – 1. We’ve seen other operators in the program. Line 15, for

16

7 March 2002 11:17

Chapter 1 – Intr oduction

To understand this while loop, it is helpful to think like the Java interpreter. Suppose we are trying to compute the factorial of 4. Before the loop starts, fact is 1.0, and x is 4. After the body of the loop has been executed once—after the first iteration— fact is 4.0, and x is 3. After the second iteration, fact is 12.0, and x is 2. After the third iteration, fact is 24.0, and x is 1. When the interpreter tests the loop condition after the third iteration, it finds that x > 1 is no longer true, so it stops running the loop, and the program resumes at line 19.

Returning the result Line 19 is another return statement, like the one we saw on line 13. This one does not return a constant value like 0.0, but instead returns the value of the fact variable. If the value of x passed into the factorial() function is 4, then, as we saw earlier, the value of fact is 24.0, so this is the value returned. Recall that the factorial() method was invoked on line 7 of the program. When this return statement is executed, control returns to line 7, where the return value is assigned to the variable named result.

Exceptions If you’ve made it all the way through the line-by-line analysis of Example 1-1, you are well on your way to understanding the basics of the Java language.* It is a simple but nontrivial program that illustrates many of the features of Java. There is one more important feature of Java programming I want to introduce, but it is one that does not appear in the program listing itself. Recall that the program computes the factorial of the number you specify on the command line. What happens if you run the program without specifying a number? C:\> java Factorial java.lang.ArrayIndexOutOfBoundsException: 0 at Factorial.main(Factorial.java:6) C:\>

And what happens if you specify a value that is not a number? C:\> java Factorial ten java.lang.NumberFormatException: ten at java.lang.Integer.parseInt(Integer.java) at java.lang.Integer.parseInt(Integer.java) at Factorial.main(Factorial.java:6) C:\>

* If you didn’t understand all the details of this factorial program, don’t worry. We’ll cover the details of the Java language a lot more thoroughly in Chapter 2 and Chapter 3. However, if you feel like you didn’t understand any of the line-by-line analysis, you may also find that the upcoming chapters are over your head. In that case, you should probably go elsewhere to learn the basics of the Java language and return to this book to solidify your understanding, and, of course, to use as a reference. One resource you may find useful in learning the language is Sun’s online Java tutorial, available at http://java.sun.com/docs/books/tutorial/.

An Example Program

7 March 2002 11:17

17

Introduction

example, uses the greater-than operator (>) in the expression x > 1, which compares the value of the variable x to 1. The value of this expression is a boolean truth value—either true or false, depending on the result of the comparison.

In both cases, an error occurs or, in Java terminology, an exception is thrown. When an exception is thrown, the Java interpreter prints out a message that explains what type of exception it was and where it occurred (both exceptions above occurred on line 6). In the first case, the exception is thrown because there are no strings in the args list, meaning we asked for a nonexistent string with args[0]. In the second case, the exception is thrown because Integer.parseInt() cannot convert the string “ten” to a number. We’ll see more about exceptions in Chapter 2 and learn how to handle them gracefully as they occur.

18

7 March 2002 11:17

Chapter 1 – Intr oduction

CHAPTER 2

This chapter is a terse but comprehensive introduction to Java syntax. It is written primarily for readers who are new to the language, but have at least some previous programming experience. Determined novices with no prior programming experience may also find it useful. If you already know Java, you should find it a useful language reference. In previous editions of this book, this chapter was written explicitly for C and C++ programmers making the transition to Java. It has been rewritten for this edition to make it more generally useful, but it still contains comparisons to C and C++ for the benefit of programmers coming from those languages.* This chapter documents the syntax of Java programs by starting at the very lowest level of Java syntax and building from there, covering increasingly higher orders of structure. It covers: •

The characters used to write Java programs and the encoding of those characters.



Data types, literal values, identifiers, and other tokens that comprise a Java program.



The operators used in Java to group individual tokens into larger expressions.



Statements, which group expressions and other statements to form logical chunks of Java code.



Methods (also called functions, procedures, or subroutines), which are named collections of Java statements that can be invoked by other Java code.

* Readers who want even more thorough coverage of the Java language should consider The Java Programming Language, Second Edition, by Ken Arnold and James Gosling (the creator of Java) (Addison Wesley Longman). And hardcore readers may want to go straight to the primary source: The Java Language Specification, by James Gosling, Bill Joy, and Guy Steele (Addison Wesley Longman). This specification is available in printed book form, but is also freely available for download from Sun’s web site at http://java.sun.com/docs/books/jls/. I found both documents quite helpful while writing this chapter.

19

7 March 2002 11:18

Java Syntax

Java Syntax from the Ground Up



Classes, which are collections of methods and fields. Classes are the central program element in Java and form the basis for object-oriented programming. Chapter 3 is devoted entirely to a discussion of classes and objects.



Packages, which are collections of related classes.



Java programs, which consist of one or more interacting classes that may be drawn from one or more packages.

The syntax of most programming languages is complex, and Java is no exception. In general, it is not possible to document all elements of a language without referring to other elements that have not yet been discussed. For example, it is not really possible to explain in a meaningful way the operators and statements supported by Java without referring to objects. But it is also not possible to document objects thoroughly without referring to the operators and statements of the language. The process of learning Java, or any language, is therefore an iterative one. If you are new to Java (or a Java-style programming language), you may find that you benefit greatly from working through this chapter and the next twice, so that you can grasp the interrelated concepts.

The Unicode Character Set Java programs are written using the Unicode character set. Unlike the 7-bit ASCII encoding, which is useful only for English, and the 8-bit ISO Latin-1 encoding, which is useful only for major Western European languages, the 16-bit Unicode encoding can represent virtually every written language in common use on the planet. Very few text editors support Unicode, however, and in practice, most Java programs are written in plain ASCII. 16-bit Unicode characters are typically written to files using an encoding known as UTF-8, which converts the 16-bit characters into a stream of bytes. The format is designed so that plain ASCII and Latin-1 text are valid UTF-8 byte streams. Thus, you can simply write plain ASCII programs, and they will work as valid Unicode. If you want to embed a Unicode character within a Java program that is written in plain ASCII, use the special Unicode escape sequence \uxxxx. That is, a backslash and a lowercase u, followed by four hexadecimal characters. For example, \u0020 is the space character, and \u03c0 is the character π. You can use Unicode characters anywhere in a Java program, including comments and variable names.

Comments Java supports three types of comments. The first type is a single-line comment, which begins with the characters // and continues until the end of the current line. For example: int i = 0;

// Initialize the loop variable

The second kind of comment is a multiline comment. It begins with the characters /* and continues, over any number of lines, until the characters */. Any text between the /* and the */ is ignored by the Java compiler. Although this style of

20

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

comment is typically used for multiline comments, it can also be used for singleline comments. This type of comment cannot be nested (i.e., one /* */ comment cannot appear within another one). When writing multiline comments, programmers often use extra * characters to make the comments stand out. Here is a typical multiline comment:

The third type of comment is a special case of the second. If a comment begins with /**, it is regarded as a special doc comment. Like regular multiline comments, doc comments end with */ and cannot be nested. When you write a Java class you expect other programmers to use, use doc comments to embed documentation about the class and each of its methods directly into the source code. A program named javadoc extracts these comments and processes them to create online documentation for your class. A doc comment can contain HTML tags and can use additional syntax understood by javadoc. For example: /** * Display a list of classes, many to a line. * * @param classes The classes to display * @return true on success, * false on failure. * @author David Flanagan */

See Chapter 7 for more information on the doc-comment syntax and Chapter 8 for more information on the javadoc program.

Identifiers and Reserved Words An identifier is any symbolic name that refers to something in a Java program. Class, method, parameter, and variable names are all identifiers. An identifier must begin with a letter, an underscore ( _ ), or a Unicode currency symbol (e.g., $, £, ¥). This initial letter can be followed by any number of letters, digits, underscores, or currency symbols. Remember that Java uses the Unicode character set, which contains quite a few letters and digits other than those in the ASCII character set. The following are legal identifiers: i engine3 theCurrentTime the_current_time θ

Identifiers can include numbers, but cannot begin with a number. In addition, they cannot contain any punctuation characters other than underscores and currency characters. By convention, dollar signs and other currency characters are reserved for identifiers automatically generated by a compiler or some kind of code preprocessor. It is best to avoid these characters in your own identifiers.

Identifiers and Reserved Words

7 March 2002 11:18

21

Java Syntax

/* * Step 4: Print static methods, both public and protected, * but don't list deprecated ones. */

Another important restriction on identifiers is that you cannot use any of the keywords and literals that are part of the Java language itself. These reserved words are listed in Table 2-1. Table 2−1. Java reserved words abstract

default

if

package

synchronized

assert

do

implements

private

this

boolean

double

import

protected

throw

break

else

instanceof

public

throws

byte

extends

int

return

transient

case

false

interface

short

true

catch

final

long

static

try

char

finally

native

strictfp

void

class

float

new

super

volatile

const

for

null

switch

while

continue

goto

Note that const and goto are reserved words but aren’t part of the Java language. assert is a reserved word as of Java 1.4

Primitive Data Types Java supports eight basic data types known as primitive types. In addition, it supports classes and arrays as composite data types, or reference types. Classes and arrays are documented later in this chapter. The primitive types are: a boolean type, a character type, four integer types, and two floating-point types. The four integer types and the two floating-point types differ in the number of bits that represent them, and therefore in the range of numbers they can represent. Table 2-2 summarizes these primitive data types. Table 2−2. Java primitive data types Type

Contains

Default

Size

Range

boolean

true or false

false

1 bit

NA

char

Unicode character

\u0000

16 bits

\u0000 to \uFFFF

byte

Signed integer

0

8 bits

–128 to 127

short

Signed integer

0

16 bits

–32768 to 32767

int

Signed integer

0

32 bits

–2147483648 to 2147483647

long

Signed integer

0

64 bits

–9223372036854775808 to 9223372036854775807

float

IEEE 754 floating point

0.0

32 bits

±1.4E–45 to ±3.4028235E+38

22

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

Table 2−2. Java primitive data types (continued) Type

Contains

Default

Size

Range

double

IEEE 754 floating point

0.0

64 bits

±4.9E–324 to ±1.7976931348623157E+308

The boolean Type

C and C++ programmers should note that Java is quite strict about its boolean type: boolean values can never be converted to or from other data types. In particular, a boolean is not an integral type, and integer values cannot be used in place of a boolean. In other words, you cannot take shortcuts such as the following in Java: if (o) { while(i) { } }

Instead, Java forces you to write cleaner code by explicitly stating the comparisons you want: if (o != null) { while(i != 0) { } }

The char Type The char type represents Unicode characters. It surprises many experienced programmers to learn that Java char values are 16 bits long, but in practice this fact is totally transparent. To include a character literal in a Java program, simply place it between single quotes (apostrophes): char c = 'A';

You can, of course, use any Unicode character as a character literal, and you can use the \u Unicode escape sequence. In addition, Java supports a number of other escape sequences that make it easy both to represent commonly used nonprinting ASCII characters such as newline and to escape certain punctuation characters that have special meaning in Java. For example: char tab = '\t', apostrophe = '\'', nul = '', aleph='\u05D0';

Table 2-3 lists the escape characters that can be used in char literals. These characters can also be used in string literals, which are covered later in this chapter.

Primitive Data Types

7 March 2002 11:18

23

Java Syntax

The boolean type represents truth values. There are only two possible values of this type, representing the two boolean states: on or off, yes or no, true or false. Java reserves the words true and false to represent these two boolean values.

Table 2−3. Java escape characters Escape sequence

Character value

\b

Backspace

\t

Horizontal tab

\n

Newline

\f

Form feed

\r

Carriage return

\"

Double quote

\'

Single quote

\\

Backslash

\xxx

The Latin-1 character with the encoding xxx, where xxx is an octal (base 8) number between 000 and 377. The forms \x and \xx are also legal, as in '\0', but are not recommended because they can cause difficulties in string constants where the escape sequence is followed by a regular digit.

\uxxxx

The Unicode character with encoding xxxx, where xxxx is four hexadecimal digits. Unicode escapes can appear anywhere in a Java program, not only in character and string literals.

char values can be converted to and from the various integral types. Unlike byte, short, int, and long, however, char is an unsigned type. The Character class defines a number of useful static methods for working with characters, including isDigit(), isJavaLetter(), isLowerCase(), and toUpperCase().

Integer Types The integer types in Java are byte, short, int, and long. As shown in Table 2-2, these four types differ only in the number of bits and, therefore, in the range of numbers each type can represent. All integral types represent signed numbers; there is no unsigned keyword as there is in C and C++. Literals for each of these types are written exactly as you would expect: as a string of decimal digits, optionally preceded by a minus sign.* Here are some legal integer literals: 0 1 123 -42000

* Technically, the minus sign is an operator that operates on the literal, not part of the literal itself. Also, all integer literals are 32-bit int values unless followed by the letter L, in which case they are 64-bit long values. There is no special syntax for byte and short literals, but int literals are usually converted to these shorter types as needed. For example, in the code: byte b = 123;

123 is a 32-bit int literal that is automatically converted (without requiring a cast) to a byte in the assignment statement.

24

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

Integer literals can also be expressed in hexadecimal or octal notation. A literal that begins with 0x or 0X is taken as a hexadecimal number, using the letters A to F (or a to f) as the additional digits required for base-16 numbers. Integer literals beginning with a leading 0 are taken to be octal (base-8) numbers and cannot include the digits 8 or 9. Java does not allow integer literals to be expressed in binary (base-2) notation. Legal hexadecimal and octal literals include: // Decimal 255, expressed in hexadecimal // The same number, expressed in octal (base 8) // A magic number used to identify Java class files

Integer literals are 32-bit int values unless they end with the character L or l, in which case they are 64-bit long values: 1234 1234L 0xffL

// An int value // A long value // Another long value

Integer arithmetic in Java is modular, which means that it never produces an overflow or an underflow when you exceed the range of a given integer type. Instead, numbers just wrap around. For example: byte b1 = 127, b2 = 1; byte sum = (byte)(b1 + b2);

// Largest byte is 127 // Sum wraps to –128, which is the smallest byte

Neither the Java compiler nor the Java interpreter warns you in any way when this occurs. When doing integer arithmetic, you simply must ensure that the type you are using has a sufficient range for the purposes you intend. Integer division by zero and modulo by zero are illegal and cause an ArithmeticException to be thrown. Each integer type has a corresponding wrapper class: Byte, Short, Integer, and Long. Each of these classes defines MIN_VALUE and MAX_VALUE constants that describe the range of the type. The classes also define useful static methods, such as Byte.parseByte() and Integer.parseInt(), for converting strings to integer values.

Floating-Point Types Real numbers in Java are represented with the float and double data types. As shown in Table 2-2, float is a 32-bit, single-precision floating-point value, and double is a 64-bit, double-precision floating-point value. Both types adhere to the IEEE 754-1985 standard, which specifies both the format of the numbers and the behavior of arithmetic for the numbers. Floating-point values can be included literally in a Java program as an optional string of digits, followed by a decimal point and another string of digits. Here are some examples: 123.45 0.0 .01

Floating-point literals can also use exponential, or scientific, notation, in which a number is followed by the letter e or E (for exponent) and another number. This

Primitive Data Types

7 March 2002 11:18

25

Java Syntax

0xff 0377 0xCAFEBABE

second number represents the power of ten by which the first number is multiplied. For example: 1.2345E02 1e-6 6.02e23

// 1.2345 × 102, or 123.45 // 1 × 10-6, or 0.000001 // Avogadro's Number: 6.02 × 1023

Floating-point literals are double values by default. To include a float value literally in a program, follow the number by the character f or F: double d = 6.02E23; float f = 6.02e23f;

Floating-point literals cannot be expressed in hexadecimal or octal notation. Most real numbers, by their very nature, cannot be represented exactly in any finite number of bits. Thus, it is important to remember that float and double values are only approximations of the numbers they are meant to represent. A float is a 32-bit approximation, which results in at least 6 significant decimal digits, and a double is a 64-bit approximation, which results in at least 15 significant digits. In practice, these data types are suitable for most real-number computations. In addition to representing ordinary numbers, the float and double types can also represent four special values: positive and negative infinity, zero, and NaN. The infinity values result when a floating-point computation produces a value that overflows the representable range of a float or double. When a floating-point computation underflows the representable range of a float or a double, a zero value results. The Java floating-point types make a distinction between positive zero and negative zero, depending on the direction from which the underflow occurred. In practice, positive and negative zero behave pretty much the same. Finally, the last special floating-point value is NaN, which stands for not-a-number. The NaN value results when an illegal floating-point operation, such as 0.0/0.0, is performed. Here are examples of statements that result in these special values: double double double double

inf = 1.0/0.0; neginf = -1.0/0.0; negzero = -1.0/inf; NaN = 0.0/0.0;

// // // //

Infinity -Infinity Negative zero Not-a-Number

Because the Java floating-point types can handle overflow to infinity and underflow to zero and have a special NaN value, floating-point arithmetic never throws exceptions, even when performing illegal operations, like dividing zero by zero or taking the square root of a negative number. The float and double primitive types have corresponding classes, named Float and Double. Each of these classes defines the following useful constants: MIN_VALUE, MAX_VALUE, NEGATIVE_INFINITY, POSITIVE_INFINITY, and NaN. The infinite floating-point values behave as you would expect. Adding or subtracting any finite value to or from infinity, for example, yields infinity. Negative zero behaves almost identically to positive zero, and, in fact, the = = equality operator reports that negative zero is equal to positive zero. One way to distinguish negative zero from positive, or regular, zero is to divide by it. 1.0/0.0 yields positive infinity, but 1.0 divided by negative zero yields negative infinity. Finally, since NaN is not-a-number, the = = operator says that it is not equal to any other number,

26

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

including itself ! To check whether a float or double value is NaN, you must use the Float.isNaN() and Double.isNaN() methods.

Strings

"Hello, world" "'This' is a string!"

String literals can contain any of the escape sequences that can appear as char literals (see Table 2-3). Use the \" sequence to include a double-quote within a String literal. Strings and string literals are discussed in more detail later in this chapter. Chapter 4 demonstrates some of the ways you can work with String objects in Java.

Type Conversions Java allows conversions between integer values and floating-point values. In addition, because every character corresponds to a number in the Unicode encoding, char values can be converted to and from the integer and floating-point types. In fact, boolean is the only primitive type that cannot be converted to or from another primitive type in Java. There are two basic types of conversions. A widening conversion occurs when a value of one type is converted to a wider type—one that has a larger range of legal values. Java performs widening conversions automatically when, for example, you assign an int literal to a double variable or a char literal to an int variable. Narrowing conversions are another matter, however. A narrowing conversion occurs when a value is converted to a type that is not wider than it. Narrowing conversions are not always safe: it is reasonable to convert the integer value 13 to a byte, for example, but it is not reasonable to convert 13000 to a byte, since byte can only hold numbers between –128 and 127. Because you can lose data in a narrowing conversion, the Java compiler complains when you attempt any narrowing conversion, even if the value being converted would in fact fit in the narrower range of the specified type: int i = 13; byte b = i;

// The compiler does not allow this

The one exception to this rule is that you can assign an integer literal (an int value) to a byte or short variable, if the literal falls within the range of the variable. If you need to perform a narrowing conversion and are confident you can do so without losing data or precision, you can force Java to perform the conversion

Primitive Data Types

7 March 2002 11:18

27

Java Syntax

In addition to the boolean, character, integer, and floating-point data types, Java also has a data type for working with strings of text (usually simply called strings). The String type is a class, however, and is not one of the primitive types of the language. Because strings are so commonly used, though, Java does have a syntax for including string values literally in a program. A String literal consists of arbitrary text within double quotes. For example:

using a language construct known as a cast. Perform a cast by placing the name of the desired type in parentheses before the value to be converted. For example: int i = 13; byte b = (byte) i; i = (int) 13.456;

// Force the int to be converted to a byte // Force this double literal to the int 13

Casts of primitive types are most often used to convert floating-point values to integers. When you do this, the fractional part of the floating-point value is simply truncated (i.e., the floating-point value is rounded towards zero, not towards the nearest integer). The methods Math.round(), Math.floor(), and Math.ceil() perform other types of rounding. The char type acts like an integer type in most ways, so a char value can be used anywhere an int or long value is required. Recall, however, that the char type is unsigned, so it behaves differently than the short type, even though both of them are 16 bits wide: short s = (short) 0xffff; char c = '\uffff'; int i1 = s; int i2 = c;

// // // //

These bits represent the number –1 The same bits, representing a Unicode character Converting the short to an int yields –1 Converting the char to an int yields 65535

Table 2-4 is a grid that shows which primitive types can be converted to which other types and how the conversion is performed. The letter N in the table means that the conversion cannot be performed. The letter Y means that the conversion is a widening conversion and is therefore performed automatically and implicitly by Java. The letter C means that the conversion is a narrowing conversion and requires an explicit cast. Finally, the notation Y* means that the conversion is an automatic widening conversion, but that some of the least significant digits of the value may be lost by the conversion. This can happen when converting an int or long to a float or double. The floating-point types have a larger range than the integer types, so any int or long can be represented by a float or double. However, the floating-point types are approximations of numbers and cannot always hold as many significant digits as the integer types. Table 2−4. Java primitive type conversions Convert fr om:

boolean

byte

short

char

int

long

float

double

boolean



N

N

N

N

N

N

N

byte

N



Y

C

Y

Y

Y

Y

short

N

C



C

Y

Y

Y

Y

char

N

C

C



Y

Y

Y

Y

int

N

C

C

C



Y

Y*

Y

long

N

C

C

C

C



Y*

Y*

float

N

C

C

C

C

C



Y

double

N

C

C

C

C

C

C



28

7 March 2002 11:18

Convert to:

Chapter 2 – Java Syntax from the Ground Up

Reference Types

As you can see, there are an infinite number of possible class and array data types. Collectively, these data types are known as refer ence types. The reason for this name will become clear later in this chapter. For now, however, what is important to understand is that class and array types differ significantly from primitive types, in that they are compound, or composite, types. A primitive data type holds exactly one value. Classes and arrays are aggregate types that contain multiple values. The Point type, for example, holds two double values representing the X and Y coordinates of the point. And char[] is obviously a compound type because it represents a list of characters. By their very nature, class and array types are more complicated than the primitive data types. We’ll discuss classes and arrays in detail later in this chapter and examine classes in even more detail in Chapter 3.

Expressions and Operators So far in this chapter, we’ve learned about the primitive types that Java programs can manipulate and seen how to include primitive values as literals in a Java program. We’ve also used variables as symbolic names that represent, or hold, values. These literals and variables are the tokens out of which Java programs are built. An expr ession is the next higher level of structure in a Java program. The Java interpreter evaluates an expression to compute its value. The very simplest expressions are called primary expressions and consist of literals and variables. So, for example, the following are all expressions: 1.7 true sum

// A floating-point literal // A boolean literal // A variable

When the Java interpreter evaluates a literal expression, the resulting value is the literal itself. When the interpreter evaluates a variable expression, the resulting value is the value stored in the variable. Primary expressions are not very interesting. More complex expressions are made by using operators to combine primary expressions. For example, the following expression uses the assignment operator to combine two primary expressions — a variable and a floating-point literal—into an assignment expression: sum = 1.7

Expr essions and Operators

7 March 2002 11:18

29

Java Syntax

In addition to its eight primitive types, Java defines two additional categories of data types: classes and arrays. Java programs consist of class definitions; each class defines a new data type that can be manipulated by Java programs. For example, a program might define a class named Point and use it to store and manipulate X,Y points in a Cartesian coordinate system. This makes Point a new data type in that program. An array type represents a list of values of some other type. char is a data type, and an array of char values is another data type, written char[]. An array of Point objects is a data type, written Point[]. And an array of Point arrays is yet another type, written Point[][].

But operators are used not only with primary expressions; they can also be used with expressions at any level of complexity. Thus, the following are all legal expressions: sum = 1 + 2 + 3*1.2 + (4 + 8)/3.0 sum/Math.sqrt(3.0 * 1.234) (int)(sum + 33)

Operator Summary The kinds of expressions you can write in a programming language depend entirely on the set of operators available to you. Table 2-5 summarizes the operators available in Java. The P and A columns of the table specify the precedence and associativity of each group of related operators, respectively. Table 2−5. Java operators P

A

Operator

Operand type(s)

Operation per formed

15

L

.

object, member

object member access

[]

array, int

array element access

( args )

method, arglist

method invocation

++, − −

variable

post-increment, decrement

++, − −

variable

pre-increment, decrement

+, −

number

unary plus, unary minus

˜

integer

bitwise complement

!

boolean

boolean NOT

new

class, arglist

object creation

( type )

type, any

cast (type conversion)

14

13

R

12

L

*, /, %

number, number

multiplication, division, remainder

11

L

+, −

number, number

addition, subtraction

+

string, any

string concatenation

10

L




integer, integer

right shift with sign extension

>>>

integer, integer

right shift with zero extension

=

number, number

greater than, greater than or equal

9

8

30

7 March 2002 11:18

R

L

L

instanceof

reference, type

type comparison

==

primitive, primitive

equal (have identical values)

!=

primitive, primitive

not equal (have different values)

==

reference, reference

equal (refer to same object)

Chapter 2 – Java Syntax from the Ground Up

Table 2−5. Java operators (continued) P

A

Operator

Operand type(s)

Operation per formed

!=

reference, reference

not equal (refer to different objects)

integer, integer

bitwise AND

L

& &

boolean, boolean

boolean AND

6

L

ˆ

integer, integer

bitwise XOR

ˆ

boolean, boolean

boolean XOR

5

L

|

integer, integer

bitwise OR

|

boolean, boolean

boolean OR

4

L

&&

boolean, boolean

conditional AND

3

L

||

boolean, boolean

conditional OR

2

R

?:

boolean, any, any

conditional (ternary) operator

1

R

=

variable, any

assignment

*=, /=, %=,

variable, any

assignment with operation

Java Syntax

7

+=, −=, =, >>>=, &=, ˆ=, |=

Precedence The P column of Table 2-5 specifies the pr ecedence of each operator. Precedence specifies the order in which operations are performed. Consider this expression: a + b * c

The multiplication operator has higher precedence than the addition operator, so a is added to the product of b and c. Operator precedence can be thought of as a measure of how tightly operators bind to their operands. The higher the number, the more tightly they bind. Default operator precedence can be overridden through the use of parentheses, to explicitly specify the order of operations. The previous expression can be rewritten as follows to specify that the addition should be performed before the multiplication: (a + b) * c

The default operator precedence in Java was chosen for compatibility with C; the designers of C chose this precedence so that most expressions can be written naturally without parentheses. There are only a few common Java idioms for which parentheses are required. Examples include: // Class cast combined with member access ((Integer) o).intValue(); // Assignment combined with comparison

Expr essions and Operators

7 March 2002 11:18

31

while((line = in.readLine()) != null) { ... } // Bitwise operators combined with comparison if ((flags & (PUBLIC | PROTECTED)) != 0) { ... }

Associativity When an expression involves several operators that have the same precedence, the operator associativity governs the order in which the operations are performed. Most operators are left-to-right associative, which means that the operations are performed from left to right. The assignment and unary operators, however, have right-to-left associativity. The A column of Table 2-5 specifies the associativity of each operator or group of operators. The value L means left to right, and R means right to left. The additive operators are all left-to-right associative, so the expression a+b-c is evaluated from left to right: (a+b)-c. Unary operators and assignment operators are evaluated from right to left. Consider this complex expression: a = b += c = -˜d

This is evaluated as follows: a = (b += (c = -(˜d)))

As with operator precedence, operator associativity establishes a default order of evaluation for an expression. This default order can be overridden through the use of parentheses. However, the default operator associativity in Java has been chosen to yield a natural expression syntax, and you rarely need to alter it.

Operand number and type The fourth column of Table 2-5 specifies the number and type of the operands expected by each operator. Some operators operate on only one operand; these are called unary operators. For example, the unary minus operator changes the sign of a single number: -n

// The unary minus operator

Most operators, however, are binary operators that operate on two operand values. The − operator actually comes in both forms: a - b

// The subtraction operator is a binary operator

Java also defines one ternary operator, often called the conditional operator. It is like an if statement inside an expression. Its three operands are separated by a question mark and a colon; the second and third operands must be convertible to the same type: x > y ? x : y

// Ternary expression; evaluates to the larger of x and y

In addition to expecting a certain number of operands, each operator also expects particular types of operands. Column four of the table lists the operand types. Some of the codes used in that column require further explanation:

32

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

number An integer, floating-point value, or character (i.e., any primitive type except boolean) integer A byte, short, int, long, or char value (long values are not allowed for the array access operator [])

variable A variable or anything else, such as an array element, to which a value can be assigned

Return type Just as every operator expects its operands to be of specific types, each operator produces a value of a specific type. The arithmetic, increment and decrement, bitwise, and shift operators return a double if at least one of the operands is a double. Otherwise, they return a float if at least one of the operands is a float. Otherwise, they return a long if at least one of the operands is a long. Otherwise, they return an int, even if both operands are byte, short, or char types that are narrower than int. The comparison, equality, and boolean operators always return boolean values. Each assignment operator returns whatever value it assigned, which is of a type compatible with the variable on the left side of the expression. The conditional operator returns the value of its second or third argument (which must both be of the same type).

Side effects Every operator computes a value based on one or more operand values. Some operators, however, have side effects in addition to their basic evaluation. If an expression contains side effects, evaluating it changes the state of a Java program in such a way that evaluating the expression again may yield a different result. For example, the ++ increment operator has the side effect of incrementing a variable. The expression ++a increments the variable a and returns the newly incremented value. If this expression is evaluated again, the value will be different. The various assignment operators also have side effects. For example, the expression a*=2 can also be written as a=a*2. The value of the expression is the value of a multiplied by 2, but the expression also has the side effect of storing that value back into a. The method invocation operator () has side effects if the invoked method has side effects. Some methods, such as Math.sqrt(), simply compute and return a value without side effects of any kind. Typically, however, methods do have side effects. Finally, the new operator has the profound side effect of creating a new object.

Expr essions and Operators

7 March 2002 11:18

33

Java Syntax

refer ence An object or array

Order of evaluation When the Java interpreter evaluates an expression, it performs the various operations in an order specified by the parentheses in the expression, the precedence of the operators, and the associativity of the operators. Before any operation is performed, however, the interpreter first evaluates the operands of the operator. (The exceptions are the &&, ||, and ?: operators, which do not always evaluate all their operands.) The interpreter always evaluates operands in order from left to right. This matters if any of the operands are expressions that contain side effects. Consider this code, for example: int a = 2; int v = ++a + ++a * ++a;

Although the multiplication is performed before the addition, the operands of the + operator are evaluated first. Thus, the expression evaluates to 3+4*5, or 23.

Arithmetic Operators Since most programs operate primarily on numbers, the most commonly used operators are often those that perform arithmetic operations. The arithmetic operators can be used with integers, floating-point numbers, and even characters (i.e., they can be used with any primitive type other than boolean). If either of the operands is a floating-point number, floating-point arithmetic is used; otherwise, integer arithmetic is used. This matters because integer arithmetic and floatingpoint arithmetic differ in the way division is performed and in the way underflows and overflows are handled, for example. The arithmetic operators are: Addition (+) The + operator adds two numbers. As we’ll see shortly, the + operator can also be used to concatenate strings. If either operand of + is a string, the other one is converted to a string as well. Be sure to use parentheses when you want to combine addition with concatenation. For example: System.out.println("Total: " + 3 + 4);

// Prints "Total: 34", not 7!

Subtraction (−) When − is used as a binary operator, it subtracts its second operand from its first. For example, 7–3 evaluates to 4. The − operator can perform unary negation. Multiplication (*) The * operator multiplies its two operands. For example, 7*3 evaluates to 21. Division (/) The / operator divides its first operand by its second. If both operands are integers, the result is an integer, and any remainder is lost. If either operand is a floating-point value, however, the result is a floating-point value. When dividing two integers, division by zero throws an ArithmeticException. For floating-point calculations, however, division by zero simply yields an infinite result or NaN:

34

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

7/3 7/3.0f 7/0 7/0.0 0.0/0.0

// // // // //

Evaluates Evaluates Throws an Evaluates Evaluates

to 2 to 2.333333f ArithmeticException to positive infinity to NaN

Unary minus (−) When − is used as a unary operator, before a single operand, it performs unary negation. In other words, it converts a positive value to an equivalently negative value, and vice versa.

String Concatenation Operator In addition to adding numbers, the + operator (and the related += operator) also concatenates, or joins, strings. If either of the operands to + is a string, the operator converts the other operand to a string. For example: System.out.println("Quotient: " + 7/3.0f);

// Prints "Quotient: 2.3333333"

As a result, you must be careful to put any addition expressions in parentheses when combining them with string concatenation. If you do not, the addition operator is interpreted as a concatenation operator. The Java interpreter has built-in string conversions for all primitive types. An object is converted to a string by invoking its toString() method. Some classes define custom toString() methods, so that objects of that class can easily be converted to strings in this way. An array is converted to a string by invoking the built-in toString() method, which, unfortunately, does not return a useful string representation of the array contents.

Increment and Decrement Operators The ++ operator increments its single operand, which must be a variable, an element of an array, or a field of an object, by one. The behavior of this operator depends on its position relative to the operand. When used before the operand, where it is known as the pr e-incr ement operator, it increments the operand and evaluates to the incremented value of that operand. When used after the operand, where it is known as the post-incr ement operator, it increments its operand, but evaluates to the value of that operand before it was incremented.

Expr essions and Operators

7 March 2002 11:18

35

Java Syntax

Modulo (%) The % operator computes the first operand modulo the second operand (i.e., it returns the remainder when the first operand is divided by the second operand an integral number of times). For example, 7%3 is 1. The sign of the result is the same as the sign of the first operand. While the modulo operator is typically used with integer operands, it also works for floating-point values. For example, 4.3%2.1 evaluates to 0.1. When operating with integers, trying to compute a value modulo zero causes an ArithmeticException. When working with floating-point values, anything modulo 0.0 evaluates to NaN, as does infinity modulo anything.

For example, the following code sets both i and j to 2: i = 1; j = ++i;

But these lines set i to 2 and j to 1: i = 1; j = i++;

Similarly, the − − operator decrements its single numeric operand, which must be a variable, an element of an array, or a field of an object, by one. Like the ++ operator, the behavior of − − depends on its position relative to the operand. When used before the operand, it decrements the operand and returns the decremented value. When used after the operand, it decrements the operand, but returns the undecr emented value. The expressions x++ and x− − are equivalent to x=x+1 and x=x−1, respectively, except that when using the increment and decrement operators, x is only evaluated once. If x is itself an expression with side effects, this makes a big difference. For example, these two expressions are not equivalent: a[i++]++; a[i++] = a[i++] + 1;

// Increments an element of an array // Adds one to an array element and stores it in another

These operators, in both prefix and postfix forms, are most commonly used to increment or decrement the counter that controls a loop.

Comparison Operators The comparison operators consist of the equality operators that test values for equality or inequality and the relational operators used with ordered types (numbers and characters) to test for greater than and less than relationships. Both types of operators yield a boolean result, so they are typically used with if statements and while and for loops to make branching and looping decisions. For example: if (o != null) ...; while(i < a.length) ...;

// The not equals operator // The less than operator

Java provides the following equality operators: Equals (= =) The = = operator evaluates to true if its two operands are equal and false otherwise. With primitive operands, it tests whether the operand values themselves are identical. For operands of reference types, however, it tests whether the operands refer to the same object or array. In other words, it does not test the equality of two distinct objects or arrays. In particular, note that you cannot test two distinct strings for equality with this operator. If = = is used to compare two numeric or character operands that are not of the same type, the narrower operand is converted to the type of the wider operand before the comparison is done. For example, when comparing a short to a float, the short is first converted to a float before the comparison is performed. For floating-point numbers, the special negative zero value tests equal to the regular, positive zero value. Also, the special NaN (not-a-

36

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

number) value is not equal to any other number, including itself. To test whether a floating-point value is NaN, use the Float.isNan() or Double.isNan() method. Not equals (!=) The != operator is exactly the opposite of the = = operator. It evaluates to true if its two primitive operands have different values or if its two reference operands refer to different objects or arrays. Otherwise, it evaluates to false.

vides the following relational operators: Less than (=) Evaluates to true if the first operand is greater than or equal to the second.

Boolean Operators As we’ve just seen, the comparison operators compare their operands and yield a boolean result, which is often used in branching and looping statements. In order

to make branching and looping decisions based on conditions more interesting than a single comparison, you can use the boolean (or logical) operators to combine multiple comparison expressions into a single, more complex, expression. The boolean operators require their operands to be boolean values and they evaluate to boolean values. The operators are: Conditional AND (&&) This operator performs a boolean AND operation on its operands. It evaluates to true if and only if both its operands are true. If either or both operands are false, it evaluates to false. For example: if (x < 10 && y > 3) ... // If both comparisons are true

This operator (and all the boolean operators except the unary ! operator) have a lower precedence than the comparison operators. Thus, it is perfectly legal to write a line of code like the one above. However, some programmers prefer to use parentheses to make the order of evaluation explicit: if ((x < 10) && (y > 3)) ...

You should use whichever style you find easier to read. This operator is called a conditional AND because it conditionally evaluates its second operand. If the first operand evaluates to false, the value of the expression is false, regardless of the value of the second operand. Therefore,

Expr essions and Operators

7 March 2002 11:18

37

Java Syntax

The relational operators can be used with numbers and characters, but not with boolean values, objects, or arrays because those types are not ordered. Java pro-

to increase efficiency, the Java interpreter takes a shortcut and skips the second operand. Since the second operand is not guaranteed to be evaluated, you must use caution when using this operator with expressions that have side effects. On the other hand, the conditional nature of this operator allows us to write Java expressions such as the following: if (data != null && i < data.length && data[i] != -1) ...

The second and third comparisons in this expression would cause errors if the first or second comparisons evaluated to false. Fortunately, we don’t have to worry about this because of the conditional behavior of the && operator. Conditional OR (||) This operator performs a boolean OR operation on its two boolean operands. It evaluates to true if either or both of its operands are true. If both operands are false, it evaluates to false. Like the && operator, || does not always evaluate its second operand. If the first operand evaluates to true, the value of the expression is true, regardless of the value of the second operand. Thus, the operator simply skips that second operand in that case. Boolean NOT (!) This unary operator changes the boolean value of its operand. If applied to a true value, it evaluates to false, and if applied to a false value, it evaluates to true. It is useful in expressions like these: if (!found) ... // found is a boolean variable declared somewhere while (!c.isEmpty()) ... // The isEmpty() method returns a boolean value

Because ! is a unary operator, it has a high precedence and often must be used with parentheses: if (!(x > y && y > z))

Boolean AND (&) When used with boolean operands, the & operator behaves like the && operator, except that it always evaluates both operands, regardless of the value of the first operand. This operator is almost always used as a bitwise operator with integer operands, however, and many Java programmers would not even recognize its use with boolean operands as legal Java code. Boolean OR (|) This operator performs a boolean OR operation on its two boolean operands. It is like the || operator, except that it always evaluates both operands, even if the first one is true. The | operator is almost always used as a bitwise operator on integer operands; its use with boolean operands is very rare. Boolean XOR (ˆ) When used with boolean operands, this operator computes the Exclusive OR (XOR) of its operands. It evaluates to true if exactly one of the two operands is true. In other words, it evaluates to false if both operands are false or if both operands are true. Unlike the && and || operators, this one must always evaluate both operands. The ˆ operator is much more commonly used as a bitwise operator on integer operands. With boolean operands, this operator is equivalent to the != operator.

38

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

Bitwise and Shift Operators

If either of the arguments to a bitwise operator is a long, the result is a long. Otherwise, the result is an int. If the left operand of a shift operator is a long, the result is a long; otherwise, the result is an int. The operators are: Bitwise complement (˜) The unary ˜ operator is known as the bitwise complement, or bitwise NOT, operator. It inverts each bit of its single operand, converting ones to zeros and zeros to ones. For example: byte b = ˜12; flags = flags & ˜f;

// ˜00001100 ==> 11110011 or -13 decimal // Clear flag f in a set of flags

Bitwise AND (&) This operator combines its two integer operands by performing a boolean AND operation on their individual bits. The result has a bit set only if the corresponding bit is set in both operands. For example: 10 & 7 if ((flags & f) != 0)

// 00001010 & 00000111 ==> 00000010 or 2 // Test whether flag f is set

When used with boolean operands, & is the infrequently used boolean AND operator described earlier. Bitwise OR (|) This operator combines its two integer operands by performing a boolean OR operation on their individual bits. The result has a bit set if the corresponding bit is set in either or both of the operands. It has a zero bit only where both corresponding operand bits are zero. For example: 10 | 7 flags = flags | f;

// 00001010 | 00000111 ==> 00001111 or 15 // Set flag f

When used with boolean operands, | is the infrequently used boolean OR operator described earlier. Bitwise XOR (ˆ) This operator combines its two integer operands by performing a boolean XOR (Exclusive OR) operation on their individual bits. The result has a bit set if the corresponding bits in the two operands are different. If the corresponding operand bits are both ones or both zeros, the result bit is a zero. For example: 10 ˆ 7

// 00001010 ˆ 00000111 ==> 00001101 or 13

Expr essions and Operators

7 March 2002 11:18

39

Java Syntax

The bitwise and shift operators are low-level operators that manipulate the individual bits that make up an integer value. The bitwise operators are most commonly used for testing and setting individual flag bits in a value. In order to understand their behavior, you must understand binary (base-2) numbers and the twos-complement format used to represent negative integers. You cannot use these operators with floating-point, boolean, array, or object operands. When used with boolean operands, the &, |, and ˆ operators perform a different operation, as described in the previous section.

When used with boolean operands, ˆ is the infrequently used boolean XOR operator. Left shift (> 2

// 00001010 >> 1 = 00000101 = 5 = 10/2 // 00011011 >> 3 = 00000011 = 3 = 27/8 // 11001110 >> 2 = 11110011 = -13 != -50/4

If the left operand is positive and the right operand is n, the >> operator is the same as integer division by 2n. Unsigned right shift (>>>) This operator is like the >> operator, except that it always shifts zeros into the high-order bits of the result, regardless of the sign of the left-hand operand. This technique is called zero extension; it is appropriate when the left operand is being treated as an unsigned value (despite the fact that Java integer types are all signed). Examples: 0xff >>> 4 -50 >>> 2

// 11111111 >>> 4 = 00001111 = 15 = 255/16 // OxFFFFFFCE >>> 2 = Ox3FFFFF33 = 107371811

Assignment Operators The assignment operators store, or assign, a value into some kind of variable. The left operand must evaluate to an appropriate local variable, array element, or object field. The right side can be any value of a type compatible with the variable. An assignment expression evaluates to the value that is assigned to the variable. More importantly, however, the expression has the side effect of actually performing the assignment. Unlike all other binary operators, the assignment operators are right-associative, which means that the assignments in a=b=c are performed right-to-left, as follows: a=(b=c).

40

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

The basic assignment operator is =. Do not confuse it with the equality operator, = =. In order to keep these two operators distinct, I recommend that you read = as “is assigned the value.”

a[i++] += 2; a[i++] = a[i++] + 2;

The general form of these combination assignment operators is: var op= value

This is equivalent (unless there are side effects in var) to: var = var op value

The available operators are: += &= =

*= ˆ= >>>=

/=

%=

// Arithmetic operators plus assignment // Bitwise operators plus assignment // Shift operators plus assignment

The most commonly used operators are += and − =, although &= and |= can also be useful when working with boolean flags. For example: i += 2; c -= 5; flags |= f; flags &= ˜f;

// // // //

Increment a loop counter by 2 Decrement a counter by 5 Set a flag f in an integer set of flags Clear a flag f in an integer set of flags

The Conditional Operator The conditional operator ?: is a somewhat obscure ternary (three-operand) operator inherited from C. It allows you to embed a conditional within an expression. You can think of it as the operator version of the if/else statement. The first and second operands of the conditional operator are separated by a question mark (?), while the second and third operands are separated by a colon (:). The first operand must evaluate to a boolean value. The second and third operands can be of any type, but they must be convertible to the same type. The conditional operator starts by evaluating its first operand. If it is true, the operator evaluates its second operand and uses that as the value of the expression. On the other hand, if the first operand is false, the conditional operator evaluates and returns its third operand. The conditional operator never evaluates both its

Expr essions and Operators

7 March 2002 11:18

41

Java Syntax

In addition to this simple assignment operator, Java also defines 11 other operators that combine assignment with the 5 arithmetic operators and the 6 bitwise and shift operators. For example, the += operator reads the value of the left variable, adds the value of the right operand to it, stores the sum back into the left variable as a side effect, and returns the sum as the value of the expression. Thus, the expression x+=2 is almost the same as x=x+2. The difference between these two expressions is that when you use the += operator, the left operand is evaluated only once. This makes a difference when that operand has a side effect. Consider the following two expressions, which are not equivalent:

second and third operand, so be careful when using expressions with side effects with this operator. Examples of this operator are: int max = (x > y) ? x : y; String name = (name != null) ? name : "unknown";

Note that the ?: operator has lower precedence than all other operators except the assignment operators, so parentheses are not usually necessary around the operands of this operator. Many programmers find conditional expressions easier to read if the first operand is placed within parentheses, however. This is especially true because the conditional if statement always has its conditional expression written within parentheses.

The instanceof Operator The instanceof operator requires an object or array value as its left operand and the name of a reference type as its right operand. It evaluates to true if the object or array is an instance of the specified type; it returns false otherwise. If the left operand is null, instanceof always evaluates to false. If an instanceof expression evaluates to true, it means that you can safely cast and assign the left operand to a variable of the type of the right operand. The instanceof operator can be used only with array and object types and values, not primitive types and values. Object and array types are discussed in detail later in this chapter. Examples of instanceof are: "string" instanceof String "" instanceof Object null instanceof String Object o = new int[] o instanceof int[] o instanceof byte[] o instanceof Object

// True: all strings are instances of String // True: strings are also instances of Object // False: null is never instanceof anything

{1,2,3}; // True: the array value is an int array // False: the array value is not a byte array // True: all arrays are instances of Object

// Use instanceof to make sure that it is safe to cast an object if (object instanceof Point) { Point p = (Point) object; }

Special Operators There are five language constructs in Java that are sometimes considered operators and sometimes considered simply part of the basic language syntax. These “operators” are listed in Table 2-5 in order to show their precedence relative to the other true operators. The use of these language constructs is detailed elsewhere in this chapter, but is described briefly here, so that you can recognize these constructs when you encounter them in code examples: Object member access (.) An object is a collection of data and methods that operate on that data; the data fields and methods of an object are called its members. The dot (.) operator accesses these members. If o is an expression that evaluates to an

42

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

object reference, and f is the name of a field of the object, o.f evaluates to the value contained in that field. If m is the name of a method, o.m refers to that method and allows it to be invoked using the () operator shown later.

Method invocation (()) A method is a named collection of Java code that can be run, or invoked, by following the name of the method with zero or more comma-separated expressions contained within parentheses. The values of these expressions are the arguments to the method. The method processes the arguments and optionally returns a value that becomes the value of the method invocation expression. If o.m is a method that expects no arguments, the method can be invoked with o.m(). If the method expects three arguments, for example, it can be invoked with an expression such as o.m(x,y,z). Before the Java interpreter invokes a method, it evaluates each of the arguments to be passed to the method. These expressions are guaranteed to be evaluated in order from left to right (which matters if any of the arguments have side effects). Object creation (new) In Java, objects (and arrays) are created with the new operator, which is followed by the type of the object to be created and a parenthesized list of arguments to be passed to the object constructor. A constructor is a special method that initializes a newly created object, so the object creation syntax is similar to the Java method invocation syntax. For example: new ArrayList(); new Point(1,2)

Type conversion or casting (()) As we’ve already seen, parentheses can also be used as an operator to perform narrowing type conversions, or casts. The first operand of this operator is the type to be converted to; it is placed between the parentheses. The second operand is the value to be converted; it follows the parentheses. For example: (byte) 28 (int) (x + 3.14f) (String)h.get(k)

// An integer literal cast to a byte type // A floating-point sum value cast to an integer value // A generic object cast to a more specific string type

Statements A statement is a single command executed b the Java interpreter. By default, the Java interpreter runs one statement after another, in the order they are written. Many of the statements defined by Java, however, are flow-control statements,

Statements

7 March 2002 11:18

43

Java Syntax

Array element access ([]) An array is a numbered list of values. Each element of an array can be referred to by its number, or index. The [] operator allows you to refer to the individual elements of an array. If a is an array, and i is an expression that evaluates to an int, a[i] refers to one of the elements of a. Unlike other operators that work with integer values, this operator restricts array index values to be of type int or narrower.

such as conditionals and loops, that alter this default order of execution in welldefined ways. Table 2-6 summarizes the statements defined by Java. Table 2−6. Java statements Statement

Purpose

Syntax

expr ession

side effects

var = expr; expr++; method(); new Type();

compound

group statements

{ statements }

empty

do nothing

;

labeled

name a statement

label : statement

variable

declare a variable

[final] type name [= value] [, name [= value]] . . . ;

if

conditional

if ( expr ) statement [ else statement]

switch

conditional

switch ( expr ) { [ case expr : statements ] . . . [ default: statements ] }

while

loop

while ( expr ) statement

do

loop

do statement while ( expr );

for

simplified loop

for ( init ; test ; increment ) statement

break

exit block

break [ label ] ;

continue

restart loop

continue [ label ] ;

return

end method

return [ expr ] ;

synchronized

critical section

synchronized ( expr ) { statements }

throw

throw exception

throw expr ;

try

handle exception

try { statements } [ catch ( type name ) { statements } ] ... [ finally { statements } ]

assert

verify invariant

assert invariant [ : error] ; (Java 1.4

and later)

Expression Statements As we saw earlier in the chapter, certain types of Java expressions have side effects. In other words, they do not simply evaluate to some value, but also change the program state in some way. Any expression with side effects can be used as a statement simply by following it with a semicolon. The legal types of expression statements are assignments, increments and decrements, method calls, and object creation. For example:

44

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

a = 1; x *= 2; i++; --c; System.out.println("statement");

// // // // //

Assignment Assignment with operation Post-increment Pre-decrement Method invocation

Compound Statements

for(int i = 0; i < 10; i++) { a[i]++; // Body of this loop is a compound statement. b[i]--; // It consists of two expression statements } // within curly braces.

The Empty Statement An empty statement in Java is written as a single semicolon. The empty statement doesn’t do anything, but the syntax is occasionally useful. For example, you can use it to indicate an empty loop body of a for loop: for(int i = 0; i < 10; a[i++]++) /* empty */;

// Increment array elements // Loop body is empty statement

Labeled Statements A labeled statement is simply a statement that has been given a name by prepending an identifier and a colon to it. Labels are used by the break and continue statements. For example: rowLoop: for(int r = 0; r < rows.length; r++) { colLoop: for(int c = 0; c < columns.length; c++) { break rowLoop; } }

// A labeled loop // Another one // Use a label

Local Variable Declaration Statements A local variable, often simply called a variable, is a symbolic name for a location where a value can be stored that is defined within a method or compound statement. All variables must be declared before they can be used; this is done with a variable declaration statement. Because Java is a strongly typed language, a variable declaration specifies the type of the variable, and only values of that type can be stored in the variable. In its simplest form, a variable declaration specifies a variable’s type and name: int counter; String s;

Statements

7 March 2002 11:18

45

Java Syntax

A compound statement is any number and kind of statements grouped together within curly braces. You can use a compound statement anywhere a statement is required by Java syntax:

A variable declaration can also include an initializer : an expression that specifies an initial value for the variable. For example: int i = 0; String s = readLine(); int[] data = {x+1, x+2, x+3};

// Array initializers are documented later

The Java compiler does not allow you to use a local variable that has not been initialized, so it is usually convenient to combine variable declaration and initialization into a single statement. The initializer expression need not be a literal value or a constant expression that can be evaluated by the compiler; it can be an arbitrarily complex expression whose value is computed when the program is run. A single variable declaration statement can declare and initialize more than one variable, but all variables must be of the same type. Variable names and optional initializers are separated from each other with commas: int i, j, k; float x = 1.0, y = 1.0; String question = "Really Quit?", response;

In Java 1.1 and later, variable declaration statements can begin with the final keyword. This modifier specifies that once an initial value is specified for the variable, that value is never allowed to change: final String greeting = getLocalLanguageGreeting();

C programmers should note that Java variable declaration statements can appear anywhere in Java code; they are not restricted to the beginning of a method or block of code. Local variable declarations can also be integrated with the initialize portion of a for loop, as we’ll discuss shortly. Local variables can be used only within the method or block of code in which they are defined. This is called their scope or lexical scope : void method() { int i = 0; while (i < 10) { int j = 0; i++; } System.out.println(i); }

// // // // // // // //

A generic method Declare variable i i is in scope here Declare j; the scope of j begins here i is in scope here; increment it j is no longer in scope; can't use it anymore i is still in scope here The scope of i ends here

The if/else Statement The if statement is the fundamental control statement that allows Java to make decisions or, more precisely, to execute statements conditionally. The if statement has an associated expression and statement. If the expression evaluates to true, the interpreter executes the statement. If the expression evaluates to false, however, the interpreter skips the statement. For example: if (username = = null) username = "John Doe";

46

7 March 2002 11:18

// If username is null, // define it

Chapter 2 – Java Syntax from the Ground Up

Although they look extraneous, the parentheses around the expression are a required part of the syntax for the if statement. As I already mentioned, a block of statements enclosed in curly braces is itself a statement, so we can also write if statements that look as follows: if ((address = = null) || (address.equals(""))) { address = "[undefined]"; System.out.println("WARNING: no address specified."); }

if (username != null) System.out.println("Hello " + username); else { username = askQuestion("What is your name?"); System.out.println("Hello " + username + ". Welcome!"); }

When you use nested if/else statements, some caution is required to ensure that the else clause goes with the appropriate if statement. Consider the following lines: if (i = = j) if (j = = k) System.out.println("i equals k"); else System.out.println("i doesn't equal j");

// WRONG!!

In this example, the inner if statement forms the single statement allowed by the syntax of the outer if statement. Unfortunately, it is not clear (except from the hint given by the indentation) which if the else goes with. And in this example, the indentation hint is wrong. The rule is that an else clause like this is associated with the nearest if statement. Properly indented, this code looks like this: if (i = = j) if (j = = k) System.out.println("i equals k"); else System.out.println("i doesn't equal j");

// WRONG!!

This is legal code, but it is clearly not what the programmer had in mind. When working with nested if statements, you should use curly braces to make your code easier to read. Here is a better way to write the code: if (i = = j) { if (j = = k) System.out.println("i equals k"); } else { System.out.println("i doesn't equal j"); }

Statements

7 March 2002 11:18

47

Java Syntax

An if statement can include an optional else keyword that is followed by a second statement. In this form of the statement, the expression is evaluated, and, if it is true, the first statement is executed. Otherwise, the second statement is executed. For example:

The else if clause The if/else statement is useful for testing a condition and choosing between two statements or blocks of code to execute. But what about when you need to choose between several blocks of code? This is typically done with an else if clause, which is not really new syntax, but a common idiomatic usage of the standard if/else statement. It looks like this: if (n = = 1) { // Execute code block } else if (n = = 2) { // Execute code block } else if (n = = 3) { // Execute code block } else { // If all else fails, }

#1

#2

#3

execute block #4

There is nothing special about this code. It is just a series of if statements, where each if is part of the else clause of the previous statement. Using the else if idiom is preferable to, and more legible than, writing these statements out in their fully nested form: if (n = = 1) { // Execute code block #1 } else { if (n = = 2) { // Execute code block #2 } else { if (n = = 3) { // Execute code block #3 } else { // If all else fails, execute block #4 } } }

The switch Statement An if statement causes a branch in the flow of a program’s execution. You can use multiple if statements, as shown in the previous section, to perform a multiway branch. This is not always the best solution, however, especially when all of the branches depend on the value of a single variable. In this case, it is inefficient to repeatedly check the value of the same variable in multiple if statements. A better solution is to use a switch statement, which is inherited from the C programming language. Although the syntax of this statement is not nearly as elegant as other parts of Java, the brute practicality of the construct makes it worthwhile. If you are not familiar with the switch statement itself, you may at least be familiar with the basic concept, under the name computed goto or jump table. A switch

48

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

statement has an integer expression and a body that contains various numbered entry points. The expression is evaluated, and control jumps to the entry point specified by that value. For example, the following switch statement is equivalent to the repeated if and else/if statements shown in the previous section:

break;

// Start here if n = = 1 // Stop here // Start here if n = = 2

Java Syntax

switch(n) { case 1: // Execute code block #1 break; case 2: // Execute code block #2 break; case 3: // Execute code block #3 break; default:

// Stop here // Start here if n = = 3 // // // //

Stop here If all else fails... Execute code block #4 Stop here

}

As you can see from the example, the various entry points into a switch statement are labeled either with the keyword case, followed by an integer value and a colon, or with the special default keyword, followed by a colon. When a switch statement executes, the interpreter computes the value of the expression in parentheses and then looks for a case label that matches that value. If it finds one, the interpreter starts executing the block of code at the first statement following the case label. If it does not find a case label with a matching value, the interpreter starts execution at the first statement following a special-case default: label. Or, if there is no default: label, the interpreter skips the body of the switch statement altogether. Note the use of the break keyword at the end of each case in the previous code. The break statement is described later in this chapter, but, in this case, it causes the interpreter to exit the body of the switch statement. The case clauses in a switch statement specify only the starting point of the desired code. The individual cases are not independent blocks of code, and they do not have any implicit ending point. Therefore, you must explicitly specify the end of each case with a break or related statement. In the absence of break statements, a switch statement begins executing code at the first statement after the matching case label and continues executing statements until it reaches the end of the block. On rare occasions, it is useful to write code like this that falls through from one case label to the next, but 99% of the time you should be careful to end every case and default section with a statement that causes the switch statement to stop executing. Normally you use a break statement, but return and throw also work. A switch statement can have more than one case clause labeling the same statement. Consider the switch statement in the following method: boolean parseYesOrNoResponse(char response) { switch(response) { case 'y': case 'Y': return true; case 'n': case 'N': return false; default: throw new IllegalArgumentException("Response must be Y or N");

Statements

7 March 2002 11:18

49

} }

There are some important restrictions on the switch statement and its case labels. First, the expression associated with a switch statement must have a byte, char, short, or int value. The floating-point and boolean types are not supported, and neither is long, even though long is an integer type. Second, the value associated with each case label must be a constant value or a constant expression the compiler can evaluate. A case label cannot contain a runtime expression involving variables or method calls, for example. Third, the case label values must be within the range of the data type used for the switch expression. And finally, it is obviously not legal to have two or more case labels with the same value or more than one default label.

The while Statement Just as the if statement is the basic control statement that allows Java to make decisions, the while statement is the basic statement that allows Java to perform repetitive actions. It has the following syntax: while (expression) statement

The while statement works by first evaluating the expression. If it is false, the interpreter skips the statement associated with the loop and moves to the next statement in the program. If it is true, however, the statement that forms the body of the loop is executed, and the expression is reevaluated. Again, if the value of expression is false, the interpreter moves on to the next statement in the program; otherwise it executes the statement again. This cycle continues while the expression remains true (i.e., until it evaluates to false), at which point the while statement ends, and the interpreter moves on to the next statement. You can create an infinite loop with the syntax while(true). Here is an example while loop that prints the numbers 0 to 9: int count = 0; while (count < 10) { System.out.println(count); count++; }

As you can see, the variable count starts off at 0 in this example and is incremented each time the body of the loop runs. Once the loop has executed 10 times, the expression becomes false (i.e., count is no longer less than 10), the while statement finishes, and the Java interpreter can move to the next statement in the program. Most loops have a counter variable like count. The variable names i, j, and k are commonly used as a loop counters, although you should use more descriptive names if it makes your code easier to understand.

50

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

The do Statement A do loop is much like a while loop, except that the loop expression is tested at the bottom of the loop, rather than at the top. This means that the body of the loop is always executed at least once. The syntax is: do statement while ( expression ) ;

int count = 0; do { System.out.println(count); count++; } while(count < 10);

Note that the do loop is much less commonly used than its while cousin. This is because, in practice, it is unusual to encounter a situation where you are sure you always want a loop to execute at least once.

The for Statement The for statement provides a looping construct that is often more convenient than the while and do loops. The for statement takes advantage of a common looping pattern. Most loops have a counter, or state variable of some kind, that is initialized before the loop starts, tested to determine whether to execute the loop body, and then incremented, or updated somehow, at the end of the loop body before the test expression is evaluated again. The initialization, test, and update steps are the three crucial manipulations of a loop variable, and the for statement makes these three steps an explicit part of the loop syntax: for(initialize ; test ; update) statement

This for loop is basically equivalent to the following while loop:* initialize; while(test) { statement; update; }

Placing the initialize, test, and update expressions at the top of a for loop makes it especially easy to understand what the loop is doing, and it prevents * As you’ll see when we consider the continue statement, this while loop is not exactly equivalent to the for loop.

Statements

7 March 2002 11:18

51

Java Syntax

There are a couple of differences to notice between the do loop and the more ordinary while loop. First, the do loop requires both the do keyword to mark the beginning of the loop and the while keyword to mark the end and introduce the loop condition. Also, unlike the while loop, the do loop is terminated with a semicolon. This is because the do loop ends with the loop condition, rather than simply ending with a curly brace that marks the end of the loop body. The following do loop prints the same output as the while loop shown above:

mistakes such as forgetting to initialize or update the loop variable. The interpreter discards the values of the initialize and update expressions, so in order to be useful, these expressions must have side effects. initialize is typically an assignment expression, while update is usually an increment, decrement, or some other assignment. The following for loop prints the numbers 0 to 9, just as the previous while and do loops have done: int count; for(count = 0 ; count < 10 ; count++) System.out.println(count);

Notice how this syntax places all the important information about the loop variable on a single line, making it very clear how the loop executes. Placing the update expression in the for statement itself also simplifies the body of the loop to a single statement; we don’t even need to use curly braces to produce a statement block. The for loop supports some additional syntax that makes it even more convenient to use. Because many loops use their loop variables only within the loop, the for loop allows the initialize expression to be a full variable declaration, so that the variable is scoped to the body of the loop and is not visible outside of it. For example: for(int count = 0 ; count < 10 ; count++) System.out.println(count);

Furthermore, the for loop syntax does not restrict you to writing loops that use only a single variable. Both the initialize and update expressions of a for loop can use a comma to separate multiple initializations and update expressions. For example: for(int i = 0, j = 10 ; i < 10 ; i++, j--) sum += i * j;

Even though all the examples so far have counted numbers, for loops are not restricted to loops that count numbers. For example, you might use a for loop to iterate through the elements of a linked list: for(Node n = listHead; n != null; n = n.nextNode()) process(n);

The initialize, test, and update expressions of a for loop are all optional; only the semicolons that separate the expressions are required. If the test expression is omitted, it is assumed to be true. Thus, you can write an infinite loop as for(;;).

The break Statement A break statement causes the Java interpreter to skip immediately to the end of a containing statement. We have already seen the break statement used with the

52

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

switch statement. The break statement is most often written as simply the keyword break followed by a semicolon: break;

When used in this form, it causes the Java interpreter to immediately exit the innermost containing while, do, for, or switch statement. For example:

The break statement can also be followed by the name of a containing labeled statement. When used in this form, break causes the Java interpreter to immediately exit from the named block, which can be any kind of statement, not just a loop or switch. For example: testfornull: if (data != null) { // If the array is defined, for(int row = 0; row < numrows; row++) { // loop through one dimension, for(int col = 0; col < numcols; col++) { // then loop through the other. if (data[row][col] == null) // If the array is missing data, break testfornull; // treat the array as undefined. } } } // Java interpreter goes here after executing break testfornull

The continue Statement While a break statement exits a loop, a continue statement quits the current iteration of a loop and starts the next one. continue, in both its unlabeled and labeled forms, can be used only within a while, do, or for loop. When used without a label, continue causes the innermost loop to start a new iteration. When used with a label that is the name of a containing loop, it causes the named loop to start a new iteration. For example: for(int i = 0; i < data.length; i++) { if (data[i] == -1) continue; process(data[i]); }

// // // //

Loop through data. If a data value is missing, skip to the next iteration. Process the data value.

while, do, and for loops differ slightly in the way that continue starts a new

iteration: •

With a while loop, the Java interpreter simply returns to the top of the loop, tests the loop condition again, and, if it evaluates to true, executes the body of the loop again.



With a do loop, the interpreter jumps to the bottom of the loop, where it tests the loop condition to decide whether to perform another iteration of the loop.

Statements

7 March 2002 11:18

53

Java Syntax

for(int i = 0; i < data.length; i++) { // Loop through the data array. if (data[i] == target) { // When we find what we're looking for, index = i; // remember where we found it break; // and stop looking! } } // The Java interpreter goes here after executing break



With a for loop, the interpreter jumps to the top of the loop, where it first evaluates the update expression and then evaluates the test expression to decide whether to loop again. As you can see, the behavior of a for loop with a continue statement is different from the behavior of the “basically equivalent” while loop I presented earlier; update gets evaluated in the for loop, but not in the equivalent while loop.

The return Statement A return statement tells the Java interpreter to stop executing the current method. If the method is declared to return a value, the return statement is followed by an expression. The value of the expression becomes the return value of the method. For example, the following method computes and returns the square of a number: double square(double x) { return x * x; }

// A method to compute x squared // Compute and return a value

Some methods are declared void to indicate they do not return any value. The Java interpreter runs methods like this by executing its statements one by one until it reaches the end of the method. After executing the last statement, the interpreter returns implicitly. Sometimes, however, a void method has to return explicitly before reaching the last statement. In this case, it can use the return statement by itself, without any expression. For example, the following method prints, but does not return, the square root of its argument. If the argument is a negative number, it returns without printing anything: void printSquareRoot(double x) { if (x < 0) return; System.out.println(Math.sqrt(x)); }

// // // //

A method to print square root of x If x is negative, return explicitly Print the square root of x End of method: return implicitly

The synchronized Statement Since Java is a multithreaded system, you must often take care to prevent multiple threads from modifying an object simultaneously in a way that might corrupt the object’s state. Sections of code that must not be executed simultaneously are known as critical sections. Java provides the synchronized statement to protect these critical sections. The syntax is: synchronized ( expression ) { statements }

expression is an expression that must evaluate to an object or an array. The statements constitute the code of the critical section and must be enclosed in

curly braces. Before executing the critical section, the Java interpreter first obtains an exclusive lock on the object or array specified by expression. It holds the lock until it is finished running the critical section, then releases it. While a thread holds the lock on an object, no other thread can obtain that lock. Therefore, no other thread can execute this or any other critical sections that require a lock on the same object. If a thread cannot immediately obtain the lock required to execute a critical section, it simply waits until the lock becomes available.

54

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

Note that you do not have to use the synchronized statement unless your program creates multiple threads that share data. If only one thread ever accesses a data structure, there is no need to protect it with synchronized. When you do have to use synchronized, it might be in code like the following:

Java Syntax

public static void SortIntArray(int[] a) { // Sort the array a. This is synchronized so that some other thread // cannot change elements of the array while we're sorting it (at // least not other threads that protect their changes to the array // with synchronized). synchronized (a) { // Do the array sort here } }

The synchronized keyword is also available as a modifier in Java and is more commonly used in this form than as a statement. When applied to a method, the synchronized keyword indicates that the entire method is a critical section. For a synchronized class method (a static method), Java obtains an exclusive lock on the class before executing the method. For a synchronized instance method, Java obtains an exclusive lock on the class instance. (Class and instance methods are discussed in Chapter 3.)

The throw Statement An exception is a signal that indicates some sort of exceptional condition or error has occurred. To thr ow an exception is to signal an exceptional condition. To catch an exception is to handle it—to take whatever actions are necessary to recover from it. In Java, the throw statement is used to throw an exception: throw expression ;

The expression must evaluate to an exception object that describes the exception or error that has occurred. We’ll talk more about types of exceptions shortly; for now, all you need to know is that an exception is represented by an object. Here is some example code that throws an exception: public static double factorial(int x) { if (x < 0) throw new IllegalArgumentException("x must be >= 0"); double fact; for(fact=1.0; x > 1; fact *= x, x--) /* empty */ ; // Note use of the empty statement return fact; }

When the Java interpreter executes a throw statement, it immediately stops normal program execution and starts looking for an exception handler that can catch, or handle, the exception. Exception handlers are written with the try/catch/finally statement, which is described in the next section. The Java interpreter first looks at the enclosing block of code to see if it has an associated exception handler. If so, it exits that block of code and starts running the exception-handling code associ-

Statements

7 March 2002 11:18

55

ated with the block. After running the exception handler, the interpreter continues execution at the statement immediately following the handler code. If the enclosing block of code does not have an appropriate exception handler, the interpreter checks the next higher enclosing block of code in the method. This continues until a handler is found. If the method does not contain an exception handler that can handle the exception thrown by the throw statement, the interpreter stops running the current method and returns to the caller. Now the interpreter starts looking for an exception handler in the blocks of code of the calling method. In this way, exceptions propagate up through the lexical structure of Java methods, up the call stack of the Java interpreter. If the exception is never caught, it propagates all the way up to the main() method of the program. If it is not handled in that method, the Java interpreter prints an error message, prints a stack trace to indicate where the exception occurred, and then exits.

Exception types An exception in Java is an object. The type of this object is java.lang.Throwable, or more commonly, some subclass of Throwable that more specifically describes the type of exception that occurred.* Throwable has two standard subclasses: java.lang.Error and java.lang.Exception. Exceptions that are subclasses of Error generally indicate unrecoverable problems: the virtual machine has run out of memory, or a class file is corrupted and cannot be read, for example. Exceptions of this sort can be caught and handled, but it is rare to do so. Exceptions that are subclasses of Exception, on the other hand, indicate less severe conditions. These are exceptions that can be reasonably caught and handled. They include such exceptions as java.io.EOFException, which signals the end of a file, and java.lang.ArrayIndexOutOfBoundsException, which indicates that a program has tried to read past the end of an array. In this book, I use the term “exception” to refer to any exception object, regardless of whether the type of that exception is Exception or Error. Since an exception is an object, it can contain data, and its class can define methods that operate on that data. The Throwable class and all its subclasses include a String field that stores a human-readable error message that describes the exceptional condition. It’s set when the exception object is created and can be read from the exception with the getMessage() method. Most exceptions contain only this single message, but a few add other data. The java.io.InterruptedIOException, for example, adds a field named bytesTransferred that specifies how much input or output was completed before the exceptional condition interrupted it.

Declaring exceptions In addition to making a distinction between Error and Exception classes, the Java exception-handling scheme also makes a distinction between checked and unchecked exceptions. Any exception object that is an Error is unchecked. Any exception object that is an Exception is checked, unless it is a subclass of java.lang.RuntimeException, in which case it is unchecked. (RuntimeException * We haven’t talked about subclasses yet; they are covered in detail in Chapter 3.

56

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

is a subclass of Exception.) The reason for this distinction is that virtually any method can throw an unchecked exception, at essentially any time. There is no way to predict an OutOfMemoryError, for example, and any method that uses objects or arrays can throw a NullPointerException if it is passed an invalid null argument. Checked exceptions, on the other hand, arise only in specific, welldefined circumstances. If you try to read data from a file, for example, you must at least consider the possibility that a FileNotFoundException will be thrown if the specified file cannot be found.

Even if you never throw an exception yourself, there are times when you must use a throws clause to declare an exception. If your method calls a method that can throw a checked exception, you must either include exception-handling code to handle that exception or use throws to declare that your method can also throw that exception. How do you know if the method you are calling can throw a checked exception? You can look at its method signature to find out. Or, failing that, the Java compiler will tell you (by reporting a compilation error) if you’ve called a method whose exceptions you must handle or declare. The following method reads the first line of text from a named file. It uses methods that can throw various types of java.io.IOException objects, so it declares this fact with a throws clause: public static String readFirstLine(String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); return in.readLine(); }

We’ll talk more about method declarations and method signatures later in this chapter.

The try/catch/finally Statement The try/catch/finally statement is Java’s exception-handling mechanism. The try clause of this statement establishes a block of code for exception handling. This try block is followed by zero or more catch clauses, each of which is a block of statements designed to handle a specific type of exception. The catch clauses are followed by an optional finally block that contains cleanup code guaranteed to be executed regardless of what happens in the try block. Both the catch and finally clauses are optional, but every try block must be accompanied by at least one or the other. The try, catch, and finally blocks all begin and end with curly braces. These are a required part of the syntax and cannot be omitted, even if the clause contains only a single statement.

Statements

7 March 2002 11:18

57

Java Syntax

Java has different rules for working with checked and unchecked exceptions. If you write a method that throws a checked exception, you must use a throws clause to declare the exception in the method signature. The reason these types of exceptions are called checked exceptions is that the Java compiler checks to make sure you have declared them in method signatures and produces a compilation error if you have not. The factorial() method shown earlier throws an exception of type java.lang.IllegalArgumentException. This is a subclass of RuntimeException, so it is an unchecked exception, and we do not have to declare it with a throws clause (although we can if we want to be explicit).

The following code illustrates the syntax and purpose of the try/catch/finally statement: try { // Normally this code runs from the top of the block to the bottom // without problems. But it can sometimes throw an exception, // either directly with a throw statement or indirectly by calling // a method that throws an exception. } catch (SomeException e1) { // This block contains statements that handle an exception object // of type SomeException or a subclass of that type. Statements in // this block can refer to that exception object by the name e1. } catch (AnotherException e2) { // This block contains statements that handle an exception object // of type AnotherException or a subclass of that type. Statements // in this block can refer to that exception object by the name e2. } finally { // This block contains statements that are always executed // after we leave the try clause, regardless of whether we leave it: // 1) normally, after reaching the bottom of the block; // 2) because of a break, continue, or return statement; // 3) with an exception that is handled by a catch clause above; or // 4) with an uncaught exception that has not been handled. // If the try clause calls System.exit(), however, the interpreter // exits before the finally clause can be run. }

try The try clause simply establishes a block of code that either has its exceptions handled or needs special cleanup code to be run when it terminates for any reason. The try clause by itself doesn’t do anything interesting; it is the catch and finally clauses that do the exception-handling and cleanup operations.

catch A try block can be followed by zero or more catch clauses that specify code to handle various types of exceptions. Each catch clause is declared with a single argument that specifies the type of exceptions the clause can handle and also provides a name the clause can use to refer to the exception object it is currently handling. The type and name of an exception handled by a catch clause are exactly like the type and name of an argument passed to a method, except that for a catch clause, the argument type must be Throwable or one of its subclasses. When an exception is thrown, the Java interpreter looks for a catch clause with an argument of the same type as the exception object or a superclass of that type. The interpreter invokes the first such catch clause it finds. The code within a catch block should take whatever action is necessary to cope with the exceptional condition. If the exception is a java.io.FileNotFoundException exception, for example, you might handle it by asking the user to check his spelling and try again. It is not required to have a catch clause for every possible exception; in some cases the correct response is to allow the exception to propagate up and be

58

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

caught by the invoking method. In other cases, such as a programming error signaled by NullPointerException, the correct response is probably not to catch the exception at all, but allow it to propagate and have the Java interpreter exit with a stack trace and an error message.

finally

In the normal case, control reaches the end of the try block and then proceeds to the finally block, which performs any necessary cleanup. If control leaves the try block because of a return, continue, or break statement, the finally block is executed before control transfers to its new destination. If an exception occurs in the try block, and there is an associated catch block to handle the exception, control transfers first to the catch block and then to the finally block. If there is no local catch block to handle the exception, control transfers first to the finally block, and then propagates up to the nearest containing catch clause that can handle the exception. If a finally block itself transfers control with a return, continue, break, or throw statement or by calling a method that throws an exception, the pending control transfer is abandoned, and this new transfer is processed. For example, if a finally clause throws an exception, that exception replaces any exception that was in the process of being thrown. If a finally clause issues a return statement, the method returns normally, even if an exception has been thrown and has not been handled yet. try and finally can be used together without exceptions or any catch clauses. In this case, the finally block is simply cleanup code that is guaranteed to be executed, regardless of any break, continue, or return statements within the try

clause. In previous discussions of the for and continue statements, we’ve seen that a for loop cannot be naively translated into a while loop because the continue statement behaves slightly differently when used in a for loop than it does when used in a while loop. The finally clause gives us a way to write a while loop that handles the continue statement in the same way that a for loop does. Consider the following generalized for loop: for( initialize ; test ; update ) statement

The following while loop behaves the same, even if the statement block contains a continue statement: initialize ; while ( test ) {

Statements

7 March 2002 11:18

59

Java Syntax

The finally clause is generally used to clean up after the code in the try clause (e.g., close files, shut down network connections). What is useful about the finally clause is that it is guaranteed to be executed if any portion of the try block is executed, regardless of how the code in the try block completes. In fact, the only way a try clause can exit without allowing the finally clause to be executed is by invoking the System.exit() method, which causes the Java interpreter to stop running.

try { statement } finally { update ; } }

Note, however, that placing the update statement within a finally block causes this while loop to respond to break statements differently than the for loop does.

The assert Statement An assert statement is used to document and verify design assumptions in Java code. This statement was added in Java 1.4 and cannot be used with previous versions of the language. An assertion consists of the assert keyword followed by a boolean expression that the programmer believes should always evaluate to true. By default, assertions are not enabled, and the assert statement does not actually do anything. It is possible to enable assertions as a debugging and testing tool, however; when this is done, the assert statement evaluates the expression. If it is indeed true, assert does nothing. On the other hand, if the expression evaluates to false, the assertion fails, and the assert statement throws a java.lang.AssertionError. The assert statement may include an optional second expression, separated from the first by a colon. When assertions are enabled, and the first expression evaluates to false, the value of the second expression is taken as an error code or error message and is passed to the AssertionError() constructor. The full syntax of the statement is: assert assertion ;

or: assert assertion : errorcode ;

It is important to remember that the assertion must be a boolean expression, which typically means that it contains a comparison operator or invokes a boolean-valued method.

Compiling assertions Because the assert statement was added in Java 1.4, and because assert was not a reserved word prior to Java 1.4, the introduction of this new statement can cause code that uses “assert” as an identifier to break. For this reason, the javac compiler does not recognize the assert statement by default. To compile Java code that uses the assert statement, you must use the command-line argument -source 1.4. For example: javac -source 1.4 ClassWithAssertions.java

The javac compiler allows “assert” to be used as an identifier unless -source 1.4 is specified. If it finds assert used as an identifier, it issues an incompatibility warning. In future releases, the command-line option may no longer be required, and the assert statement may be recognized by default, so code that uses assert as an identifier should be phased out or fixed.

60

7 March 2002 11:18

Chapter 2 – Java Syntax from the Ground Up

Enabling assertions assert statements encode assumptions that should always be true. For efficiency,

java -ea:com.example.sorters.MergeSort com.example.sorters.Test

To enable assertions for all classes in a package and in all of its subpackages, follow the -ea argument with a colon, the package name, and three dots: java -ea:com.example.sorters... com.example.sorters.Test

You can disable assertions in the same way, using the -da argument. For example, to enable assertions throughout a package and then disable them in a specific class or subpackage, use: java -ea:com.example.sorters... -da:com.example.sorters.QuickSort java -ea:com.example.sorters... -da:com.example.sorters.plugins...

If you prefer verbose command-line arguments, you can use -enableassertions and -disableassertions instead of -ea and -da and -enablesystemassertions instead of -esa. Java 1.4 adds to java.lang.ClassLoader methods for enabling and disabling the assertions for classes loaded through that ClassLoader. If you use a custom class loader in your program and want to turn on assertions, you may be interested in these methods. See ClassLoader in Chapter 11.

Using assertions Because assertions are disabled by default and impose no performance penalty on your code, you can use them liberally to document any assumptions you make while programming. It may take some time to get used to this, but as you do, you’ll find more and more uses for the assert statement. Suppose, for example, that you’re writing a method in such a way that you know that the variable x is either 0 or 1. Without assertions, you might code an if statement that looks like this: if (x = = 0) { ... } else { // x is 1 ... }

The comment in this code is an informal assertion indicating that you believe that within the body of the else clause, x will always equal 1.

Statements

7 March 2002 11:18

61

Java Syntax

it does not make sense to test assertions each time code is executed. Thus, by default, assertions are disabled, and assert statements have no effect. The assertion code remains compiled in the class files, however, so it can always be enabled for testing, diagnostic, and debugging purposes. You can enable assertions, either across the board or selectively, with command-line arguments to the Java interpreter. To enable assertions in all classes except for system classes, use the -ea argument. To enable assertions in system classes, use -esa. To enable assertions within a specific class, use -ea followed by a colon and the classname:

Now suppose that your code is later modified in such a way that x can take on a value other than 0 and 1. The comment and the assumption that go along with it are no longer valid, and this may cause a bug that is not immediately apparent or is difficult to localize. The solution in this situation is to convert your comment into an assert statement. The code becomes: if (x = = 0) { ... } else { assert x = = 1 : x ... }

// x must be 0 or 1

Now, if x somehow ends up holding an unexpected value, an AssertionError is thrown, which makes the bug immediately apparent and easy to pinpoint. Furthermore, the second expression (following the colon) in the assert statement includes the unexpected value of x as the “error message” of the AssertionError. This message is not intended to mean anything to an end user, but to provide enough information so that you know not just that an assertion failed but also what caused it to fail. A similar technique is useful with switch statements. If you write a switch statement without a default clause, you make an assumption about the set of possible values for the switch expression. If you believe that no other value is possible, you can add an assert statement to document and validate that fact. For example: switch(x) { case -1: return LESS; case 0: return EQUALS; case 1: return GREATER; default: assert false:x; // Throw AssertionError if x is not -1, 0, or 1. }

Note that assert false; always fails. This form of the statement is a useful “deadend” statement when you believe that the statement can never be reached. Another common use of the assert statement is to test whether the arguments passed to a method all have values that are legal for that method; this is also known as enforcing method preconditions. For example: private static Object[] subArray(Object[] a, int x, int y) { assert x
Miscellaneous (?>x)

Match x independently of the rest of the expression, without considering whether the match causes the rest of the expression to fail to match. Useful to optimize certain complex regular expressions. A group of this form does not capture the matched text.

(?onflags-offflags)

Don’t match anything, but turn on the flags specified by onflags, and turn off the flags specified by offflags. These two strings are combinations in any order of the following letters and correspond to the following Pattern constants: i (CASE_INSENSITIVE), d (UNIX_LINES), m (MULTILINE), s (DOTALL), u (UNICODE_CASE), and x (COMMENTS). Flag settings specified in this way take effect at the point that they appear in the expression and persist until the end of the expression, or until the end of the parenthesized group of which they are a part, or until overridden by another flag setting expression.

(?onflags-offflags:x)

Match x, applying the specified flags to this subexpression only. This is a noncapturing group, such as (?: . . . ), with the addition of flags.

\Q

Don’t match anything, but quote all subsequent pattern text until \E. All characters within such a quoted section are interpreted as literal characters to match, and none (except \E) have special meanings.

\E

Don’t match anything; terminate a quote started with \Q.

Chapter 17 – java.util and Subpackages

7 March 2002 11:36

725

Pattern Table 17−1. Java regular expression quick refer ence (continued) Syntax

Matches

#comment

If the COMMENT flag is set, pattern text between a # and the end of the line is considered a comment and is ignored.

These repetition characters are known as greedy quantifiers because they match as many occurrences of x as possible while still allowing the rest of the regular expression to match. If you want a “reluctant quantifier,” which matches as few occurrences as possible while still allowing the rest of the regular expression to match, follow the previous quantifiers with a question mark. For example, use *? instead of *, and {2,}? instead of {2,}. Or, if you follow a quantifier with a plus sign instead of a question mark, then you specify a “possessive quantifier,” which matches as many occurrences as possible, even if it means that the rest of the regular expression will not match. Possessive quantifiers can be useful when you are sure that they will not adversely affect the rest of the match, because they can be implemented more efficiently than regular greedy quantifiers. b Anchors do not match characters but instead match the zero-width positions between characters, “anchoring” the match to a position at which a specific condition holds. a

Object

Pattern

Serializable

public final class Pattern implements Serializable { // No Constructor // Public Constants public static final int CANON_EQ; public static final int CASE_INSENSITIVE; public static final int COMMENTS; public static final int DOTALL; public static final int MULTILINE; public static final int UNICODE_CASE; public static final int UNIX_LINES; // Public Class Methods public static Pattern compile(String regex); public static Pattern compile(String regex, int flags); public static boolean matches(String regex, CharSequence input); // Public Instance Methods public int flags(); public Matcher matcher(CharSequence input); public String pattern(); public String[ ] split(CharSequence input); public String[ ] split(CharSequence input, int limit); }

=128 =2 =4 =32 =8 =64 =1

Returned By: Matcher.pattern(), Pattern.compile()

PatternSyntaxException java.util.regex

Java 1.4 serializable unchecked

This exception signals a syntax error in the text representation of a regular expression. An exception of this type may be thrown by the Pattern.compile() and Pattern.matches() methods, and also by the String matches(), replaceFirst(), replaceAll() and split() methods which call those Pattern methods. getPattern() returns the text that contained the syntax error, and getIndex() returns the approximate location of the error within that text, or –1, if the location is not known.

726

7 March 2002 11:36

Chapter 17 – java.util and Subpackages

Package java.util.zip getDescription() returns an error message that provides further detail about the error. The inherited getMessage() method combines the information provided by these other three methods into a single multiline message. Object

Throwable

Exception

RuntimeException

IllegalArgumentException

PatternSyntaxException

Serializable

public class PatternSyntaxException extends IllegalArgumentException { // Public Constructors public PatternSyntaxException(String desc, String regex, int index); // Public Instance Methods public String getDescription(); public int getIndex(); public String getPattern(); // Public Methods Overriding Throwable public String getMessage(); }

Package java.util.zip

Java 1.1

The java.util.zip package contains classes for data compression and decompression. The Deflater and Inflater classes perform data compression and decompression. DeflaterOutputStream and InflaterInputStream apply that functionality to byte streams; the subclasses of these streams implement both the GZIP and ZIP compression formats. The Adler32 and CRC32 classes implement the Checksum interface and compute the checksums required for data compression. Interfaces: public interface Checksum; Classes: public class Adler32 implements Checksum; public class CheckedInputStream extends java.io.FilterInputStream; public class CheckedOutputStream extends java.io.FilterOutputStream; public class CRC32 implements Checksum; public class Deflater; public class DeflaterOutputStream extends java.io.FilterOutputStream; public class GZIPOutputStream extends DeflaterOutputStream; public class ZipOutputStream extends DeflaterOutputStream; public class Inflater; public class InflaterInputStream extends java.io.FilterInputStream; public class GZIPInputStream extends InflaterInputStream; public class ZipInputStream extends InflaterInputStream; public class ZipEntr y implements Cloneable; public class ZipFile; Exceptions: public class DataFormatException extends Exception; public class ZipException extends java.io.IOException;

Chapter 17 – java.util and Subpackages

7 March 2002 11:36

727

Adler32

Adler32

Java 1.1

java.util.zip This class implements the Checksum interface and computes a checksum on a stream of data using the Adler-32 algorithm. This algorithm is significantly faster than the CRC-32 algorithm and is almost as reliable. The CheckedInputStream and CheckedOutputStream classes provide a higher-level interface to computing checksums on streams of data. Object

Adler32

Checksum

public class Adler32 implements Checksum { // Public Constructors public Adler32(); // Public Instance Methods public void update(byte[ ] b); // Methods Implementing Checksum public long getValue(); public void reset(); public void update(int b); public void update(byte[ ] b, int off, int len); }

CheckedInputStream

default:1

Java 1.1

java.util.zip This class is a subclass of java.io.FilterInputStream; it allows a stream to be read and a checksum computed on its contents at the same time. This is useful when you want to check the integrity of a stream of data against a published checksum value. To create a CheckedInputStream, you must specify both the stream it should read and a Checksum object, such as CRC32, that implements the particular checksum algorithm you desire. The read() and skip() methods are the same as those of other input streams. As bytes are read, they are incorporated into the checksum that is being computed. The getChecksum() method does not return the checksum value itself, but rather the Checksum object. You must call the getValue() method of this object to obtain the checksum value. Object

InputStream

FilterInputStream

CheckedInputStream

public class CheckedInputStream extends java.io.FilterInputStream { // Public Constructors public CheckedInputStream(java.io.InputStream in, Checksum cksum); // Public Instance Methods public Checksum getChecksum(); // Public Methods Overriding FilterInputStream public int read() throws java.io.IOException; public int read(byte[ ] buf, int off, int len) throws java.io.IOException; public long skip(long n) throws java.io.IOException; }

CheckedOutputStream

Java 1.1

java.util.zip This class is a subclass of java.io.FilterOutputStream that allows data to be written to a stream and a checksum computed on that data at the same time. To create a CheckedOutputStream, you must specify both the output stream to write its data to and a Checksum object, such as an instance of Adler32, that implements the particular checksum algorithm you desire. The write() methods are similar to those of other OutputStream classes.

728

7 March 2002 11:36

Chapter 17 – java.util and Subpackages

CRC32 The getChecksum() method returns the Checksum object. You must call getValue() on this object in order to obtain the actual checksum value. Object

OutputStream

FilterOutputStream

CheckedOutputStream

public class CheckedOutputStream extends java.io.FilterOutputStream { // Public Constructors public CheckedOutputStream(java.io.OutputStream out, Checksum cksum); // Public Instance Methods public Checksum getChecksum(); // Public Methods Overriding FilterOutputStream public void write(int b) throws java.io.IOException; public void write(byte[ ] b, int off, int len) throws java.io.IOException; }

Checksum

Java 1.1

java.util.zip This interface defines the methods required to compute a checksum on a stream of data. The checksum is computed based on the bytes of data supplied by the update() methods; the current value of the checksum can be obtained at any time with the getValue() method. reset() resets the checksum to its default value; use this method before beginning a new stream of data. The checksum value computed by a Checksum object and returned through the getValue() method must fit into a long value. Therefore, this interface is not suitable for the cryptographic checksum algorithms used in cryptography and security. The classes CheckedInputStream and CheckedOutputStream provide a higher-level API for computing a checksum on a stream of data. See also java.security.MessageDigest. public interface Checksum { // Public Instance Methods public abstract long getValue(); public abstract void reset(); public abstract void update(int b); public abstract void update(byte[ ] b, int off, int len); } Implementations: Adler32, CRC32 Passed To: CheckedInputStream.CheckedInputStream(), CheckedOutputStream.CheckedOutputStream() Returned By: CheckedInputStream.getChecksum(), CheckedOutputStream.getChecksum()

CRC32

Java 1.1

java.util.zip This class implements the Checksum interface and computes a checksum on a stream of data using the CRC-32 algorithm. The CheckedInputStream and CheckedOutputStream classes provide a higher-level interface to computing checksums on streams of data. Object

CRC32

Checksum

public class CRC32 implements Checksum { // Public Constructors public CRC32(); // Public Instance Methods public void update(byte[ ] b);

Chapter 17 – java.util and Subpackages

7 March 2002 11:36

729

CRC32

// Methods Implementing Checksum public long getValue(); public void reset(); public void update(int b); public void update(byte[ ] b, int off, int len); }

default:0

Type Of: GZIPInputStream.crc, GZIPOutputStream.crc

DataFormatException

Java 1.1 serializable checked

java.util.zip

Signals that invalid or corrupt data has been encountered while uncompressing data. Object

Throwable

Exception

DataFormatException

Serializable

public class DataFormatException extends Exception { // Public Constructors public DataFormatException(); public DataFormatException(String s); } Thrown By: Inflater.inflate()

Deflater

Java 1.1

java.util.zip This class implements the general ZLIB data-compression algorithm used by the gzip and PKZip compression programs. The constants defined by this class are used to specify the compression strategy and the compression speed/strength tradeoff level to be used. If you set the nowrap argument to the constructor to true, the ZLIB header and checksum data are omitted from the compressed output, which is the format both gzip and PKZip use. The important methods of this class are setInput(), which specifies input data to be compressed, and deflate(), which compresses the data and returns the compressed output. The remaining methods exist so that Deflater can be used for stream-based compression, as it is in higher-level classes, such as GZIPOutputStream and ZipOutputStream. These stream classes are sufficient in most cases. Most applications do not need to use Deflater directly. The Inflater class uncompresses data compressed with a Deflater object. public class Deflater { // Public Constructors public Deflater(); public Deflater(int level); public Deflater(int level, boolean nowrap); // Public Constants public static final int BEST_COMPRESSION; public static final int BEST_SPEED; public static final int DEFAULT_COMPRESSION; public static final int DEFAULT_STRATEGY; public static final int DEFLATED; public static final int FILTERED; public static final int HUFFMAN_ONLY; public static final int NO_COMPRESSION;

730

7 March 2002 11:36

Chapter 17 – java.util and Subpackages

=9 =1 =-1 =0 =8 =1 =2 =0

DeflaterOutputStream

// Property Accessor Methods (by property name) public int getAdler(); public int getTotalIn(); public int getTotalOut(); // Public Instance Methods public int deflate(byte[ ] b); public int deflate(byte[ ] b, int off, int len); public void end(); public void finish(); public boolean finished(); public boolean needsInput(); public void reset(); public void setDictionar y(byte[ ] b); public void setDictionar y(byte[ ] b, int off, int len); public void setInput(byte[ ] b); public void setInput(byte[ ] b, int off, int len); public void setLevel(int level); public void setStrategy(int strategy); // Protected Methods Overriding Object protected void finalize(); }

synchronized default:1 synchronized default:0 synchronized default:0

synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized

Passed To: DeflaterOutputStream.DeflaterOutputStream() Type Of: DeflaterOutputStream.def

DeflaterOutputStream

Java 1.1

java.util.zip This class is a subclass of java.io.FilterOutputStream; it filters a stream of data by compressing (deflating) it and then writing the compressed data to another output stream. To create a DeflaterOutputStream, you must specify both the stream it is to write to and a Deflater object to perform the compression. You can set various options on the Deflater object to specify just what type of compression is to be performed. Once a DeflaterOutputStream is created, its write() and close() methods are the same as those of other output streams. The InflaterInputStream class can read data written with a DeflaterOutputStream. A DeflaterOutputStream writes raw compressed data; applications often prefer one of its subclasses, GZIPOutputStream or ZipOutputStream, that wraps the raw compressed data within a standard file format. Object

OutputStream

FilterOutputStream

DeflaterOutputStream

public class DeflaterOutputStream extends java.io.FilterOutputStream { // Public Constructors public DeflaterOutputStream(java.io.OutputStream out); public DeflaterOutputStream(java.io.OutputStream out, Deflater def); public DeflaterOutputStream(java.io.OutputStream out, Deflater def, int size); // Public Instance Methods public void finish() throws java.io.IOException; // Public Methods Overriding FilterOutputStream public void close() throws java.io.IOException; public void write(int b) throws java.io.IOException; public void write(byte[ ] b, int off, int len) throws java.io.IOException; // Protected Instance Methods protected void deflate() throws java.io.IOException; // Protected Instance Fields

Chapter 17 – java.util and Subpackages

7 March 2002 11:36

731

DeflaterOutputStream

protected byte[ ] buf; protected Deflater def; } Subclasses: GZIPOutputStream, ZipOutputStream

GZIPInputStream

Java 1.1

java.util.zip This class is a subclass of InflaterInputStream that reads and uncompresses data compressed in gzip format. To create a GZIPInputStream, simply specify the InputStream to read compressed data from and, optionally, a buffer size for the internal decompression buffer. Once a GZIPInputStream is created, you can use the read() and close() methods as you would with any input stream. Object

InputStream

FilterInputStream

InflaterInputStream

GZIPInputStream

public class GZIPInputStream extends InflaterInputStream { // Public Constructors public GZIPInputStream(java.io.InputStream in) throws java.io.IOException; public GZIPInputStream(java.io.InputStream in, int size) throws java.io.IOException; // Public Constants public static final int GZIP_MAGIC; // Public Methods Overriding InflaterInputStream public void close() throws java.io.IOException; public int read(byte[ ] buf, int off, int len) throws java.io.IOException; // Protected Instance Fields protected CRC32 crc; protected boolean eos; }

GZIPOutputStream

=35615

Java 1.1

java.util.zip This class is a subclass of DeflaterOutputStream that compresses and writes data using the gzip file format. To create a GZIPOutputStream, specify the OutputStream to write to and, optionally, a size for the internal compression buffer. Once the GZIPOutputStream is created, you can use the write() and close() methods as you would any output stream. Object

OutputStream

FilterOutputStream

DeflaterOutputStream

GZIPOutputStream

public class GZIPOutputStream extends DeflaterOutputStream { // Public Constructors public GZIPOutputStream(java.io.OutputStream out) throws java.io.IOException; public GZIPOutputStream(java.io.OutputStream out, int size) throws java.io.IOException; // Public Methods Overriding DeflaterOutputStream public void finish() throws java.io.IOException; public void write(byte[ ] buf, int off, int len) throws java.io.IOException; // Protected Instance Fields protected CRC32 crc; }

732

7 March 2002 11:36

Chapter 17 – java.util and Subpackages

synchronized

InflaterInputStream

Inflater

Java 1.1

java.util.zip This class implements the general ZLIB data-decompression algorithm used by gzip, PKZip, and other data-compression applications. It decompresses or inflates data compressed through the Deflater class. The important methods of this class are setInput(), which specifies input data to be decompressed, and inflate(), which decompresses the input data into an output buffer. A number of other methods exist so that this class can be used for stream-based decompression, as it is in the higher-level classes, such as GZIPInputStream and ZipInputStream. These stream-based classes are sufficient in most cases. Most applications do not need to use Inflater directly. public class Inflater { // Public Constructors public Inflater(); public Inflater(boolean nowrap); // Property Accessor Methods (by property name) public int getAdler(); public int getRemaining(); public int getTotalIn(); public int getTotalOut(); // Public Instance Methods public void end(); public boolean finished(); public int inflate(byte[ ] b) throws DataFormatException; public int inflate(byte[ ] b, int off, int len) throws DataFormatException; public boolean needsDictionar y(); public boolean needsInput(); public void reset(); public void setDictionar y(byte[ ] b); public void setDictionar y(byte[ ] b, int off, int len); public void setInput(byte[ ] b); public void setInput(byte[ ] b, int off, int len); // Protected Methods Overriding Object protected void finalize(); }

synchronized default:1 synchronized default:0 synchronized default:0 synchronized default:0 synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized

Passed To: InflaterInputStream.InflaterInputStream() Type Of: InflaterInputStream.inf

InflaterInputStream

Java 1.1

java.util.zip This class is a subclass of java.io.FilterInputStream; it reads a specified stream of compressed input data (typically, one that was written with DeflaterOutputStream or a subclass) and filters that data by uncompressing (inflating) it. To create an InflaterInputStream, specify both the input stream to read from and an Inflater object to perform the decompression. Once an InflaterInputStream is created, the read() and skip() methods are the same as those of other input streams. The InflaterInputStream uncompresses raw data. Applications often prefer one of its subclasses, GZIPInputStream or ZipInputStream, that work with compressed data written in the standard gzip and PKZip file formats. Object

InputStream

FilterInputStream

InflaterInputStream

Chapter 17 – java.util and Subpackages

7 March 2002 11:36

733

InflaterInputStream

public class InflaterInputStream extends java.io.FilterInputStream { // Public Constructors public InflaterInputStream(java.io.InputStream in); public InflaterInputStream(java.io.InputStream in, Inflater inf); public InflaterInputStream(java.io.InputStream in, Inflater inf, int size); // Public Methods Overriding FilterInputStream 1.2 public int available() throws java.io.IOException; 1.2 public void close() throws java.io.IOException; public int read() throws java.io.IOException; public int read(byte[ ] b, int off, int len) throws java.io.IOException; public long skip(long n) throws java.io.IOException; // Protected Instance Methods protected void fill() throws java.io.IOException; // Protected Instance Fields protected byte[ ] buf; protected Inflater inf; protected int len; } Subclasses: GZIPInputStream, ZipInputStream

ZipEntr y

Java 1.1 cloneable

java.util.zip

This class describes a single entry (typically a compressed file) stored within a ZIP file. The various methods get and set various pieces of information about the entry. The ZipEntr y class is used by ZipFile and ZipInputStream, which read ZIP files, and by ZipOutputStream, which writes ZIP files. When you are reading a ZIP file, a ZipEntr y object returned by ZipFile or ZipInputStream contains the name, size, modification time, and other information about an entry in the file. When writing a ZIP file, on the other hand, you must create your own ZipEntr y objects and initialize them to contain the entry name and other appropriate information before writing the contents of the entry. Object

ZipEntry

Cloneable

ZipConstants

public class ZipEntr y implements Cloneable { // Public Constructors public ZipEntr y(String name); 1.2 public ZipEntr y(ZipEntry e); // Public Constants public static final int DEFLATED; public static final int STORED; // Property Accessor Methods (by property name) public String getComment(); public void setComment(String comment); public long getCompressedSize(); 1.2 public void setCompressedSize(long csize); public long getCrc(); public void setCrc(long crc); public boolean isDirector y(); public byte[ ] getExtra(); public void setExtra(byte[ ] extra);

734

7 March 2002 11:36

Chapter 17 – java.util and Subpackages

=8 =0

ZipFile

public int getMethod(); public void setMethod(int method); public String getName(); public long getSize(); public void setSize(long size); public long getTime(); public void setTime(long time); // Public Methods Overriding Object 1.2 public Object clone(); 1.2 public int hashCode(); public String toString(); } Subclasses: java.util.jar.JarEntr y Passed To: java.util.jar.JarEntr y.JarEntr y(), java.util.jar.JarFile.getInputStream(), java.util.jar.JarOutputStream.putNextEntr y(), ZipEntr y.ZipEntr y(), ZipFile.getInputStream(), ZipOutputStream.putNextEntr y() Returned By: java.util.jar.JarFile.getEntr y(), java.util.jar.JarInputStream.{createZipEntr y(), getNextEntr y()}, ZipFile.getEntr y(), ZipInputStream.{createZipEntr y(), getNextEntr y()}

ZipException

Java 1.1 serializable checked

java.util.zip Signals that an error has occurred in reading or writing a ZIP file. Object

Throwable

Exception

IOException

ZipException

Serializable

public class ZipException extends java.io.IOException { // Public Constructors public ZipException(); public ZipException(String s); } Subclasses: java.util.jar.JarException Thrown By: ZipFile.ZipFile()

ZipFile

Java 1.1

java.util.zip This class reads the contents of ZIP files. It uses a random-access file internally so that the entries of the ZIP file do not have to be read sequentially, as they do with the ZipInputStream class. A ZipFile object can be created by specifying the ZIP file to be read either as a String filename or as a File object. In Java 1.3, temporary ZIP files can be marked for automatic deletion when they are closed. To take advantage of this feature, pass ZipFile.OPEN_READ|ZipFile.OPEN_DELETE as the mode argument to the ZipFile() constructor. Once a ZipFile is created, the getEntr y() method returns a ZipEntr y object for a named entry, and the entries() method returns an Enumeration object that allows you to loop through all the ZipEntr y objects for the file. To read the contents of a specific ZipEntr y

Chapter 17 – java.util and Subpackages

7 March 2002 11:36

735

ZipFile within the ZIP file, pass the ZipEntr y to getInputStream(); this returns an InputStream object from which you can read the entry’s contents. Object

ZipFile

ZipConstants

public class ZipFile { // Public Constructors public ZipFile(String name) throws java.io.IOException; public ZipFile(java.io.File file) throws ZipException, java.io.IOException; 1.3 public ZipF ile(java.io.F ile file, int mode) throws java.io.IOException; // Public Constants 1.3 public static final int OPEN_DELETE; 1.3 public static final int OPEN_READ; // Public Instance Methods public void close() throws java.io.IOException; public java.util.Enumeration entries(); public ZipEntry getEntr y(String name); public java.io.InputStream getInputStream(ZipEntry entry) throws java.io.IOException; public String getName(); 1.2 public int size(); // Protected Methods Overriding Object 1.3 protected void finalize() throws java.io.IOException; }

=4 =1

Subclasses: java.util.jar.JarFile

ZipInputStream

Java 1.1

java.util.zip This class is a subclass of InflaterInputStream that reads the entries of a ZIP file in sequential order. Create a ZipInputStream by specifying the InputStream from which it is to read the contents of the ZIP file. Once the ZipInputStream is created, you can use getNextEntr y() to begin reading data from the next entry in the ZIP file. This method must be called before read() is called to begin reading the first entry. getNextEntr y() returns a ZipEntr y object that describes the entry being read, or null when there are no more entries to be read from the ZIP file. The read() methods of ZipInputStream read until the end of the current entry and then return –1, indicating that there is no more data to read. To continue with the next entry in the ZIP file, you must call getNextEntr y() again. Similarly, the skip() method only skips bytes within the current entry. closeEntr y() can be called to skip the remaining data in the current entry, but it is usually easier simply to call getNextEntr y() to begin the next entry. Object

InputStream

FilterInputStream

InflaterInputStream

ZipInputStream ZipConstants

public class ZipInputStream extends InflaterInputStream { // Public Constructors public ZipInputStream(java.io.InputStream in); // Public Instance Methods public void closeEntr y() throws java.io.IOException; public ZipEntry getNextEntr y() throws java.io.IOException; // Public Methods Overriding InflaterInputStream 1.2 public int available() throws java.io.IOException; public void close() throws java.io.IOException;

736

7 March 2002 11:36

Chapter 17 – java.util and Subpackages

ZipOutputStream

public int read(byte[ ] b, int off, int len) throws java.io.IOException; public long skip(long n) throws java.io.IOException; // Protected Instance Methods 1.2 protected ZipEntry createZipEntr y(String name); } Subclasses: java.util.jar.JarInputStream

ZipOutputStream

Java 1.1

java.util.zip This class is a subclass of DeflaterOutputStream that writes data in ZIP file format to an output stream. Before writing any data to the ZipOutputStream, you must begin an entry within the ZIP file with putNextEntr y(). The ZipEntr y object passed to this method should specify at least a name for the entry. Once you have begun an entry with putNextEntr y(), you can write the contents of that entry with the write() methods. When you reach the end of an entry, you can begin a new one by calling putNextEntr y() again, you can close the current entry with closeEntr y(), or you can close the stream itself with close(). Before beginning an entry with putNextEntr y(), you can set the compression method and level with setMethod() and setLevel(). The constants DEFLATED and STORED are the two legal values for setMethod(). If you use STORED, the entry is stored in the ZIP file without any compression. If you use DEFLATED, you can also specify the compression speed/strength tradeoff by passing a number from 1 to 9 to setLevel(), in which 9 gives the strongest and slowest level of compression. You can also use the constants Deflater.BEST_SPEED, Deflater.BEST_COMPRESSION, and Deflater.DEFAULT_COMPRESSION with the setLevel() method. If you are storing an entry without compression, the ZIP file format requires that you specify, in advance, the entry size and CRC-32 checksum in the ZipEntr y object for the entry. An exception is thrown if these values are not specified or specified incorrectly. Object

OutputStream

FilterOutputStream

DeflaterOutputStream

ZipOutputStream ZipConstants

public class ZipOutputStream extends DeflaterOutputStream { // Public Constructors public ZipOutputStream(java.io.OutputStream out); // Public Constants public static final int DEFLATED; public static final int STORED; // Public Instance Methods public void closeEntr y() throws java.io.IOException; public void putNextEntr y(ZipEntry e) throws java.io.IOException; public void setComment(String comment); public void setLevel(int level); public void setMethod(int method); // Public Methods Overriding DeflaterOutputStream public void close() throws java.io.IOException; public void finish() throws java.io.IOException; public void write(byte[ ] b, int off, int len) throws java.io.IOException; }

=8 =0

synchronized

Subclasses: java.util.jar.JarOutputStream

Chapter 17 – java.util and Subpackages

7 March 2002 11:36

737

CHAPTER 18

javax.crypto and Subpackages

This chapter documents the cryptographic features (including encryption and decryption) of the javax.cr ypto package and its subpackages. These packages were originally part of the Java Cryptography Extension (JCE) before being integrated into Java 1.4, which is why they have the “javax” extension prefix. All of the commonly used cryptography classes are in the javax.cr ypto package itself. The javax.cr ypto.interfaces subpackage defines algorithm-specific interfaces for certain type of cryptographic keys. The javax.cr ypto.spec subpackage defines classes that provide a transparent, portable, and provider-independent representation of cryptographic keys and related objects.

Package javax.cr ypto

Java 1.4

The javax.cr ypto package defines classes and interfaces for various cryptographic operations. The central class is Cipher, which is used to encrypt and decrypt data. CipherInputStream and CipherOutputStream are utility classes that use a Cipher object to encrypt or decrypt streaming data. SealedObject is another important utility class that uses a Cipher object to encrypt an arbitrary serializable Java object. The KeyGenerator class creates the SecretKey objects used by Cipher for encryption and decryption. SecretKeyFactor y encodes and decodes SecretKey objects. The KeyAgreement class enables two or more parties to agree on a SecretKey in such a way that an eavesdropper cannot determine the key. The Mac class computes a message authentication code (MAC) that can ensure the integrity of a transmission between two parties who share a SecretKey. A MAC is akin to a digital signature, except that it is based on a secret key instead of a public/private key pair. Like the java.security package, the javax.cr ypto package is provider-based, so that arbitrary cryptographic implementations may be plugged into any Java installation. Various classes in this package have names that end in Spi. These classes define a serviceprovider interface and must be implemented by each cryptographic provider that wishes to provide an implementation of a particular cryptographic service or algorithm. This package was originally shipped as part of the Java Cryptography Extension ( JCE), but it has been added to the core platform in Java 1.4. A version of the JCE is still available (see http://java.sun.com/security/) as a standard extension for Java 1.2 and Java 1.3. This package is distributed with a cryptographic provider named “SunJCE” that

738

7 March 2002 11:38

BadPaddingException includes a robust set of implementations for Cipher, KeyAgreement, Mac, and other classes. This provider is installed by the default java.security properties in Java 1.4 distributions. A full tutorial on cryptography is beyond the scope of this chapter and of this book. In order to use this package, you need to have a basic understanding of cryptographic algorithms such as DES. In order to take full advantage of this package, you also need to have a detailed understanding of things like feedback modes, padding schemes, the Diffie-Hellman key-agreement protocol, and so on. For a good introduction to modern cryptography in Java, see Java Cryptography (O’Reilly). For more in-depth coverage, not specific to Java, see Applied Cryptography (Wiley). Interface: public interface SecretKey extends java.security.Key; Classes: public class Cipher; public class NullCipher extends Cipher; public class CipherInputStream extends java.io.FilterInputStream; public class CipherOutputStream extends java.io.FilterOutputStream; public abstract class CipherSpi; public class EncryptedPrivateKeyInfo; public class ExemptionMechanism; public abstract class ExemptionMechanismSpi; public class KeyAgreement; public abstract class KeyAgreementSpi; public class KeyGenerator ; public abstract class KeyGeneratorSpi; public class Mac implements Cloneable; public abstract class MacSpi; public class SealedObject implements Serializable; public class SecretKeyFactor y; public abstract class SecretKeyFactor ySpi; Exceptions: public class BadPaddingException extends java.security.GeneralSecurityException; public class ExemptionMechanismException extends java.security.GeneralSecurityException; public class IllegalBlockSizeException extends java.security.GeneralSecurityException; public class NoSuchPaddingException extends java.security.GeneralSecurityException; public class ShortBufferException extends java.security.GeneralSecurityException;

BadPaddingException

Java 1.4 serializable checked

javax.cr ypto

This exception signals that input data to a Cipher is not padded correctly. Object

Throwable

Exception

GeneralSecurityException

BadPaddingException

Serializable

public class BadPaddingException extends java.security.GeneralSecurityException { // Public Constructors public BadPaddingException(); public BadPaddingException(String msg); }

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

739

BadPaddingException Thrown By: Cipher.doFinal(), CipherSpi.engineDoFinal(), SealedObject.getObject()

Cipher

Java 1.4

javax.cr ypto This class performs encryption and decryption of byte arrays. Cipher is provider-based, so to obtain a Cipher object, you must call the static getInstance() factory method. The arguments to this method are a string that describes the type of encryption desired and, optionally, the name of the provider whose implementation should be used. To specify the desired type of encryption, you can simply specify the name of an encryption algorithm, such as “DES”. Or you can specify a three-part name that includes the encryption algorithm, the algorithm operating mode, and the padding scheme. These three parts are separated by slash characters, as in “DES/CBC/PKCS5Padding”. Finally, if you are requesting a block cipher algorithm in a stream mode, you can specify the number of bits to be processed at a time by following the name of the feedback mode with a number of bits. For example: “DES/CFB8/NoPadding”. The “SunJCE” provider supports the following cryptographic algorithms: “DES” The Digital Encryption Standard. “DESede” Triple DES encryption, also known as “TripleDES”. “Blowfish” The Blowfish block cipher designed by Bruce Schneier. “PBEWithMD5AndDES” A password-based encryption scheme specified in PKCS#5. This algorithm implicitly uses “CBC” mode and the “PKCS5Padding” padding; it cannot be used with other modes or padding schemes. “PBEWithMD5AndTripleDES” A password-based encryption similar to “PBEWithMD5AndDES”, but uses DESede instead of DES. SunJCE supports the following operating modes: “ECB” Electronic Codebook mode “CBC” Cipher Block Chaining mode “CFB” Cipher Feedback mode “OFB” Output Feedback mode “PCBC” Plaintext Cipher Block Chaining mode Finally, the “SunJCE” provider also supports two padding schemes: “NoPadding” and “PKCS5Padding”. The name “SSL3Padding” is reserved, but this padding scheme is not implemented in the current release of “SunJCE”. Once you have obtained a Cipher object for the desired cryptographic algorithm, mode, and padding scheme, you must initialize it by calling one of the init() methods. The first

740

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

Cipher argument to init() is one of the constants ENCRYPT_MODE or DECRYPT_MODE. The second argument is a java.security.Key object that performs the encryption or decryption. If you use one of the symmetric (i.e., non-public key) encryption algorithms supported by the “SunJCE” provider, this Key object is a SecretKey implementation. You can optionally pass a java.security.SecureRandom object to init() to provide a source of randomness. If you do not, the Cipher implementation provides its own pseudo-random number generator. Some cryptographic algorithms require additional initialization parameters; these can be passed to init() as a java.security.AlgorithmParameters object or as a java.security.spec.AlgorithmParameterSpec object. When encrypting, you can omit these parameters, and the Cipher implementation uses default values or generates appropriate random parameters for you. In this case, you should call getParameters() after performing encryption to obtain the AlgorithmParameters used to encrypt. These parameters are required in order to decrypt, and must therefore be saved or transferred along with the encrypted data. Of the algorithms supported by the “SunJCE” provider, the block ciphers “DES”, “DESede”, and “Blowfish” all require an initialization vector when they are used in “CBC”, “CFB”, “OFB”, or “PCBC” mode. You can represent an initialization vector with a javax.cr ypto.spec.IvParameterSpec object and obtain the raw bytes of the initialization vector used by a Cipher with the getIV() method. The “PBEWithMD5AndDES” algorithm requires a salt and iteration count as parameters. These can be specified with a javax.cr ypto.spec.PBEParameterSpec object. Once you have obtained and initialized a Cipher object, you are ready to use it for encryption or decryption. If you have only a single array of bytes to encrypt or decrypt, pass that input array to one of the doFinal() methods. Some versions of this method return the encrypted or decrypted bytes as the return value of the function. Other versions store the encrypted or decrypted bytes to another byte array you specify. If you choose to use one of these latter methods, you should first call getOutputSize() to determine the required size of the output array. If you want to encrypt or decrypt data from a streaming source or have more than one array of data, pass the data to one of the update() methods, calling it as many times as necessary. Then pass the last array of data to one of the doFinal() methods. If you are working with streaming data, consider using the CipherInputStream and CipherOutputStream classes instead. public class Cipher { // Protected Constructors protected Cipher(CipherSpi cipherSpi, java.security.Provider provider, String transformation); // Public Constants public static final int DECRYPT_MODE; public static final int ENCRYPT_MODE; public static final int PRIVATE_KEY; public static final int PUBLIC_KEY; public static final int SECRET_KEY; public static final int UNWRAP_MODE; public static final int WRAP_MODE; // Public Class Methods public static final Cipher getInstance(String transformation) throws java.security.NoSuchAlgorithmException, NoSuchPaddingException; public static final Cipher getInstance(String transformation, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException, NoSuchPaddingException; public static final Cipher getInstance(String transformation, java.security.Provider provider) throws java.security.NoSuchAlgorithmException, NoSuchPaddingException; // Property Accessor Methods (by property name) public final String getAlgorithm(); public final int getBlockSize();

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

=2 =1 =2 =1 =3 =4 =3

741

Cipher

public final ExemptionMechanism getExemptionMechanism(); public final byte[ ] getIV(); public final java.security.AlgorithmParameters getParameters(); public final java.security.Provider getProvider(); // Public Instance Methods public final byte[ ] doFinal() throws IllegalStateException, IllegalBlockSizeException, BadPaddingException; public final byte[ ] doFinal(byte[ ] input) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException; public final int doFinal(byte[ ] output, int outputOffset) throws IllegalStateException, IllegalBlockSizeException, ShortBufferException, BadPaddingException; public final byte[ ] doFinal(byte[ ] input, int inputOffset, int inputLen) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException; public final int doFinal(byte[ ] input, int inputOffset, int inputLen, byte[ ] output) throws IllegalStateException, ShortBufferException, IllegalBlockSizeException, BadPaddingException; public final int doFinal(byte[ ] input, int inputOffset, int inputLen, byte[ ] output, int outputOffset) throws IllegalStateException, ShortBufferException, IllegalBlockSizeException, BadPaddingException; public final int getOutputSize(int inputLen) throws IllegalStateException; public final void init(int opmode, java.security.cert.Certificate certificate) throws java.security.InvalidKeyException; public final void init(int opmode, java.security.Key key) throws java.security.InvalidKeyException; public final void init(int opmode, java.security.cert.Certificate certificate, java.security.SecureRandom random) throws java.security.InvalidKeyException; public final void init(int opmode, java.security.Key key, java.security.AlgorithmParameters params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; public final void init(int opmode, java.security.Key key, java.security.SecureRandom random) throws java.security.InvalidKeyException; public final void init(int opmode, java.security.Key key, java.security.spec.AlgorithmParameterSpec params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; public final void init(int opmode, java.security.Key key, java.security.spec.AlgorithmParameterSpec params, java.security.SecureRandom random) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; public final void init(int opmode, java.security.Key key, java.security.AlgorithmParameters params, java.security.SecureRandom random) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; public final java.security.Key unwrap(byte[ ] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType) throws IllegalStateException, java.security.InvalidKeyException, java.security.NoSuchAlgorithmException; public final byte[ ] update(byte[ ] input) throws IllegalStateException; public final byte[ ] update(byte[ ] input, int inputOffset, int inputLen) throws IllegalStateException; public final int update(byte[ ] input, int inputOffset, int inputLen, byte[ ] output) throws IllegalStateException, ShortBufferException; public final int update(byte[ ] input, int inputOffset, int inputLen, byte[ ] output, int outputOffset) throws IllegalStateException, ShortBufferException; public final byte[ ] wrap(java.security.Key key) throws IllegalStateException, IllegalBlockSizeException, java.security.InvalidKeyException; } Subclasses: NullCipher Passed To: CipherInputStream.CipherInputStream(), CipherOutputStream.CipherOutputStream(), Encr yptedPrivateKeyInfo.getKeySpec(), SealedObject.{getObject(), SealedObject()} Returned By: Cipher.getInstance()

742

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

CipherSpi

CipherInputStream

Java 1.4

javax.cr ypto This class is an input stream that uses a Cipher object to encrypt or decrypt the bytes it reads from another stream. You must initialize the Cipher object before passing it to the CipherInputStream() constructor. Object

InputStream

FilterInputStream

CipherInputStream

public class CipherInputStream extends java.io.FilterInputStream { // Public Constructors public CipherInputStream(java.io.InputStream is, Cipher c); // Protected Constructors protected CipherInputStream(java.io.InputStream is); // Public Methods Overriding FilterInputStream public int available() throws java.io.IOException; public void close() throws java.io.IOException; public boolean markSupported(); public int read() throws java.io.IOException; public int read(byte[ ] b) throws java.io.IOException; public int read(byte[ ] b, int off, int len) throws java.io.IOException; public long skip(long n) throws java.io.IOException; }

CipherOutputStream

constant

Java 1.4

javax.cr ypto This class is an output stream that uses a Cipher object to encrypt or decrypt bytes before passing them to another output stream. You must initialize the Cipher object before passing it to the CipherOutputStream() constructor. If you are using a Cipher with any kind of padding, you must not call flush() until you are done writing all data to the stream; otherwise decryption fails. Object

OutputStream

FilterOutputStream

CipherOutputStream

public class CipherOutputStream extends java.io.FilterOutputStream { // Public Constructors public CipherOutputStream(java.io.OutputStream os, Cipher c); // Protected Constructors protected CipherOutputStream(java.io.OutputStream os); // Public Methods Overriding FilterOutputStream public void close() throws java.io.IOException; public void flush() throws java.io.IOException; public void write(int b) throws java.io.IOException; public void write(byte[ ] b) throws java.io.IOException; public void write(byte[ ] b, int off, int len) throws java.io.IOException; }

CipherSpi

Java 1.4

javax.cr ypto This abstract class defines the service-provider interface for Cipher. A cryptographic provider must implement a concrete subclass of this class for each encryption algorithm it supports. A provider can implement a separate class for each combination of algorithm, mode, and padding scheme it supports or implement more general classes and

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

743

CipherSpi leave the mode and/or padding scheme to be specified in calls to engineSetMode() and engineSetPadding(). Applications never need to use or subclass this class. public abstract class CipherSpi { // Public Constructors public CipherSpi(); // Protected Instance Methods protected abstract byte[ ] engineDoFinal(byte[ ] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException; protected abstract int engineDoFinal(byte[ ] input, int inputOffset, int inputLen, byte[ ] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException; protected abstract int engineGetBlockSize(); protected abstract byte[ ] engineGetIV(); protected int engineGetKeySize(java.security.Key key) throws java.security.InvalidKeyException; protected abstract int engineGetOutputSize(int inputLen); protected abstract java.security.AlgorithmParameters engineGetParameters(); protected abstract void engineInit(int opmode, java.security.Key key, java.security.SecureRandom random) throws java.security.InvalidKeyException; protected abstract void engineInit(int opmode, java.security.Key key, java.security.AlgorithmParameters params, java.security.SecureRandom random) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; protected abstract void engineInit(int opmode, java.security.Key key, java.security.spec.AlgorithmParameterSpec params, java.security.SecureRandom random) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; protected abstract void engineSetMode(String mode) throws java.security.NoSuchAlgorithmException; protected abstract void engineSetPadding(String padding) throws NoSuchPaddingException; protected java.security.Key engineUnwrap(byte[ ] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType) throws java.security.InvalidKeyException, java.security.NoSuchAlgorithmException; protected abstract byte[ ] engineUpdate(byte[ ] input, int inputOffset, int inputLen); protected abstract int engineUpdate(byte[ ] input, int inputOffset, int inputLen, byte[ ] output, int outputOffset) throws ShortBufferException; protected byte[ ] engineWrap(java.security.Key key) throws IllegalBlockSizeException, java.security.InvalidKeyException; } Passed To: Cipher.Cipher()

Encr yptedPrivateKeyInfo

Java 1.4

javax.cr ypto This class represents an encrypted private key. getEncr yptedData() returns the encrypted bytes. getAlgName() and getAlgParameters() return the algorithm name and parameters used to encrypt it. Pass a Cipher object to getKeySpec() to decrypt the key. public class Encr yptedPrivateKeyInfo { // Public Constructors public Encr yptedPrivateKeyInfo(byte[ ] encoded) throws java.io.IOException; public Encr yptedPrivateKeyInfo(java.security.AlgorithmParameters algParams, byte[ ] encryptedData) throws java.security.NoSuchAlgorithmException; public Encr yptedPrivateKeyInfo(String algName, byte[ ] encryptedData) throws java.security.NoSuchAlgorithmException; // Public Instance Methods public String getAlgName(); public java.security.AlgorithmParameters getAlgParameters();

744

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

ExemptionMechanism

public byte[ ] getEncoded() throws java.io.IOException; public byte[ ] getEncr yptedData(); public java.security.spec.PKCS8EncodedKeySpec getKeySpec(Cipher c) throws java.security.spec.InvalidKeySpecException; }

ExemptionMechanism

Java 1.4

javax.cr ypto Some countries place legal restrictions on the use of cryptographic algorithms. In some cases, a program may be exempt from these restrictions if it implements an “exemption mechanism” such as key recovery, key escrow, or key weakening. This class defines a general API to such mechanism. This class is rarely used and is not supported in the default implementation provided by Sun. Using this class successfully is quite complex and is beyond the scope of this reference. For details, see the discussion “How to Make Applicaions ‘Exempt’ from Cryptographic Restrictions” in the JCE Reference Guide, which is part of the standard bundle of documentation shipped by Sun with the JDK. public class ExemptionMechanism { // Protected Constructors protected ExemptionMechanism(ExemptionMechanismSpi exmechSpi, java.security.Provider provider, String mechanism); // Public Class Methods public static final ExemptionMechanism getInstance(String mechanism) throws java.security.NoSuchAlgorithmException; public static final ExemptionMechanism getInstance(String mechanism, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException; public static final ExemptionMechanism getInstance(String mechanism, java.security.Provider provider) throws java.security.NoSuchAlgorithmException; // Public Instance Methods public final byte[ ] genExemptionBlob() throws IllegalStateException, ExemptionMechanismException; public final int genExemptionBlob(byte[ ] output) throws IllegalStateException, ShortBufferException, ExemptionMechanismException; public final int genExemptionBlob(byte[ ] output, int outputOffset) throws IllegalStateException, ShortBufferException, ExemptionMechanismException; public final String getName(); public final int getOutputSize(int inputLen) throws IllegalStateException; public final java.security.Provider getProvider(); public final void init(java.security.Key key) throws java.security.InvalidKeyException, ExemptionMechanismException; public final void init(java.security.Key key, java.security.spec.AlgorithmParameterSpec params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException, ExemptionMechanismException; public final void init(java.security.Key key, java.security.AlgorithmParameters params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException, ExemptionMechanismException; public final boolean isCr yptoAllowed(java.security.Key key) throws ExemptionMechanismException; // Protected Methods Overriding Object protected void finalize(); } Returned By: Cipher.getExemptionMechanism(), ExemptionMechanism.getInstance()

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

745

ExemptionMechanismException

ExemptionMechanismException

Java 1.4 serializable checked

javax.cr ypto

This exception signals a problem in one of the ExemptionMechanism methods. Object

Throwable

Exception

GeneralSecurityException

ExemptionMechanismException

Serializable

public class ExemptionMechanismException extends java.security.GeneralSecurityException { // Public Constructors public ExemptionMechanismException(); public ExemptionMechanismException(String msg); } Thrown By: ExemptionMechanism.{genExemptionBlob(), init(), isCryptoAllowed()}, ExemptionMechanismSpi.{engineGenExemptionBlob(), engineInit()}

ExemptionMechanismSpi

Java 1.4

javax.cr ypto This abstract class defines the Service Provider Interface for ExemptionMechanism. Security providers may implement this interface, but applications never need to use it. Note that the default “SunJCE” provider does not provide an implementation. public abstract class ExemptionMechanismSpi { // Public Constructors public ExemptionMechanismSpi(); // Protected Instance Methods protected abstract byte[ ] engineGenExemptionBlob() throws ExemptionMechanismException; protected abstract int engineGenExemptionBlob(byte[ ] output, int outputOffset) throws ShortBufferException, ExemptionMechanismException; protected abstract int engineGetOutputSize(int inputLen); protected abstract void engineInit(java.security.Key key) throws java.security.InvalidKeyException, ExemptionMechanismException; protected abstract void engineInit(java.security.Key key, java.security.AlgorithmParameters params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException, ExemptionMechanismException; protected abstract void engineInit(java.security.Key key, java.security.spec.AlgorithmParameterSpec params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException, ExemptionMechanismException; } Passed To: ExemptionMechanism.ExemptionMechanism()

IllegalBlockSizeException

Java 1.4 serializable checked

javax.cr ypto

This exception signals that the length of data provided to a block cipher (as implemented, for example, by Cipher and SealedObject) does not match the block size for the cipher. Object

Throwable

Exception

GeneralSecurityException

IllegalBlockSizeException

Serializable

public class IllegalBlockSizeException extends java.security.GeneralSecurityException { // Public Constructors

746

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

KeyAgreement

public IllegalBlockSizeException(); public IllegalBlockSizeException(String msg); } Thrown By: Cipher.{doFinal(), wrap()}, CipherSpi.{engineDoFinal(), engineWrap()}, SealedObject.{getObject(), SealedObject()}

KeyAgreement

Java 1.4

javax.cr ypto This class provides an API to a key-agreement protocol that allows two or more parties to agree on a secret key without exchanging any secrets and in such a way that an eavesdropper listening in on the communication between those parties cannot determine the secret key. The KeyAgreement class is algorithm-independent and providerbased, so you must obtain a KeyAgreement object by calling one of the static getInstance() factory methods and specifying the name of the desired key agreement algorithm and, optionally, the name of the desired provider of that algorithm. The “SunJCE” provider implements a single key-agreement algorithm named “DiffieHellman”. To use a KeyAgreement object, each party first calls the init() method and supplies a Key object of its own. Then, each party obtains a Key object from one of the other parties to the agreement and calls doPhase(). Each party obtains an intermediate Key object as the return value of doPhase(), and these keys are again exchanged and passed to doPhase(). This process typically repeats n–1 times, where n is the number of parties, but the actual number of repetitions is algorithm-dependent. When doPhase() is called the last time, the second argument must be true to indicate that it is the last phase of the agreement. After all calls to doPhase() have been made, each party calls generateSecret() to obtain an array of bytes or a SecretKey object for a named algorithm type. All parties obtain the same bytes or SecretKey from this method. The KeyAgreement class is not responsible for the transfer of Key objects between parties or for mutual authentication among the parties. These tasks must be accomplished through some external mechanism. The most common type of key agreement is “DiffieHellman” key agreement between two parties. It proceeds as follows. First, both parties obtain a java.security.KeyPairGenerator for the “DiffieHellman” algorithm and use it to generate a java.security.KeyPair of DiffieHellman public and private keys. Each party passes its private key to the init() method of its KeyAgreement object. (The init() method can be passed a java.security.spec.AlgorithmParameterSpec object, but the Diffie-Hellman protocol does not require any additional parameters.) Next, the two parties exchange public keys, typically through some kind of networking mechanism (the KeyAgreement class is not responsible for the actual exchange of keys). Each party passes the public key of the other party to the doPhase() method of its KeyAgreement object. There are only two parties to this agreement, so only one phase is required, and the second argument to doPhase() is true. At this point, both parties call generateSecret() to obtain the shared secret key. A three-party Diffie-Hellman key agreement requires two phases and is slightly more complicated. Let’s call the three parties Alice, Bob, and Carol. Each generates a key pair and uses its private key to initialize its KeyAgreement object, as before. Then Alice passes her public key to Bob, Bob passes his to Carol, and Carol passes hers to Alice. Each party passes this public key to doPhase(). Since this is not the final doPhase(), the second argument is false, and doPhase() returns an intermediate Key object. The three parties exchange these intermediate keys again in the same way: Alice to Bob, Bob to Carol, and Carol to Alice. Now each party passes the intermediate key it has received to doPhase() a second time, passing true to indicate that this is the final phase. Finally, all three can call generateSecret() to obtain a shared key to encrypt future communication.

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

747

KeyAgreement

public class KeyAgreement { // Protected Constructors protected KeyAgreement(KeyAgreementSpi keyAgreeSpi, java.security.Provider provider, String algorithm); // Public Class Methods public static final KeyAgreement getInstance(String algorithm) throws java.security.NoSuchAlgorithmException; public static final KeyAgreement getInstance(String algorithm, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException; public static final KeyAgreement getInstance(String algorithm, java.security.Provider provider) throws java.security.NoSuchAlgorithmException; // Public Instance Methods public final java.security.Key doPhase(java.security.Key key, boolean lastPhase) throws java.security.InvalidKeyException, IllegalStateException; public final byte[ ] generateSecret() throws IllegalStateException; public final SecretKey generateSecret(String algorithm) throws IllegalStateException, java.security.NoSuchAlgorithmException, java.security.InvalidKeyException; public final int generateSecret(byte[ ] sharedSecret, int offset) throws IllegalStateException, ShortBufferException; public final String getAlgorithm(); public final java.security.Provider getProvider(); public final void init(java.security.Key key) throws java.security.InvalidKeyException; public final void init(java.security.Key key, java.security.SecureRandom random) throws java.security.InvalidKeyException; public final void init(java.security.Key key, java.security.spec.AlgorithmParameterSpec params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; public final void init(java.security.Key key, java.security.spec.AlgorithmParameterSpec params, java.security.SecureRandom random) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; } Returned By: KeyAgreement.getInstance()

KeyAgreementSpi

Java 1.4

javax.cr ypto This abstract class defines the service-provider interface for KeyAgreement. A cryptographic provider must implement a concrete subclass of this class for each encryption algorithm it supports. Applications never need to use or subclass this class. public abstract class KeyAgreementSpi { // Public Constructors public KeyAgreementSpi(); // Protected Instance Methods protected abstract java.security.Key engineDoPhase(java.security.Key key, boolean lastPhase) throws java.security.InvalidKeyException, IllegalStateException; protected abstract byte[ ] engineGenerateSecret() throws IllegalStateException; protected abstract SecretKey engineGenerateSecret(String algorithm) throws IllegalStateException, java.security.NoSuchAlgorithmException, java.security.InvalidKeyException; protected abstract int engineGenerateSecret(byte[ ] sharedSecret, int offset) throws IllegalStateException, ShortBufferException; protected abstract void engineInit(java.security.Key key, java.security.SecureRandom random) throws java.security.InvalidKeyException; protected abstract void engineInit(java.security.Key key, java.security.spec.AlgorithmParameterSpec params, java.security.SecureRandom random) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; } Passed To: KeyAgreement.KeyAgreement()

748

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

KeyGeneratorSpi

KeyGenerator

Java 1.4

javax.cr ypto This class provides an API for generating secret keys for symmetric cryptography. It is similar to java.security.KeyPairGenerator, which generates public/private key pairs for asymmetric or public-key cryptography. KeyGenerator is algorithm-independent and providerbased, so you must obtain a KeyGenerator instance by calling one of the static getInstance() factory methods and specifying the name of the cryptographic algorithm for which a key is desired and, optionally, the name of the security provider whose key-generation implementation is to be used. The “SunJCE” provider includes KeyGenerator implementations for the “DES”, “DESede”, and “Blowfish” encryption algorithms, and also for the “HmacMD5” and “HmacSHA1” message authentication (MAC) algorithms. Once you have obtained a KeyGenerator, you initialize it with the init() method. You can provide a java.security.spec.AlgorithmParameterSpec object to provide algorithm-specific initialization parameters or simply specify the desired size (in bits) of the key to be generated. In either case, you can also specify a source of randomness in the form of a SecureRandom object. If you do not specify a SecureRandom, the KeyGenerator instantiates one of its own. None of the algorithms supported by the “SunJCE” provider require algorithm-specific parameters. After calling getInstance() to obtain a KeyGenerator and init() to initialize it, simply call generateKey() to create a new SecretKey. Remember that the SecretKey must be kept secret. Take precautions when storing or transmitting the key, so that it does not fall into the wrong hands. You may want to use a java.security.KeyStore object to store the key in a password-protected form. public class KeyGenerator { // Protected Constructors protected KeyGenerator(KeyGeneratorSpi keyGenSpi, java.security.Provider provider, String algorithm); // Public Class Methods public static final KeyGenerator getInstance(String algorithm) throws java.security.NoSuchAlgorithmException; public static final KeyGenerator getInstance(String algorithm, java.security.Provider provider) throws java.security.NoSuchAlgorithmException; public static final KeyGenerator getInstance(String algorithm, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException; // Public Instance Methods public final SecretKey generateKey(); public final String getAlgorithm(); public final java.security.Provider getProvider(); public final void init(int keysize); public final void init(java.security.spec.AlgorithmParameterSpec params) throws java.security.InvalidAlgorithmParameterException; public final void init(java.security.SecureRandom random); public final void init(int keysize, java.security.SecureRandom random); public final void init(java.security.spec.AlgorithmParameterSpec params, java.security.SecureRandom random) throws java.security.InvalidAlgorithmParameterException; } Returned By: KeyGenerator.getInstance()

KeyGeneratorSpi

Java 1.4

javax.cr ypto This abstract class defines the service-provider interface for KeyGenerator. A cryptographic provider must implement a concrete subclass of this class for each key-generation algorithm it supports. Applications never need to use or subclass this class.

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

749

KeyGeneratorSpi

public abstract class KeyGeneratorSpi { // Public Constructors public KeyGeneratorSpi(); // Protected Instance Methods protected abstract SecretKey engineGenerateKey(); protected abstract void engineInit(java.security.SecureRandom random); protected abstract void engineInit(int keysize, java.security.SecureRandom random); protected abstract void engineInit(java.security.spec.AlgorithmParameterSpec params, java.security.SecureRandom random) throws java.security.InvalidAlgorithmParameterException; } Passed To: KeyGenerator.KeyGenerator()

Mac

Java 1.4 cloneable

javax.cr ypto

This class defines an API for computing a message authentication code (MAC) that can check the integrity of information transmitted between two parties that share a secret key. A MAC is similar to a digital signature, except that it is generated with a secret key rather than with a public/private key pair. The Mac class is algorithm-independent and provider-based. Obtain a Mac object by calling one of the static getInstance() factory methods and specifying the name of the desired MAC algorithm and, optionally, the name of the provider of the desired implementation. The “SunJCE” provider implements two algorithms: “HmacMD5” and “HmacSHA1”. These are MAC algorithms based on the MD5 and SHA-1 cryptographic hash functions. After obtaining a Mac object, initialize it by calling the init() method and specifying a SecretKey and, optionally, a java.security.spec.AlgorithmParameterSpec object. The “HmacMD5” and “HmacSHA1” algorithms can use any kind of SecretKey; they are not restricted to a particular cryptographic algorithm. And neither algorithm requires an AlgorithmParameterSpec object. After obtaining and initializing a Mac object, specify the data for which the MAC is to be computed. If the data is contained in a single byte array, simply pass it to doFinal(). If the data is streaming or is stored in various locations, you can supply the data in multiple calls to update(). End the series of update() calls with a single call to doFinal(). Note that some versions of doFinal() return the MAC data as the function return value. Another version stores the MAC data in a byte array you supply. If you use this version of doFinal(), be sure to call getMacLength() to instantiate an array of the correct length. A call to doFinal() resets the internal state of a Mac object. If you want to compute a MAC for part of your data and then proceed to compute the MAC for the full data, you should clone() the Mac object before calling doFinal(). Note, however, that Mac implementations are not required to implement Cloneable. Object

Mac

Cloneable

public class Mac implements Cloneable { // Protected Constructors protected Mac(MacSpi macSpi, java.security.Provider provider, String algorithm); // Public Class Methods public static final Mac getInstance(String algorithm) throws java.security.NoSuchAlgorithmException; public static final Mac getInstance(String algorithm, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException; public static final Mac getInstance(String algorithm, java.security.Provider provider) throws java.security.NoSuchAlgorithmException;

750

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

NoSuchPaddingException

// Public Instance Methods public final byte[ ] doFinal() throws IllegalStateException; public final byte[ ] doFinal(byte[ ] input) throws IllegalStateException; public final void doFinal(byte[ ] output, int outOffset) throws ShortBufferException, IllegalStateException; public final String getAlgorithm(); public final int getMacLength(); public final java.security.Provider getProvider(); public final void init(java.security.Key key) throws java.security.InvalidKeyException; public final void init(java.security.Key key, java.security.spec.AlgorithmParameterSpec params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; public final void reset(); public final void update(byte[ ] input) throws IllegalStateException; public final void update(byte input) throws IllegalStateException; public final void update(byte[ ] input, int offset, int len) throws IllegalStateException; // Public Methods Overriding Object public final Object clone() throws CloneNotSupportedException; } Returned By: Mac.getInstance()

MacSpi

Java 1.4

javax.cr ypto This abstract class defines the service-provider interface for Mac. A cryptographic provider must implement a concrete subclass of this class for each MAC algorithm it supports. Applications never need to use or subclass this class. public abstract class MacSpi { // Public Constructors public MacSpi(); // Public Methods Overriding Object public Object clone() throws CloneNotSupportedException; // Protected Instance Methods protected abstract byte[ ] engineDoFinal(); protected abstract int engineGetMacLength(); protected abstract void engineInit(java.security.Key key, java.security.spec.AlgorithmParameterSpec params) throws java.security.InvalidKeyException, java.security.InvalidAlgorithmParameterException; protected abstract void engineReset(); protected abstract void engineUpdate(byte input); protected abstract void engineUpdate(byte[ ] input, int offset, int len); } Passed To: Mac.Mac()

NoSuchPaddingException

Java 1.4 serializable checked

javax.cr ypto

This exception signals that no implementation of the requested padding scheme can be found. Object

Throwable

Exception

GeneralSecurityException

NoSuchPaddingException

Serializable

public class NoSuchPaddingException extends java.security.GeneralSecurityException { // Public Constructors public NoSuchPaddingException();

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

751

NoSuchPaddingException

public NoSuchPaddingException(String msg); } Thrown By: Cipher.getInstance(), CipherSpi.engineSetPadding()

NullCipher

Java 1.4

javax.cr ypto This trivial subclass of Cipher implements an identity cipher that does not transform plain text in any way. Unlike Cipher objects returned by Cipher.getInstance(), a NullCipher must be created with the NullCipher() constructor. Object

Cipher

NullCipher

public class NullCipher extends Cipher { // Public Constructors public NullCipher(); }

SealedObject

Java 1.4 serializable

javax.cr ypto

This class is a wrapper around a serializable object. It serializes the object and encrypts the resulting data stream, thereby protecting the confidentiality of the object. Create a SealedObject by specifying the object to be sealed and a Cipher object to perform the encryption. Retrieve the sealed object by calling getObject() and specifying the Cipher or java.security.Key to use for decryption. The SealedObject keeps track of the encryption algorithm and parameters so that a Key object alone can decrypt the object. Object

SealedObject

Serializable

public class SealedObject implements Serializable { // Public Constructors public SealedObject(Serializable object, Cipher c) throws java.io.IOException, IllegalBlockSizeException; // Protected Constructors protected SealedObject(SealedObject so); // Public Instance Methods public final String getAlgorithm(); public final Object getObject(java.security.Key key) throws java.io.IOException, ClassNotFoundException, java.security.NoSuchAlgorithmException, java.security.InvalidKeyException; public final Object getObject(Cipher c) throws java.io.IOException, ClassNotFoundException, IllegalBlockSizeException, BadPaddingException; public final Object getObject(java.security.Key key, String provider) throws java.io.IOException, ClassNotFoundException, java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException, java.security.InvalidKeyException; // Protected Instance Fields protected byte[ ] encodedParams; } Passed To: SealedObject.SealedObject()

SecretKey javax.cr ypto

Java 1.4 serializable

This interface represents a secret key used for symmetric cryptographic algorithms that depend on both the sender and receiver knowing the same secret. SecretKey extends the java.security.Key interface, but does not add any new methods. The interface exists in

752

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

SecretKeyFactory order to keep secret keys distinct from the public and private keys used in public-key, or asymmetric, cryptography. See also java.security.PublicKey and java.security.PrivateKey. A secret key is nothing more than arrays of bytes and does not require a specialized encoding format. Therefore, an implementation of this interface should return the format name “RAW” from getFormat() and should return the bytes of the key from getEncoded(). (These two methods are defined by the java.security.Key interface that SecretKey extends.) Serializable

Key

SecretKey

public interface SecretKey extends java.security.Key { } Implementations: javax.cr ypto.interfaces.PBEKey, javax.cr ypto.spec.SecretKeySpec, javax.security.auth.kerberos.KerberosKey Passed To: SecretKeyFactor y.{getKeySpec(), translateKey()}, SecretKeyFactor ySpi.{engineGetKeySpec(), engineTranslateKey()} Returned By: KeyAgreement.generateSecret(), KeyAgreementSpi.engineGenerateSecret(), KeyGenerator.generateKey(), KeyGeneratorSpi.engineGenerateKey(), SecretKeyFactor y.{generateSecret(), translateKey()}, SecretKeyFactor ySpi.{engineGenerateSecret(), engineTranslateKey()}, javax.security.auth.kerberos.KerberosTicket.getSessionKey()

SecretKeyFactor y

Java 1.4

javax.cr ypto This class defines an API for translating a secret key between its opaque SecretKey representation and its transparent javax.cr ypto.SecretKeySpec representation. It is much like java.security.KeyFactor y, except that it works with secret (or symmetric) keys rather than with public and private (asymmetric) keys. SecretKeyFactor y is algorithm-independent and provider-based, so you must obtain a SecretKeyFactor y object by calling one of the static getInstance() factory methods and specifying the name of the desired secret-key algorithm and, optionally, the name of the provider whose implementation is desired. The “SunJCE” provider provides SecretKeyFactor y implementations for the “DES”, “DESede”, and “PBEWithMD5AndDES” algorithms. Once you have obtained a SecretKeyFactor y, use generateSecret() to create a SecretKey from a java.security.spec.KeySpec (or its subclass, javax.cr ypto.spec.SecretKeySpec) or call getKeySpec() to obtain a KeySpec for a Key object. Because there can be more than one suitable type of KeySpec, getKeySpec() requires a Class object to specify the type of the KeySpec to be created. See also DESKeySpec, DESedeKeySpec, and PBEKeySpec in the javax.cr ypto.spec package. public class SecretKeyFactor y { // Protected Constructors protected SecretKeyFactor y(SecretKeyFactorySpi keyFacSpi, java.security.Provider provider, String algorithm); // Public Class Methods public static final SecretKeyFactory getInstance(String algorithm) throws java.security.NoSuchAlgorithmException; public static final SecretKeyFactory getInstance(String algorithm, java.security.Provider provider) throws java.security.NoSuchAlgorithmException; public static final SecretKeyFactory getInstance(String algorithm, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException; // Public Instance Methods public final SecretKey generateSecret(java.security.spec.KeySpec keySpec) throws java.security.spec.InvalidKeySpecException;

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

753

SecretKeyFactory

public final String getAlgorithm(); public final java.security.spec.KeySpec getKeySpec(SecretKey key, Class keySpec) throws java.security.spec.InvalidKeySpecException; public final java.security.Provider getProvider(); public final SecretKey translateKey(SecretKey key) throws java.security.InvalidKeyException; } Returned By: SecretKeyFactor y.getInstance()

SecretKeyFactor ySpi

Java 1.4

javax.cr ypto This abstract class defines the service-provider interface for SecretKeyFactor y. A cryptographic provider must implement a concrete subclass of this class for each type of secret key it supports. Applications never need to use or subclass this class. public abstract class SecretKeyFactor ySpi { // Public Constructors public SecretKeyFactor ySpi(); // Protected Instance Methods protected abstract SecretKey engineGenerateSecret(java.security.spec.KeySpec keySpec) throws java.security.spec.InvalidKeySpecException; protected abstract java.security.spec.KeySpec engineGetKeySpec(SecretKey key, Class keySpec) throws java.security.spec.InvalidKeySpecException; protected abstract SecretKey engineTranslateKey(SecretKey key) throws java.security.InvalidKeyException; } Passed To: SecretKeyFactor y.SecretKeyFactor y()

ShortBufferException

Java 1.4 serializable checked

javax.cr ypto

This signals that an output buffer is too short to hold the results of an operation. Object

Throwable

Exception

GeneralSecurityException

ShortBufferException

Serializable

public class ShortBufferException extends java.security.GeneralSecurityException { // Public Constructors public ShortBufferException(); public ShortBufferException(String msg); } Thrown By: Cipher.{doFinal(), update()}, CipherSpi.{engineDoFinal(), engineUpdate()}, ExemptionMechanism.genExemptionBlob(), ExemptionMechanismSpi.engineGenExemptionBlob(), KeyAgreement.generateSecret(), KeyAgreementSpi.engineGenerateSecret(), Mac.doFinal()

Package javax.cr ypto.interfaces

Java 1.4

The interfaces in the javax.cr ypto.interfaces package define the public methods that must be supported by various types of encryption keys. The “DH” interfaces represent DiffieHellman public/private key pairs used in the Diffie-Hellman key-agreement protocol. The “PBE” interface is for Password-Based Encryption. These interfaces are typically of interest only to programmers who are implementing a cryptographic provider or who

754

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

DHPublicKey want to implement cryptographic algorithms themselves. Use of this package requires basic familiarity with the encryption algorithms and the mathematics that underlie them. Note that the javax.cr ypto.spec package contains classes that provide algorithm-specific details about encryption keys. Interfaces: public interface DHKey; public interface DHPrivateKey extends DHKey, java.security.PrivateKey; public interface DHPublicKey extends DHKey, java.security.PublicKey; public interface PBEKey extends javax.cr ypto.SecretKey;

DHKey

Java 1.4

javax.cr ypto.interfaces This interface represents a Diffie-Hellman key. The javax.cr ypto.spec.DHParameterSpec returned by getParams() specifies the parameters that generate the key; they define a key family. See the subinterfaces DHPublicKey and DHPrivateKey for the actual key values. public interface DHKey { // Public Instance Methods public abstract javax.crypto.spec.DHParameterSpec getParams(); } Implementations: DHPrivateKey, DHPublicKey

DHPrivateKey

Java 1.4 serializable

javax.cr ypto.interfaces

This interface represents a Diffie-Hellman private key. Note that it extends two interfaces: DHKey and java.security.PrivateKey. getX() returns the private-key value. If you are working with a PrivateKey you know is a Diffie-Hellman key, you can cast your PrivateKey to a DHPrivateKey. DHPrivateKey DHKey

Serializable

Key

PrivateKey

public interface DHPrivateKey extends DHKey, java.security.PrivateKey { // Public Instance Methods public abstract java.math.BigInteger getX(); }

DHPublicKey

Java 1.4 serializable

javax.cr ypto.interfaces

This interface represents a Diffie-Hellman public key. Note that it extends two interfaces: DHKey and java.security.PublicKey. getY() returns the public-key value. If you are working with a PublicKey you know is a Diffie-Hellman key, you can cast your PublicKey to a DHPublicKey. DHPublicKey DHKey

Serializable

Key

PublicKey

public interface DHPublicKey extends DHKey, java.security.PublicKey { // Public Instance Methods

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

755

DHPublicKey

public abstract java.math.BigInteger getY(); }

PBEKey

Java 1.4 serializable

javax.cr ypto.interfaces

This interface represents a key for password-based encryption. If you are working with a SecretKey that you know is a password-based key, you can cast it to a PBEKey. Serializable

Key

SecretKey

PBEKey

public interface PBEKey extends javax.crypto.SecretKey { // Public Instance Methods public abstract int getIterationCount(); public abstract char[ ] getPassword(); public abstract byte[ ] getSalt(); }

Package javax.cr ypto.spec

Java 1.4

The javax.cr ypto.spec package contains classes that define transparent java.security.spec.KeySpec and java.security.spec.AlgorithmParameterSpec representations of secret keys, Diffie-Hellman public and private keys, and parameters used by various cryptographic algorithms. The classes in this package are used in conjunction with java.security.KeyFactor y, javax.cr ypto.SecretKeyFactor y and java.security.AlgorithmParameters for converting opaque Key, and AlgorithmParameters objects to and from transparent representations. In order to make good use of this package, you must be familiar with the specifications of the various cryptographic algorithms it supports and the basic mathematics that underlie those algorithms. Classes: public class DESedeKeySpec implements java.security.spec.KeySpec; public class DESKeySpec implements java.security.spec.KeySpec; public class DHGenParameterSpec implements java.security.spec.AlgorithmParameterSpec; public class DHParameterSpec implements java.security.spec.AlgorithmParameterSpec; public class DHPrivateKeySpec implements java.security.spec.KeySpec; public class DHPublicKeySpec implements java.security.spec.KeySpec; public class IvParameterSpec implements java.security.spec.AlgorithmParameterSpec; public class PBEKeySpec implements java.security.spec.KeySpec; public class PBEParameterSpec implements java.security.spec.AlgorithmParameterSpec; public class RC2ParameterSpec implements java.security.spec.AlgorithmParameterSpec; public class RC5ParameterSpec implements java.security.spec.AlgorithmParameterSpec; public class SecretKeySpec implements java.security.spec.KeySpec, javax.cr ypto.SecretKey;

DESedeKeySpec

Java 1.4

javax.cr ypto.spec This class is a transparent representation of a DESede (triple-DES) key. The key is 24 bytes long. Object

756

7 March 2002 11:38

DESedeKeySpec

KeySpec

Chapter 18 – javax.crypto and Subpackages

DHGenParameterSpec

public class DESedeKeySpec implements java.security.spec.KeySpec { // Public Constructors public DESedeKeySpec(byte[ ] key) throws java.security.InvalidKeyException; public DESedeKeySpec(byte[ ] key, int offset) throws java.security.InvalidKeyException; // Public Constants public static final int DES_EDE_KEY_LEN; // Public Class Methods public static boolean isParityAdjusted(byte[ ] key, int offset) throws java.security.InvalidKeyException; // Public Instance Methods public byte[ ] getKey(); }

DESKeySpec

=24

Java 1.4

javax.cr ypto.spec This class is a transparent representation of a DES key. The key is 8 bytes long. Object

DESKeySpec

KeySpec

public class DESKeySpec implements java.security.spec.KeySpec { // Public Constructors public DESKeySpec(byte[ ] key) throws java.security.InvalidKeyException; public DESKeySpec(byte[ ] key, int offset) throws java.security.InvalidKeyException; // Public Constants public static final int DES_KEY_LEN; // Public Class Methods public static boolean isParityAdjusted(byte[ ] key, int offset) throws java.security.InvalidKeyException; public static boolean isWeak(byte[ ] key, int offset) throws java.security.InvalidKeyException; // Public Instance Methods public byte[ ] getKey(); }

DHGenParameterSpec

=8

Java 1.4

javax.cr ypto.spec This class is a transparent representation of the values needed to generate a set of Diffie-Hellman parameters (see DHParameterSpec). An instance of this class can be passed to the init() method of a java.security.AlgorithmParameterGenerator that computes Diffie-Hellman parameters. Object

DHGenParameterSpec

AlgorithmParameterSpec

public class DHGenParameterSpec implements java.security.spec.AlgorithmParameterSpec { // Public Constructors public DHGenParameterSpec(int primeSize, int exponentSize); // Public Instance Methods public int getExponentSize(); public int getPrimeSize(); }

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

757

DHParameterSpec

DHParameterSpec

Java 1.4

javax.cr ypto.spec This class is a transparent representation of the set of parameters required by the DiffieHellman key-agreement algorithm. All parties to the key agreement must share these parameters and use them to generate a Diffie-Hellman public/private key pair. Object

DHParameterSpec

AlgorithmParameterSpec

public class DHParameterSpec implements java.security.spec.AlgorithmParameterSpec { // Public Constructors public DHParameterSpec(java.math.BigInteger p, java.math.BigInteger g); public DHParameterSpec(java.math.BigInteger p, java.math.BigInteger g, int l); // Public Instance Methods public java.math.BigInteger getG(); public int getL(); public java.math.BigInteger getP(); } Returned By: javax.cr ypto.interfaces.DHKey.getParams()

DHPrivateKeySpec

Java 1.4

javax.cr ypto.spec This java.security.spec.KeySpec is a transparent representation of a Diffie-Hellman private key. Object

DHPrivateKeySpec

KeySpec

public class DHPrivateKeySpec implements java.security.spec.KeySpec { // Public Constructors public DHPrivateKeySpec(java.math.BigInteger x, java.math.BigInteger p, java.math.BigInteger g); // Public Instance Methods public java.math.BigInteger getG(); public java.math.BigInteger getP(); public java.math.BigInteger getX(); }

DHPublicKeySpec

Java 1.4

javax.cr ypto.spec This java.security.spec.KeySpec is a transparent representation of a Diffie-Hellman public key. Object

DHPublicKeySpec

KeySpec

public class DHPublicKeySpec implements java.security.spec.KeySpec { // Public Constructors public DHPublicKeySpec(java.math.BigInteger y, java.math.BigInteger p, java.math.BigInteger g); // Public Instance Methods public java.math.BigInteger getG(); public java.math.BigInteger getP(); public java.math.BigInteger getY(); }

758

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

PBEParameterSpec

IvParameterSpec

Java 1.4

javax.cr ypto.spec This java.security.spec.AlgorithmParameterSpec is a transparent representation of an initialization vector, or IV. An IV is required for block ciphers used in feedback mode, such as DES in CBC mode. Object

IvParameterSpec

AlgorithmParameterSpec

public class IvParameterSpec implements java.security.spec.AlgorithmParameterSpec { // Public Constructors public IvParameterSpec(byte[ ] iv); public IvParameterSpec(byte[ ] iv, int offset, int len); // Public Instance Methods public byte[ ] getIV(); }

PBEKeySpec

Java 1.4

javax.cr ypto.spec This class is a transparent representation of a password used in password-based encryption (PBE). The password is stored as a char array rather than as a String so that the characters of the password can be overwritten when they are no longer needed (for increased security). Object

PBEKeySpec

KeySpec

public class PBEKeySpec implements java.security.spec.KeySpec { // Public Constructors public PBEKeySpec(char[ ] password); public PBEKeySpec(char[ ] password, byte[ ] salt, int iterationCount); public PBEKeySpec(char[ ] password, byte[ ] salt, int iterationCount, int keyLength); // Public Instance Methods public final void clearPassword(); public final int getIterationCount(); public final int getKeyLength(); public final char[ ] getPassword(); public final byte[ ] getSalt(); }

PBEParameterSpec

Java 1.4

javax.cr ypto.spec This class is a transparent representation of the parameters used with the passwordbased encryption algorithm defined by PKCS#5. Object

PBEParameterSpec

AlgorithmParameterSpec

public class PBEParameterSpec implements java.security.spec.AlgorithmParameterSpec { // Public Constructors public PBEParameterSpec(byte[ ] salt, int iterationCount); // Public Instance Methods public int getIterationCount(); public byte[ ] getSalt(); }

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

759

RC2ParameterSpec

RC2ParameterSpec

Java 1.4

javax.cr ypto.spec This class is a transparent representation of the parameters used by the RC2 encryption algorithm. An object of this class initializes a Cipher object that implements RC2. Note that the “SunJCE” provider supplied by Sun does not implement RC2. Object

RC2ParameterSpec

AlgorithmParameterSpec

public class RC2ParameterSpec implements java.security.spec.AlgorithmParameterSpec { // Public Constructors public RC2ParameterSpec(int effectiveKeyBits); public RC2ParameterSpec(int effectiveKeyBits, byte[ ] iv); public RC2ParameterSpec(int effectiveKeyBits, byte[ ] iv, int offset); // Public Instance Methods public int getEffectiveKeyBits(); public byte[ ] getIV(); // Public Methods Overriding Object public boolean equals(Object obj); public int hashCode(); }

RC5ParameterSpec

Java 1.4

javax.cr ypto.spec This class is a transparent representation of the parameters used by the RC5 encryption algorithm. An object of this class initializes a Cipher object that implements RC5. Note that the “SunJCE” provider supplied by Sun does not implement RC5. Object

RC5ParameterSpec

AlgorithmParameterSpec

public class RC5ParameterSpec implements java.security.spec.AlgorithmParameterSpec { // Public Constructors public RC5ParameterSpec(int version, int rounds, int wordSize); public RC5ParameterSpec(int version, int rounds, int wordSize, byte[ ] iv); public RC5ParameterSpec(int version, int rounds, int wordSize, byte[ ] iv, int offset); // Public Instance Methods public byte[ ] getIV(); public int getRounds(); public int getVersion(); public int getWordSize(); // Public Methods Overriding Object public boolean equals(Object obj); public int hashCode(); }

SecretKeySpec javax.cr ypto.spec

Java 1.4 serializable

This class is a transparent and algorithm-independent representation of a secret key. This class is useful only for encryption algorithms (such as DES and DESede) whose secret keys can be represented as arbitrary byte arrays and do not require auxiliary

760

7 March 2002 11:38

Chapter 18 – javax.crypto and Subpackages

SecretKeySpec parameters. Note that SecretKeySpec implements the javax.cr ypto.SecretKey interface directly, so no algorithm-specific javax.cr ypto.SecretKeyFactor y object is required. Object KeySpec

SecretKeySpec Serializable

Key

SecretKey

public class SecretKeySpec implements java.security.spec.KeySpec, javax.crypto.SecretKey { // Public Constructors public SecretKeySpec(byte[ ] key, String algorithm); public SecretKeySpec(byte[ ] key, int offset, int len, String algorithm); // Methods Implementing Key public String getAlgorithm(); public byte[ ] getEncoded(); public String getFormat(); // Public Methods Overriding Object public boolean equals(Object obj); public int hashCode(); }

Chapter 18 – javax.crypto and Subpackages

7 March 2002 11:38

761

CHAPTER 19

javax.net and javax.net.ssl

This chapter documents the javax.net package and, more importantly, its subpackage javax.net.ssl. These packages were originally defined by the Java Secure Sockets Extension (JSSE) before they were integrated into Java 1.4, which is why they have a “javax” prefix. javax.net is a small package that simply defines abstract factory classes for creating network sockets and servers sockets. javax.net.ssl provides subclasses of these factory classes that have the specific purpose of creating sockets and server sockets that enable secure network communication through the SSL protocol and the closely related TLS protocol.

Package javax.net

Java 1.4

This small package defines factory classes for creating socket and server sockets. These factory classes can be used to create regular java.net.Socket and java.net.Ser verSocket objects. More importantly, however, these factory classes can be subclassed to serve as factories for other types of sockets such as the SSL-enabled sockets of the javax.net.ssl package. Classes: public abstract class Ser verSocketFactor y; public abstract class SocketFactor y;

Ser verSocketFactor y

Java 1.4

javax.net This abstract class defines a factory API for creating server socket objects. Use the static getDefault() method to obtain a default Ser verSocketFactor y object that is suitable for creating regular java.net.Ser verSocket sockets. Once you have a Ser verSocketFactor y object, call one of the createSer verSocket() methods to create a new socket and optionally bind it to a local port and specify the allowed backlog of queued connections. See javax.net.ssl.SSLSer verSocketFactor y for a socket factory that can create secure javax.net.ssl.SSLSer verSocket objects.

762

7 March 2002 11:38

Package javax.net.ssl

public abstract class Ser verSocketFactor y { // Protected Constructors protected Ser verSocketFactor y(); // Public Class Methods public static ServerSocketFactory getDefault(); // Public Instance Methods public java.net.ServerSocket createSer verSocket() throws java.io.IOException; public abstract java.net.ServerSocket createSer verSocket(int port) throws java.io.IOException; public abstract java.net.ServerSocket createSer verSocket(int port, int backlog) throws java.io.IOException; public abstract java.net.ServerSocket createSer verSocket(int port, int backlog, java.net.InetAddress ifAddress) throws java.io.IOException; } Subclasses: javax.net.ssl.SSLSer verSocketFactor y Returned By: Ser verSocketFactor y.getDefault(), javax.net.ssl.SSLSer verSocketFactor y.getDefault()

SocketFactor y

Java 1.4

javax.net This abstract class defines a factory API for creating socket objects. Use the static getDefault() method to obtain a default SocketFactor y object that is suitable for creating regular java.net.Socket sockets. (This default SocketFactor y is the one used by the Socket() constructor, which usually provides an easier way to create normal sockets.) Once you have a SocketFactor y object, call one of the createSocket() methods to create a new socket and optionally connect it to a remote host and optionally bind it to a local address and port. See javax.net.ssl.SSLSocketFactor y for a socket factory that can create secure javax.net.ssl.SSLSocket objects. public abstract class SocketFactor y { // Protected Constructors protected SocketFactor y(); // Public Class Methods public static SocketFactory getDefault(); // Public Instance Methods public java.net.Socket createSocket() throws java.io.IOException; public abstract java.net.Socket createSocket(String host, int port) throws java.io.IOException, java.net.UnknownHostException; public abstract java.net.Socket createSocket(java.net.InetAddress host, int port) throws java.io.IOException; public abstract java.net.Socket createSocket(java.net.InetAddress address, int port, java.net.InetAddress localAddress, int localPort) throws java.io.IOException; public abstract java.net.Socket createSocket(String host, int port, java.net.InetAddress localHost, int localPort) throws java.io.IOException, java.net.UnknownHostException; } Subclasses: javax.net.ssl.SSLSocketFactor y Returned By: SocketFactor y.getDefault(), javax.net.ssl.SSLSocketFactor y.getDefault()

Package javax.net.ssl

Java 1.4

This package defines an API for secure network sockets using the Secure Sockets Layer (SSL) protocol or the closely related Transport Layer Security (TLS) protocol. It defines the SSLSocket and SSLSer verSocket subclasses of the java.net socket and server socket classes. And it defines SSLSocketFactor y and SSLSer verSocketFactor y subclasses of the javax.net factory classes to create those SSL-enabled sockets and server sockets. Clients

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

763

Package javax.net.ssl that want to perform simple SSL-enabled networking can create an SSLSocket with code such as the following: SSLSocketFactory factory = SSLSocketFactory.getDefault(); SSLSocket securesock = (SSLSocket)factory.getSocket(hostname, 443);

// https port

Once an SSLSocket has been created, it can be used just like a normal java.net.Socket. Once a connection is established over an SSLSocket, you can use the getSession() method to obtain an SSLSession object that provides information about the connection. Note that despite the name of this package and of its key classes, it supports the TLS protocol in addition to the SSL. (The default provider in Sun’s implementation supports SSL 3.0 and TLS 1.0.) The TLS protocol is closely related to SSL, and we’ll simply use the term SSL here. The SSLSocket class allows you to do arbitrary networking with an SSL-enabled peer. The most common use of SSL today is with the https: protocol on the web. The addition of this package to the core Java platform enables support for https: URLs in the java.net.URL class, which allows you to securely transfer data over the web without having to directly use this package at all. When you call openConnection() on a https: URL, the URLConnection object that is returned can be cast to an HttpsURLConnection object, which defines some SSL-specific methods. See java.net.URL and java.net.URLConnection for more information about networking with URLs. Although the code shown above to create a SSLSocket is quite simple, this package is much more complex because it exposes a lot of SSL infrastructure so that applications with advanced networking needs can configure it as needed. Also, like all securityrelated packages, this one is provider-based and algorithm-independent, which adds a layer of complexity. If you want to explore this package beyond the two socket classes, the two factory classes, and the HttpsURLConnection class, start with SSLContext. This class is a factory for socket factories, and as such is the central class of the API. To customize the way SSL networking is done, you create an SSLContext optionally specifying the desired provider of the implementation. Next, you initialize the SSLContext by providing a custom KeyManager as a source of authentication information to be supplied to the remote host if required, a custom TrustManager as a verifier for the authentication information (if any) presented by the remote host, and a custom java.security.SecureRandom object as a source of randomness. Once the SSLContext is initialized in this way, you can use it to create SSLSocketFactor y and SSLSer verSocketFactor y objects that use the KeyManager and TrustManager objects you supplied. The contents of this package are known as the Java Secure Sockets Extension or JSSE. Prior to being incorporated into Java 1.4, JSSE was a standard extension and JSSE Version 1.0.2 is available as a separate download for use with Java 1.2 and Java 1.3. Note, however, that there are some API differences between JSSE Version 1.0.2 and the updated version that is now part of Java 1.4. Interfaces: public interface HostnameVerifier; public interface KeyManager ; public interface ManagerFactor yParameters; public interface SSLSession; public interface SSLSessionContext; public interface TrustManager ; public interface X509KeyManager extends KeyManager ; public interface X509TrustManager extends TrustManager ;

764

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

HandshakeCompletedEvent Events: public class HandshakeCompletedEvent extends java.util.EventObject; public class SSLSessionBindingEvent extends java.util.EventObject; Event Listeners: public interface HandshakeCompletedListener extends java.util.EventListener; public interface SSLSessionBindingListener extends java.util.EventListener ; Other Classes: public abstract class HttpsURLConnection extends java.net.HttpURLConnection; public class KeyManagerFactor y; public abstract class KeyManagerFactor ySpi; public class SSLContext; public abstract class SSLContextSpi; public final class SSLPermission extends java.security.BasicPermission; public abstract class SSLServerSocket extends java.net.Ser verSocket; public abstract class SSLServerSocketFactor y extends javax.net.Ser verSocketFactor y; public abstract class SSLSocket extends java.net.Socket; public abstract class SSLSocketFactor y extends javax.net.SocketFactor y; public class TrustManagerFactor y; public abstract class TrustManagerFactor ySpi; Exceptions: public class SSLException extends java.io.IOException; public class SSLHandshakeException extends SSLException; public class SSLKeyException extends SSLException; public class SSLPeerUnverifiedException extends SSLException; public class SSLProtocolException extends SSLException;

HandshakeCompletedEvent

Java 1.4 serializable event

javax.net.ssl

An instance of this class is passed to the handshakeCompleted() method of any registered HandshakeCompletedListener objects by an SSLSocket when that socket completes the handshake phase of establishing a connection. The various methods of a HandshakeCompletedEvent return information (such as the name of the cipher suite in use and the certificate chain of the remote host) that was determined during that handshake. Note that the getPeerCertificateChain() method returns an object from the javax.security.cert package, which is not documented in this book. The method and package exist only for backward compatibility with earlier versions of the JSSE API, and should be considered deprecated. Use getPeerCertificates(), which uses java.security.cert instead. Object

EventObject

HandshakeCompletedEvent

Serializable

public class HandshakeCompletedEvent extends java.util.EventObject { // Public Constructors public HandshakeCompletedEvent(SSLSocket sock, SSLSession s); // Property Accessor Methods (by property name) public String getCipherSuite(); public java.security.cert.Certificate[ ] getLocalCertificates();

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

765

HandshakeCompletedEvent

public javax.security.cert.X509Certificate[ ] getPeerCertificateChain() throws SSLPeerUnverifiedException; public java.security.cert.Certificate[ ] getPeerCertificates() throws SSLPeerUnverifiedException; public SSLSession getSession(); public SSLSocket getSocket(); } Passed To: HandshakeCompletedListener.handshakeCompleted()

HandshakeCompletedListener javax.net.ssl

Java 1.4 event listener

This interface is implemented by any class that wants to receive notifications (in the form of a call to handshakeCompleted() method) when an SSLSocket completes the SSL handshake. Register a HandshakeCompletedListener for an SSLSocket by passing it to the addHandshakeCompletedListener() method of the socket. When the socket completes the handshake phase of connection, it will call the handshakeCompleted() method of all registered listeners, passing in a HandshakeCompletedEvent object. EventListener

HandshakeCompletedListener

public interface HandshakeCompletedListener extends java.util.EventListener { // Public Instance Methods public abstract void handshakeCompleted(HandshakeCompletedEvent event); } Passed To: SSLSocket.{addHandshakeCompletedListener(), removeHandshakeCompletedListener()}

HostnameVerifier

Java 1.4

javax.net.ssl An object that implements this interface may be used with an HttpsURLConnection object to handle the case in which the hostname that appears in the URL does not match the hostname obtained during the SSL handshake with the server. This occurs, for example, when a web site uses the secure certificate of its parent web hosting company, for example. In this situation, the verify() method of the HostnameVerifier is called to determine whether the connection should proceed or not. verify() should return true to allow the connection to proceed, and should return false to cause the connection to fail. The hostname argument to verify() specifies the hostname that appeared in the URL. The session argument specifies the SSLSession object that was established during the handshake. Call getPeerHost() on this object to determine the hostname reported during server authentication. If no HostnameVerifier is registered with a HttpsURLConnection object, and no default verifier is registered with the HttpsURLConnection class, then hostname mismatches will always cause the connection to fail. In user-driven applications such as web browsers, a HostnameVerifier can be used to ask if the user wants to proceed or not. public interface HostnameVerifier { // Public Instance Methods public abstract boolean verify(String hostname, SSLSession session); } Passed To: javax.naming.ldap.StartTlsResponse.setHostnameVerifier(), HttpsURLConnection.{setDefaultHostnameVerifier(), setHostnameVerifier()} Returned By: HttpsURLConnection.{getDefaultHostnameVerifier(), getHostnameVerifier()} Type Of: HttpsURLConnection.hostnameVerifier

766

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

KeyManager

HttpsURLConnection

Java 1.4

javax.net.ssl This class is a java.net.URLConnection for a URL that uses the https: protocol. It extends java.net.HttpURLConnection and, in addition to inheriting the methods of its superclasses, it defines methods for specifying the SSLSocketFactor y and HostnameVerifier to use when establishing the connection. Static versions of these methods allow you to specify a default factory and verifier objects for use with all HttpsURLConnection objects. After the connection has been established, several other methods exist to obtain information (such as the cipher suite and the server certificates) about the connection itself. Obtain a HttpsURLConnection object by calling the openConnection() method of a URL that uses the https:// protocol specifier, and casting the returned value to this type. The HttpsURLConnection object is unconnected at this point, and you can call setHostnameVerifier() and setSSLSocketFactor y() to customize the way the connection is made. (If you do not specify a HostnameVerifier for the instance, or a default one for the class, then hostname mismatches will always cause the connection to fail. If you do not specify an SSLSocketFactor y for the instance or class, then a default one will be used.) To connect, call the inherited connect() method, and then call the inherited getContent() to retrieve the content of the URL as an object, or use the inherited getInputStream() to obtain a java.io.InputStream with which you can read the content of the URL. Object

URLConnection

HttpURLConnection

HttpsURLConnection

public abstract class HttpsURLConnection extends java.net.HttpURLConnection { // Protected Constructors protected HttpsURLConnection(java.net.URL url) throws java.io.IOException; // Public Class Methods public static HostnameVerifier getDefaultHostnameVerifier(); public static SSLSocketFactory getDefaultSSLSocketFactor y(); public static void setDefaultHostnameVerifier(HostnameVerifier v); public static void setDefaultSSLSocketFactor y(SSLSocketFactory sf); // Property Accessor Methods (by property name) public abstract String getCipherSuite(); public HostnameVerifier getHostnameVerifier(); public void setHostnameVerifier(HostnameVerifier v); public abstract java.security.cert.Certificate[ ] getLocalCertificates(); public abstract java.security.cert.Certificate[ ] getSer verCertificates() throws SSLPeerUnverifiedException; public SSLSocketFactory getSSLSocketFactor y(); public void setSSLSocketFactor y(SSLSocketFactory sf); // Protected Instance Fields protected HostnameVerifier hostnameVerifier; }

KeyManager

Java 1.4

javax.net.ssl This is a marker interface to identify key manager objects. A key manager is responsible for obtaining and managing authentication credentials (such as a certificate chain and an associated private key) that the local host can use to authenticate itself to the remote host. It is usually used on the server-side of an SSL connection, but can be used on the client side as well. Use a KeyManagerFactor y to obtain KeyManager objects. KeyManager objects returned by a KeyManagerFactor y can always be cast to a sub-interface specific to a particular type of authentication credentials. See X509KeyManager, for example.

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

767

KeyManager

public interface KeyManager { } Implementations: X509KeyManager Passed To: SSLContext.init(), SSLContextSpi.engineInit() Returned By: KeyManagerFactor y.getKeyManagers(), KeyManagerFactor ySpi.engineGetKeyManagers()

KeyManagerFactor y

Java 1.4

javax.net.ssl A KeyManagerFactor y is responsible for creating KeyManager objects for a specific key management algorithm. Obtain a KeyManagerFactor y object by calling one of the getInstance() methods and specifying the desired algorithm and, optionally, the desired provider. In Java 1.4, the “SunX509” algorithm is the only one supported by the default “SunJSSE” provider. After calling getInstance(), you initialize the factory object with init(). For the “SunX509” algorithm, you always use the two-argument version of init() passing in a KeyStore object that contains the private keys and certificates required by X509KeyManager objects, and also specifying the password used to protect the private keys in that KeyStore. Once a KeyManagerFactor y has been created and initialized, use it to create a KeyManager by calling getKeyManagers(). This method returns an array of KeyManager objects because some key management algorithms may handle more than one type of key. The “SunX509” algorithm manages only X509 keys, and always returns an array with an X509KeyManager object as its single element. This returned array is typically passed to the init() method of an SSLContext object. If a KeyStore and password are not passed to the init() method of the KeyManagerFactor y for the “SunX509” algorithm, then the factory uses attempts to read a KeyStore from the file specified by the javax.net.ssl.keyStore system property using the password specified by the javax.net.ssl.keyStorePassword. The type of the keystore is specified by javax.net.ssl.keyStoreType. public class KeyManagerFactor y { // Protected Constructors protected KeyManagerFactor y(KeyManagerFactorySpi factorySpi, java.security.Provider provider, String algorithm); // Public Class Methods public static final String getDefaultAlgorithm(); public static final KeyManagerFactory getInstance(String algorithm) throws java.security.NoSuchAlgorithmException; public static final KeyManagerFactory getInstance(String algorithm, java.security.Provider provider) throws java.security.NoSuchAlgorithmException; public static final KeyManagerFactory getInstance(String algorithm, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException; // Public Instance Methods public final String getAlgorithm(); public final KeyManager[ ] getKeyManagers(); public final java.security.Provider getProvider(); public final void init(ManagerFactoryParameters spec) throws java.security.InvalidAlgorithmParameterException; public final void init(java.security.KeyStore ks, char[ ] password) throws java.security.KeyStoreException, java.security.NoSuchAlgorithmException, java.security.UnrecoverableKeyException; } Returned By: KeyManagerFactor y.getInstance()

768

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

SSLContext

KeyManagerFactor ySpi

Java 1.4

javax.net.ssl This abstract class defines the Service Provider Interface for KeyManagerFactor y. Security providers must implement this interface, but applications never need to use it. public abstract class KeyManagerFactor ySpi { // Public Constructors public KeyManagerFactor ySpi(); // Protected Instance Methods protected abstract KeyManager[ ] engineGetKeyManagers(); protected abstract void engineInit(ManagerFactoryParameters spec) throws java.security.InvalidAlgorithmParameterException; protected abstract void engineInit(java.security.KeyStore ks, char[ ] password) throws java.security.KeyStoreException, java.security.NoSuchAlgorithmException, java.security.UnrecoverableKeyException; } Passed To: KeyManagerFactor y.KeyManagerFactor y()

ManagerFactor yParameters

Java 1.4

javax.net.ssl This marker interface identifies objects that provide algorithm-specific or providerspecific initialization parameters for KeyManagerFactor y and TrustManagerFactor y objects. In the default “SunJSSE” provider shipped by Sun, the only supported type for these factory classes is “SunX509”. Factories of these types need to be initialized with a KeyStore object but do not require any specialized ManagerFactor yParameters object. Therefore, the javax.net.ssl package does not define any sub-interfaces of this interface, and it is never used with the default provider. Third-party or future providers may use it, however. public interface ManagerFactor yParameters { } Passed To: KeyManagerFactor y.init(), KeyManagerFactor ySpi.engineInit(), TrustManagerFactor y.init(), TrustManagerFactor ySpi.engineInit()

SSLContext

Java 1.4

javax.net.ssl This class is a factory for socket and server socket factories. Although most applications do not need to use this class directly, it is the central class of the javax.net.ssl package. Most applications use the default SSLSocketFactor y and SSLSer verSocketFactor y objects returned by the static getDefault() methods of those classes. Applications that want to perform SSL networking using a security provider other than the default provider, or that want to customize key management or trust management for the SSL connection should use custom socket factories created from a custom SSLContext. Create an SSLContext by passing the name of the desired secure socket protocol and, optionally, the desired provider to getInstance(). The default “SunJSSE” provider supports protocol strings “SSL”, “SSLv2”, “SSLv3”, “TLS”, and “TLSv1”. Once you have created an SSLContext object, call its init() method to supply the KeyManager, TrustManager and SecureRandom objects it requires. If any of the init() arguments is null, a default value will be used. Finally, obtain a SSLSocketFactor y and SSLSer verSocketFactor y by calling getSocketFactor y() and getSer verSocketFactor y(). public class SSLContext { // Protected Constructors

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

769

SSLContext

protected SSLContext(SSLContextSpi contextSpi, java.security.Provider provider, String protocol); // Public Class Methods public static SSLContext getInstance(String protocol) throws java.security.NoSuchAlgorithmException; public static SSLContext getInstance(String protocol, java.security.Provider provider) throws java.security.NoSuchAlgorithmException; public static SSLContext getInstance(String protocol, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException; // Property Accessor Methods (by property name) public final SSLSessionContext getClientSessionContext(); public final String getProtocol(); public final java.security.Provider getProvider(); public final SSLSessionContext getSer verSessionContext(); public final SSLServerSocketFactory getSer verSocketFactor y(); public final SSLSocketFactory getSocketFactor y(); // Public Instance Methods public final void init(KeyManager[ ] km, TrustManager[ ] tm, java.security.SecureRandom random) throws java.security.KeyManagementException; } Returned By: SSLContext.getInstance()

SSLContextSpi

Java 1.4

javax.net.ssl This abstract class defines the Service Provider Interface for SSLContext. Security providers must implement this interface, but applications never need to use it. public abstract class SSLContextSpi { // Public Constructors public SSLContextSpi(); // Protected Instance Methods protected abstract SSLSessionContext engineGetClientSessionContext(); protected abstract SSLSessionContext engineGetSer verSessionContext(); protected abstract SSLServerSocketFactory engineGetSer verSocketFactor y(); protected abstract SSLSocketFactory engineGetSocketFactor y(); protected abstract void engineInit(KeyManager[ ] km, TrustManager[ ] tm, java.security.SecureRandom sr) throws java.security.KeyManagementException; } Passed To: SSLContext.SSLContext()

SSLException

Java 1.4 serializable checked

javax.net.ssl

This exception signals an SSL-related problem. This class serves as the common superclass of more specific SSL exception subclasses. Object

Throwable

Exception

IOException

SSLException

Serializable

public class SSLException extends java.io.IOException { // Public Constructors public SSLException(String reason); } Subclasses: SSLHandshakeException, SSLKeyException, SSLPeerUnverifiedException, SSLProtocolException

770

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

SSLPermission

SSLHandshakeException

Java 1.4 serializable checked

javax.net.ssl

This exception signals that the SSL handshake failed for some reason other than failed authentication (see SSLPeerUnverifiedException). For example, it may be thrown because the client and server count not agree on a mutually-acceptable cipher suite. When this exception is thrown, the SSLSocket object is no longer usable. Object

Throwable

Exception

IOException

SSLException

SSLHandshakeException

Serializable

public class SSLHandshakeException extends SSLException { // Public Constructors public SSLHandshakeException(String reason); }

SSLKeyException

Java 1.4 serializable checked

javax.net.ssl

This exception signals a problem with the public key certificate and private key used by a server (or client) for authentication. Object

Throwable

Exception

IOException

SSLException

SSLKeyException

Serializable

public class SSLKeyException extends SSLException { // Public Constructors public SSLKeyException(String reason); }

SSLPeerUnverifiedException

Java 1.4 serializable checked

javax.net.ssl

This exception signals that authentication of the remote host was not successfully completed. Object

Throwable

Exception

IOException

SSLException

SSLPeerUnverifiedException

Serializable

public class SSLPeerUnverifiedException extends SSLException { // Public Constructors public SSLPeerUnverifiedException(String reason); } Thrown By: HandshakeCompletedEvent.{getPeerCertificateChain(), getPeerCertificates()}, HttpsURLConnection.getSer verCertificates(), SSLSession.{getPeerCertificateChain(), getPeerCertificates()}

SSLPermission javax.net.ssl

Java 1.4 serializable permission

This Permission class controls access to sensitive methods in the javax.net.ssl package. The two defined target names are “setHostnameVerifier” and “getSSLSessionContext”. The first is required in order to call HttpURLConnection.setHostnameVerifier() and HttpURLConnec-

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

771

SSLPermission tion.setDefaultHostnameVerifier(). The second permission target is required in order to call SSLSession.getSessionContext(). Object

Permission

BasicPermission

Guard

Serializable

Serializable

SSLPermission

public final class SSLPermission extends java.security.BasicPermission { // Public Constructors public SSLPermission(String name); public SSLPermission(String name, String actions); }

SSLProtocolException

Java 1.4 serializable checked

javax.net.ssl

This signals a problem at the SSL protocol level. An exception of this type usually indicates that there is a bug in the SSL implementation being used locally or on the remote host. Object

Throwable

Exception

IOException

SSLException

SSLProtocolException

Serializable

public class SSLProtocolException extends SSLException { // Public Constructors public SSLProtocolException(String reason); }

SSLSer verSocket

Java 1.4

javax.net.ssl This class is an SSL-enabled subclass of java.net.Ser verSocket that is used to listen for and accept connections from clients and to create SSLSocket objects for communicating with those clients. Create an SSLSer verSocket and bind it to a local port by calling one of the inherited createSer verSocket() methods of an SSLSer verSocketFactor y. Once a SSLSer verSocket is created, use it as you would a regular Ser verSocket: call the inherited accept() method to wait for and accept a connection from a client, returning a Socket object. With SSLSer verSocket, the Socket returned by accept() can always be cast to an instance of SSLSocket. SSLSer verSocket defines methods for setting the enabled protocols and cipher suites, and for querying the full set of supported protocols and suites. See SSLSocket, which has methods with the same names, for details. If your server desires or requires authentication by its clients, call setWantClientAuth() or setNeedClientAuth(). These methods cause the SSLSocket objects returned by accept() to be configured to request or require client authentication. In typical SSL networking scenarios, the client requires the server to provide authentication information. When you create an SSLSer verSocket using the default SSLSer verSocketFactor y, the authentication information required is an X.509 public key certificate and the corresponding private key. The default SSLSer verSocketFactor y uses an X509KeyManager to obtain this information. The default X509KeyManager attempts to read this information from the java.security.KeyStore file specified by the system property javax.net.ssl.keyStore. It uses the value of the the javax.net.ssl.keyStorePassword as the keystore password, and uses the value of the javax.net.ssl.keyStoreType system property to specify the keystore type. The key store should only contain valid keys and certificate chains that identify the

772

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

SSLServerSocketFactory server; the X509KeyManager automatically chooses a key and certificate chain that are appropriate for the client. Object

ServerSocket

SSLServerSocket

public abstract class SSLSer verSocket extends java.net.ServerSocket { // Protected Constructors protected SSLSer verSocket() throws java.io.IOException; protected SSLSer verSocket(int port) throws java.io.IOException; protected SSLSer verSocket(int port, int backlog) throws java.io.IOException; protected SSLSer verSocket(int port, int backlog, java.net.InetAddress address) throws java.io.IOException; // Property Accessor Methods (by property name) public abstract String[ ] getEnabledCipherSuites(); public abstract void setEnabledCipherSuites(String[ ] suites); public abstract String[ ] getEnabledProtocols(); public abstract void setEnabledProtocols(String[ ] protocols); public abstract boolean getEnableSessionCreation(); public abstract void setEnableSessionCreation(boolean flag); public abstract boolean getNeedClientAuth(); public abstract void setNeedClientAuth(boolean flag); public abstract String[ ] getSupportedCipherSuites(); public abstract String[ ] getSupportedProtocols(); public abstract boolean getUseClientMode(); public abstract void setUseClientMode(boolean flag); public abstract boolean getWantClientAuth(); public abstract void setWantClientAuth(boolean flag); }

SSLSer verSocketFactor y

Java 1.4

javax.net.ssl This class is a javax.net.Ser verSocketFactor y for creating SSLSer verSocket objects. Most applications use the default SSLSer verSocketFactor y returned by the static getDefault() method. Once this SSLSer verSocketFactor y has been obtained, they use one of the inherited createSer verSocket() methods to create and optionally bind a new SSLSer verSocket. The return value of the createSer verSocket() methods is a java.net.Ser verSocket object, but you can safely cast this object to a SSLSer verSocket if you need to. Applications that need to customize the SSL configuration and cannot use the default server socket factory may obtain a custom SSLSer verSocketFactor y from an SSLContext, which is essentially a factory for socket factories. See SSLContext for details. Object

ServerSocketFactory

SSLServerSocketFactory

public abstract class SSLSer verSocketFactor y extends javax.net.ServerSocketFactory { // Protected Constructors protected SSLSer verSocketFactor y(); // Public Class Methods public static javax.net.ServerSocketFactory getDefault(); // Public Instance Methods public abstract String[ ] getDefaultCipherSuites(); public abstract String[ ] getSupportedCipherSuites(); }

synchronized

Returned By: SSLContext.getSer verSocketFactor y(), SSLContextSpi.engineGetSer verSocketFactor y()

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

773

SSLSession

SSLSession

Java 1.4

javax.net.ssl A SSLSession object contains information about the SSL connection established through an SSLSocket. Use the the getSession() method of a SSLSocket to obtain the SSLSession object for that socket. Many of the SSLSession methods return information that was obtained during the handshake phase of the connection. getProtocol() returns the specific version of the SSL or TLS protocol in use. getCipherSuite() returns the name of the cipher suite negotiated for the connection. getPeerHost() returns the name of the remote host, and getPeerCertificates() returns the certificate chain, if any, that was received from the remote host during authentication. The invalidate() method ends the session. It does not affect any current connections, but all future connections and any renegotiations of existing connections will need to establish a new SSLSession. Multiple SSL connections between two hosts may share the same SSLSession as long as they are using the same protocol version and cipher suite. There is no way to enumerate the SSLSocket objects that share a session, but these sockets can exchange information by using putValue() to bind a shared object to some well-known name that can be looked up by other sockets with getValue(). removeValue() removes such a binding, and getValueNames() returns an array of all names that have objects bound to them in this session. Objects bound and unbound with putValue() and removeValue() may implement SSLSessionBindingListener to be notified when they are bound and unbound. Note that the getPeerCertificateChain() method returns an object from the javax.security.cert package, which is not documented in this book. The method and package exist only for backward compatibility with earlier versions of the JSSE API, and should be considered deprecated. Use getPeerCertificates(), which uses java.security.cert instead. public interface SSLSession { // Property Accessor Methods (by property name) public abstract String getCipherSuite(); public abstract long getCreationTime(); public abstract byte[ ] getId(); public abstract long getLastAccessedTime(); public abstract java.security.cert.Certificate[ ] getLocalCertificates(); public abstract javax.security.cert.X509Certificate[ ] getPeerCertificateChain() throws SSLPeerUnverifiedException; public abstract java.security.cert.Certificate[ ] getPeerCertificates() throws SSLPeerUnverifiedException; public abstract String getPeerHost(); public abstract String getProtocol(); public abstract SSLSessionContext getSessionContext(); public abstract String[ ] getValueNames(); // Public Instance Methods public abstract Object getValue(String name); public abstract void invalidate(); public abstract void putValue(String name, Object value); public abstract void removeValue(String name); } Passed To: HandshakeCompletedEvent.HandshakeCompletedEvent(), HostnameVerifier.verify(), SSLSessionBindingEvent.SSLSessionBindingEvent() Returned By: javax.naming.ldap.StartTlsResponse.negotiate(), HandshakeCompletedEvent.getSession(), SSLSessionBindingEvent.getSession(), SSLSessionContext.getSession(), SSLSocket.getSession()

774

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

SSLSessionContext

SSLSessionBindingEvent

Java 1.4 serializable event

javax.net.ssl

An object of this type is passed to the valueBound() and valueUnbound() methods of and object that implements SSLSessionBindingListener when that object is bound or unbound in a SSLSession with the putValue() or removeValue() methods of SSLSession. getName() returns the name to which the object was bound or unbound, and getSession() returns the SSLSession object in which the binding was created or removed. Object

EventObject

SSLSessionBindingEvent

Serializable

public class SSLSessionBindingEvent extends java.util.EventObject { // Public Constructors public SSLSessionBindingEvent(SSLSession session, String name); // Public Instance Methods public String getName(); public SSLSession getSession(); } Passed To: SSLSessionBindingListener.{valueBound(), valueUnbound()}

SSLSessionBindingListener

Java 1.4 event listener

javax.net.ssl

This interface is implemented by an object that want to be notified when it is bound or unbound in an SSLSession object. If the object passed to the putValue() method of a SSLSession implements this interface, then its valueBound() method will be called by putValue(), and its valueUnbound() method will be called when that object is removed from the SSLSession with removeValue() or when it is replaced with a new object by putValue(). The argument to both methods of this interface is a SSLSessionBindingEvent, which specifies both the name to which the object was bound or unbound, and the SSLSession within which it was bound or unbound. EventListener

SSLSessionBindingListener

public interface SSLSessionBindingListener extends java.util.EventListener { // Public Instance Methods public abstract void valueBound(SSLSessionBindingEvent event); public abstract void valueUnbound(SSLSessionBindingEvent event); }

SSLSessionContext

Java 1.4

javax.net.ssl A SSLSessionContext groups and controls SSLSession objects. It is a low-level interface and is not commonly used in application code. getIds() returns an Enumeration of session IDs, and getSession() returns the SSLSession object associated with one of those IDs. setSessionCacheSize() specifies the total number of concurrent sessions allowed in the group, and setSessionTimeout() specifies the timeout length for those sessions. An SSLSessionContext can serve as a cache for SSLSession objects, facilitating reuse of those objects for multiple connections between the same two hosts. Providers are not required to support this interface. Those that do return an implementing object from the getSessionContext() method of an SSLSession object, and also return implementing objects from the getClientSessionContext() and getSer verSessionContext() meth-

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

775

SSLSessionContext ods of an SSLContext object, providing separate control over client and server SSL connections. public interface SSLSessionContext { // Public Instance Methods public abstract java.util.Enumeration getIds(); public abstract SSLSession getSession(byte[ ] sessionId); public abstract int getSessionCacheSize(); public abstract int getSessionTimeout(); public abstract void setSessionCacheSize(int size) throws IllegalArgumentException; public abstract void setSessionTimeout(int seconds) throws IllegalArgumentException; } Returned By: SSLContext.{getClientSessionContext(), getSer verSessionContext()}, SSLContextSpi.{engineGetClientSessionContext(), engineGetServerSessionContext()}, SSLSession.getSessionContext()

SSLSocket

Java 1.4

javax.net.ssl An SSLSocket is a “secure socket” subclass of java.net.Socket that implements the SSL or TLS protocols, which are commonly used to authenticate a server to a client and to encrypt the data transferred between the two. Create a SSLSocket for connecting to a SSL-enabled server by calling one of the createSocket() methods of a SSLSocketFactor y object. See SSLSocketFactor y for details. If you are writing server code, then you will obtain a SSLSocket for communicating with an SSL-enabled client from the inherited accept() method of an SSLSer verSocket. See SSLSer verSocket for details. SSLSocket inherits all of the standard socket method of its superclass, and can be used for networking just like an ordinary java.net.Socket object. In addition, however, it also defines methods that control how the secure connection is established. These methods may be called before the SSL “handshake” occurs. The handshake does not occur when the socket is first created and connected, so that you can configure various SSL parameters that control how the handshake occurs. Calling startHandshake(), getSession(), or reading or writing data on the socket trigger a handshake, so you must configure the socket before doing any of these things. If you want to be notified when the handshake occurs, call addHandshakeCompletedListener() to register a listener object to receive the notification. getSupportedProtocols() returns a list of secure socket protocols that are supported by the socket implementation. setEnabledProtocols() allows you to specify the name or names of the supported protocols that you are willing to use for this socket. getSupportedCipherSuites() returns the full set of cipher suites supported by the underlying security provider. setEnabledCipherSuites() specifies a list of one or more cipher suites that you are willing to use for the connection. Note that not all supported cipher suites are enabled by default: only suites that provide encryption and require the server to authenticate itself to the client are enabled. If you want to allow the server to remain anonymous, you can use setEnabledCipherSuites() to enable a nonauthenticating suite. Specific protocols and cipher suites are not described here because using them correctly requires a detailed understanding of cryptography, which is beyond the scope of this reference. Most applications can simply rely on the default set of enabled protocols and cipher suites. If you are writing a server and have obtained an SSLSocket by accepting a connection on an SSLSer verSocket, then you may call setWantClientAuth() to request that the client authenticate itself to you, and you may call setNeedClientAuth() to require that the client authenticate itself during the handshake. Note, however, that it is usually more efficient to request or require client authentication on the server socket than it is to call these

776

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

SSLSocketFactory methods on each SSLSocket it creates. The configuration methods described above must be called before the SSL handshake occurs. Call getSession() to obtain an SSLSession object that you can query for for information about the handshake, such as the protocol and cipher suite in use, and the identity of the server. Note that a call to getSession() will cause the handshake to occur if it has not already occurred, so you can call this method at any time. Object

Socket

SSLSocket

public abstract class SSLSocket extends java.net.Socket { // Protected Constructors protected SSLSocket(); protected SSLSocket(String host, int port) throws java.io.IOException, java.net.UnknownHostException; protected SSLSocket(java.net.InetAddress address, int port) throws java.io.IOException, java.net.UnknownHostException; protected SSLSocket(String host, int port, java.net.InetAddress clientAddress, int clientPort) throws java.io.IOException, java.net.UnknownHostException; protected SSLSocket(java.net.InetAddress address, int port, java.net.InetAddress clientAddress, int clientPort) throws java.io.IOException, java.net.UnknownHostException; // Event Registration Methods (by event name) public abstract void addHandshakeCompletedListener(HandshakeCompletedListener listener); public abstract void removeHandshakeCompletedListener(HandshakeCompletedListener listener); // Property Accessor Methods (by property name) public abstract String[ ] getEnabledCipherSuites(); public abstract void setEnabledCipherSuites(String[ ] suites); public abstract String[ ] getEnabledProtocols(); public abstract void setEnabledProtocols(String[ ] protocols); public abstract boolean getEnableSessionCreation(); public abstract void setEnableSessionCreation(boolean flag); public abstract boolean getNeedClientAuth(); public abstract void setNeedClientAuth(boolean need); public abstract SSLSession getSession(); public abstract String[ ] getSupportedCipherSuites(); public abstract String[ ] getSupportedProtocols(); public abstract boolean getUseClientMode(); public abstract void setUseClientMode(boolean mode); public abstract boolean getWantClientAuth(); public abstract void setWantClientAuth(boolean want); // Public Instance Methods public abstract void startHandshake() throws java.io.IOException; } Passed To: HandshakeCompletedEvent.HandshakeCompletedEvent() Returned By: HandshakeCompletedEvent.getSocket()

SSLSocketFactor y

Java 1.4

javax.net.ssl This class is a javax.net.SocketFactor y for creating SSLSocket objects. Most applications use the default SSLSocketFactor y returned by the static getDefault() method. Once this SSLSocketFactor y has been obtained, they use one of the inherited createSocket() methods to create, and optionally connect and bind, a new SSLSocket. The return value of the createSocket() methods is a java.net.Socket object, but you can safely cast this object to a SSLSocket if you need to. SSLSocketFactor y defines one new version of createSocket() in addition to the ones it inherits from its superclass. This version of the method creates an SSLSocket that is layered over an existing Socket object rather than creating a new

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

777

SSLSocketFactory socket entirely from scratch. Applications that need to customize the SSL configuration and cannot use the default socket factory may obtain a custom SSLSocketFactor y from an SSLContext, which is essentially a factory for socket factories. See SSLContext for details. Object

SocketFactory

SSLSocketFactory

public abstract class SSLSocketFactor y extends javax.net.SocketFactory { // Public Constructors public SSLSocketFactor y(); // Public Class Methods public static javax.net.SocketFactory getDefault(); synchronized // Public Instance Methods public abstract java.net.Socket createSocket(java.net.Socket s, String host, int port, boolean autoClose) throws java.io.IOException; public abstract String[ ] getDefaultCipherSuites(); public abstract String[ ] getSupportedCipherSuites(); } Passed To: javax.naming.ldap.StartTlsResponse.negotiate(), HttpsURLConnection.{setDefaultSSLSocketFactor y(), setSSLSocketFactor y()} Returned By: HttpsURLConnection.{getDefaultSSLSocketFactor y(), getSSLSocketFactor y()}, SSLContext.getSocketFactor y(), SSLContextSpi.engineGetSocketFactor y()

TrustManager

Java 1.4

javax.net.ssl This is a marker interface to identify trust manager objects. A trust manager is responsible for examining the authentication credentials (such as a certificate chain) presented by the remote host and deciding whether to trust those credentials and accept them. A TrustManager is usually used an SSL client to decide whether the SSL server is authentic, but may also be used by an SSL server when client authentication is also required. Use a TrustManagerFactor y to obtain TrustManager objects. TrustManager objects returned by a TrustManagerFactor y can always be cast to a sub-interface specific to a specific type of keys. See X509TrustManager, for example. public interface TrustManager { } Implementations: X509TrustManager Passed To: SSLContext.init(), SSLContextSpi.engineInit() Returned By: TrustManagerFactor y.getTrustManagers(), TrustManagerFactor ySpi.engineGetTrustManagers()

TrustManagerFactor y

Java 1.4

javax.net.ssl A TrustManagerFactor y is responsible for creating TrustManager objects for a specific trust management algorithm. Obtain a TrustManagerFactor y object by calling one of the getInstance() methods and specifying the desired algorithm and, optionally, the desired provider. In Java 1.4, the “SunX509” algorithm is the only one supported by the default “SunJSSE” provider. After calling getInstance(), you initialize the factory object with init(). For the “SunX509” algorithm, you pass a KeyStore object to init(). This KeyStore should contain the public keys of trusted CAs (certification authorities). Once a TrustManagerFactor y has been created and initialized, use it to create a TrustManager by calling

778

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

TrustManagerFactorySpi getTrustManagers(). This method returns an array of TrustManager objects because some trust management algorithms may handle more than one type of key or certificate. The “SunX509” algorithm manages only X.509 keys, and always returns an array with an X509TrustManager object as its single element. This returned array is typically passed to the init() method of an SSLContext object. If no KeyStore is passed to the init() method of the TrustManagerFactor y for the “SunX509” algorithm, then the factory uses a KeyStore created from the file named by the system property javax.net.ssl.trustStore if that property is defined. (It also uses the key store type and password specified by the properties javax.net.ssl.trustStoreType and javax.net.ssl.trustStorePassword.) Otherwise, it uses the file jr e/lib/security/jssecacerts in the Java distribution, if it exists. Otherwise it uses the file jr e/lib/security/cacerts which is part of Sun’s Java distribution. Sun ships a default cacerts file that contains certificates for several well-known and reputable CAs. You can use the keytool program to edit the cacerts keystore (the default password is “changeit”). public class TrustManagerFactor y { // Protected Constructors protected TrustManagerFactor y(TrustManagerFactorySpi factorySpi, java.security.Provider provider, String algorithm); // Public Class Methods public static final String getDefaultAlgorithm(); public static final TrustManagerFactory getInstance(String algorithm) throws java.security.NoSuchAlgorithmException; public static final TrustManagerFactory getInstance(String algorithm, java.security.Provider provider) throws java.security.NoSuchAlgorithmException; public static final TrustManagerFactory getInstance(String algorithm, String provider) throws java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException; // Public Instance Methods public final String getAlgorithm(); public final java.security.Provider getProvider(); public final TrustManager[ ] getTrustManagers(); public final void init(ManagerFactoryParameters spec) throws java.security.InvalidAlgorithmParameterException; public final void init(java.security.KeyStore ks) throws java.security.KeyStoreException; } Returned By: TrustManagerFactor y.getInstance()

TrustManagerFactor ySpi

Java 1.4

javax.net.ssl This abstract class defines the Service Provider Interface for TrustManagerFactor y. Security providers must implement this interface, but applications never need to use it. public abstract class TrustManagerFactor ySpi { // Public Constructors public TrustManagerFactor ySpi(); // Protected Instance Methods protected abstract TrustManager[ ] engineGetTrustManagers(); protected abstract void engineInit(ManagerFactoryParameters spec) throws java.security.InvalidAlgorithmParameterException; protected abstract void engineInit(java.security.KeyStore ks) throws java.security.KeyStoreException; } Passed To: TrustManagerFactor y.TrustManagerFactor y()

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

779

X509KeyManager

X509KeyManager

Java 1.4

javax.net.ssl This interface is a KeyManager for working with X.509 certificates. An X509KeyManager is used during the SSL handshake by a peer that authenticates itself by providing an X.509 certificate chain to the remote host. This is usually done on the server side of the SSL connection, and can be done on the client-side as well, although that is uncommon. Obtain an X509KeyManager object either by implementing your own or from a KeyManagerFactor y created with an algorithm of “SunX509”. Applications do not call the methods of an X509KeyManager themselves. Instead, they simply supply an appropriate X509KeyManager object to the SSLContext object that is responsible for setting up SSL connections. When the system needs to authenticate itself during an SSL handshake, it calls various methods of the key manager object to obtain the information in needs. An X509KeyManager retrieves keys and certificate chains from the KeyStore object that was passed to the init() method of the KeyManagerFactor y object from which it was created. getPrivateKey() and getCertificateChain() return the private key and the certificate chain for a specified alias. The other methods are called to list all aliases in the keystore or to choose one alias from the keystore that matches the specified keytype and certificate authority criteria. In this way, a X509KeyManager can choose a certificate chain (and its corresponding key) based on the types of keys and the list of certificate authorities recognized by the remote host. KeyManager

X509KeyManager

public interface X509KeyManager extends KeyManager { // Public Instance Methods public abstract String chooseClientAlias(String[ ] keyType, java.security.Principal[ ] issuers, java.net.Socket socket); public abstract String chooseSer verAlias(String keyType, java.security.Principal[ ] issuers, java.net.Socket socket); public abstract java.security.cert.X509Certificate[ ] getCertificateChain(String alias); public abstract String[ ] getClientAliases(String keyType, java.security.Principal[ ] issuers); public abstract java.security.PrivateKey getPrivateKey(String alias); public abstract String[ ] getSer verAliases(String keyType, java.security.Principal[ ] issuers); }

X509TrustManager

Java 1.4

javax.net.ssl This interface is a TrustManager for working with X.509 certificates. Trust managers are used during the handshake phase of SSL connection to determine whether the authentication credentials presented by the remote host are trusted. This is usually done on the client-side of an SSL connection, but may also be done on the server side. Obtain an X509TrustManager either by implementing your own or from a TrustManagerFactor y that was created to use the “SunX509” algorithm. Applications do call the methods of this interface themselves; instead, they simply provide an appropriate X509TrustManager object to the SSLContext object that is responsible for setting up SSL connections. When the system needs to determine whether the authentication credentials presented by the remote host are trusted, it calls the methods of the trust manager. TrustManager

X509TrustManager

public interface X509TrustManager extends TrustManager { // Public Instance Methods public abstract void checkClientTrusted(java.security.cert.X509Certificate[ ] chain, String authType) throws java.security.cert.CertificateException;

780

7 March 2002 11:38

Chapter 19 – javax.net and javax.net.ssl

X509TrustManager

public abstract void checkSer verTrusted(java.security.cert.X509Certificate[ ] chain, String authType) throws java.security.cert.CertificateException; public abstract java.security.cert.X509Certificate[ ] getAcceptedIssuers(); }

Chapter 19 – javax.net and javax.net.ssl

7 March 2002 11:38

781

CHAPTER 20

javax.security.auth and Subpackages

This chapter documents the javax.security.auth package and its sub-packages, which, together, form the Java Authentication and Authorization Service, or JAAS. Before being integrated into Java 1.4, JAAS was available as a standard extension, which is why these packages have the “javax” prefix. The individual packages are the following: javax.security.auth This top-level package defines the Subject class that is central to JAAS. javax.security.auth.callback This package defines a callback API to enable communication (such as the exchange of a username and password) between a low-level login module and the end user. javax.security.auth.kerberos This package contains JAAS classes related to the Kerberos network authentication protocol. javax.security.auth.login This package defines the LoginContext class and related classes used by applications to perform a JAAS login. javax.security.auth.spi This package defines the “service provider interface” for JAAS. javax.security.auth.x500 This package includes JAAS classes related to X.500 principals.

Package javax.security.auth

Java 1.4

This is the top-level package of the Java Authentication and Authorization Service (JAAS). The key class is Subject, which represents an authenticated user, and defines static methods that allow Java code be run “as” (i.e., using the permissions of) a speci-

782

7 March 2002 11:39

AuthPermission fied Subject. The remaining classes and interfaces in this package are important parts of the JAAS infrastructure, but are not commonly used in application code. Applications do not create Subject objects directly, but typically obtain them from a javax.security.auth.login.LoginContext constructed with a javax.security.auth.callback.Callback-Handler. Interfaces: public interface Destroyable; public interface Refreshable; Classes: public final class AuthPermission extends java.security.BasicPermission; public abstract class Policy; public final class PrivateCredentialPermission extends java.security.Permission; public final class Subject implements Serializable; public class SubjectDomainCombiner implements java.security.DomainCombiner ; Exceptions: public class DestroyFailedException extends Exception; public class RefreshFailedException extends Exception;

AuthPermission

Java 1.4 serializable permission

javax.security.auth

This java.security.Permission class governs the use of various methods in this package and its subpackages. The target name of the permission specifies which methods are allowed; AuthPermission objects have no actions list. Application programmers never need to use this class directly. System implementors may need to use it, and system administrators who configure security policies may need to be familiar with the following table of target names and the permissions they represent. Target name

Gives permission to

doAs

Invoke Subject.doAs() methods.

doAsPrivileged

Invoke Subject.doAsPrivileged() methods.

getSubject

Invoke Subject.getSubject().

getSubjectFromDomainCombiner

Invoke SubjectDomainCombiner.getSubject().

setReadOnly

Invoke Subject.setReadOnly().

modifyPrincipals

Modify the Set of principals associated with a Subject.

modifyPublicCredentials

Modify the Set of public credentials associated with a Subject.

modifyPrivateCredentials

Modify the Set of private credentials associated with a Subject.

refreshCredential

Invoke the refresh() method of a Refreshable credential class.

destroyCredential

Invoke the destroy() method of a Destroyable credential class.

createLoginContext.name

Instantiate a LoginContext with the specified name. If name is “*”, it allows a LoginContext of any name to be created.

getLoginConfiguration

Invoke the getConfiguration() method of javax.security.auth.login.Configuration.

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

783

AuthPermission Target name

Gives permission to

setLoginConfiguration

Invoke the setConfiguration() method of javax.security.auth.login.Configuration.

refreshLoginConfiguration

Invoke the refresh() method of javax.security.auth.login. Configuration.

Object

Permission

BasicPermission

Guard

Serializable

Serializable

AuthPermission

public final class AuthPermission extends java.security.BasicPermission { // Public Constructors public AuthPermission(String name); public AuthPermission(String name, String actions); }

Destroyable

Java 1.4

javax.security.auth Classes that encapsulate sensitive information, such as security credentials, may implement this interface to provide an API that allows the sensitive information to be destroyed or erased. The destroy() method erases or clears the sensitive information. It may throw a DestroyFailedException if the information cannot be erased for any reason. It may also throw a SecurityException if the caller does not have whatever permissions are required. Once destroy() has been called on an object, the isDestroyed() method returns true. Once an object has been destroyed, any other methods it defines may throw an IllegalStateException. public interface Destroyable { // Public Instance Methods public abstract void destroy() throws DestroyFailedException; public abstract boolean isDestroyed(); } Implementations: javax.security.auth.kerberos.KerberosKey, javax.security.auth.kerberos.KerberosTicket, javax.security.auth.x500.X500PrivateCredential

DestroyFailedException

Java 1.4 serializable checked

javax.security.auth

This exception signals that the destroy() method of a Destroyable object did not succeed. Object

Throwable

Exception

DestroyFailedException

Serializable

public class DestroyFailedException extends Exception { // Public Constructors public DestroyFailedException(); public DestroyFailedException(String msg); } Thrown By: Destroyable.destroy(), javax.security.auth.kerberos.KerberosKey.destroy(), javax.security.auth.kerberos.KerberosTicket.destroy()

784

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

PrivateCredentialPermission

Policy

Java 1.4; Deprecated in Java 1.4

javax.security.auth This deprecated class represents a Subject-based security policy. It Because the JAAS API (this package and its sub-packages) were introduced as an extension to the core Java platform, this class was required to augment the java.security.Policy class which, prior to Java 1.4, had no provisions for Subject-based authorization. In Java 1.4, however, java.security.Policy has been extended to represent security policies based on code origin, code signers, and subjects. Thus, this class is no longer required and has been deprecated. public abstract class Policy { // Protected Constructors protected Policy(); // Public Class Methods public static javax.security.auth.Policy getPolicy(); public static void setPolicy(javax.security.auth.Policy policy); // Public Instance Methods public abstract java.security.PermissionCollection getPermissions(Subject subject, java.security.CodeSource cs); public abstract void refresh(); } Passed To: javax.security.auth.Policy.setPolicy() Returned By: javax.security.auth.Policy.getPolicy()

PrivateCredentialPermission javax.security.auth

Java 1.4 serializable permission

This Permission class protects access to private credential objects belonging to a Subject (as specified by a set of one or more Principal objects). Application programmers rarely need to use it. System programmers implementing new private credentials classes may need to use it, and system administrators configuring security policy files should be familiar with it. The only defined action for PrivateCredentialPermission is “read”. The target name for this permission has a complex syntax and specifies the name of the credential class and a list of one or more principals. Each principal is specified as the name of the Principal class followed by the principal name in quotes. For example, a security policy file might contain a statement such as the following to allow permission to read the private KerberosKey credentials of a KerberosPrincipal named “david”: permission javax.security.auth.PrivateCredentialPermission "javax.security.auth.kerberos.KerberosKey javax.security.auth.kerberos.KerberosPrincipal \"david\"", "read";

The target name syntax for PrivateCredentialPermission also allows the use of the “*” wildcard in place of the credential class name or in place of the Principal class name and/or name. Object

Permission

Guard

Serializable

PrivateCredentialPermission

public final class PrivateCredentialPermission extends java.security.Permission { // Public Constructors public PrivateCredentialPermission(String name, String actions); // Public Instance Methods public String getCredentialClass(); public String[ ][ ] getPrincipals();

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

785

PrivateCredentialPermission

// Public Methods Overriding Permission public boolean equals(Object obj); public String getActions(); public int hashCode(); public boolean implies(java.security.Permission p); public java.security.PermissionCollection newPermissionCollection(); }

constant

Refreshable

Java 1.4

javax.security.auth A class implements this interface if its instances that have a limited period of validity (as some security credentials do) and need to be periodically “refreshed” in order to remain valid. isCurrent() returns true if the object is currently valid, and false if it has expired and needs to be refreshed. refresh() attempts to revalidate or extend the validity of the object. It throws a RefreshFailedException if it does not succeed (and may also throw a SecurityException if the caller does not have the requisite permissions). public interface Refreshable { // Public Instance Methods public abstract boolean isCurrent(); public abstract void refresh() throws RefreshFailedException; } Implementations: javax.security.auth.kerberos.KerberosTicket

RefreshFailedException

Java 1.4 serializable checked

javax.security.auth

This exception signals that the refresh() method of a Refreshable object failed. Object

Throwable

Exception

RefreshFailedException

Serializable

public class RefreshFailedException extends Exception { // Public Constructors public RefreshFailedException(); public RefreshFailedException(String msg); } Thrown By: Refreshable.refresh(), javax.security.auth.kerberos.KerberosTicket.refresh()

Subject javax.security.auth

Java 1.4 serializable

The Subject class is the key abstraction of the JAAS API. It represents a person or other entity and consists of: •

A java.util.Set of Principal objects that specify the identity (or identities) of the Subject.



A Set of objects that specify the public credentials, such as the public key certificates of the Subject.



A Set of objects that specify the private credentials, such as the private keys and Kerberos tickets of the Subject.

786

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

Subject Subject defines methods that allow you to retrieve each of these three sets, or to retrieve a subset of each set that contains only objects of a specified Class. Unless the Subject is read-only, you can use the methods of java.util.Set to modify each of the three sets. Once setReadOnly() has been called, however, the sets become immutable and their contents may not be modified. Application code does not typically create Subject objects itself. Instead, it obtains a Subject that represents the authenticated user of the application by calling the login() and getSubject() methods of a javax.security.auth.login.LoginContext object. Once an authenticated Subject has been obtained from a LoginContext, an application can call the doAs() method to run code using the permissions granted to that Subject combined with the permissions granted to the code itself. doAs() runs the code defined in the run() method of a PrivilegedAction or PrivilegedExceptionAction object. doAsPrivileged() is a similar method but executes the specified run() method using the Subject’s permissions only, unconstrained by unprivileged code in the call stack. Note that many of the methods of this class throw a SecurityException if the caller has not been granted the requisite AuthPermission. Object

Subject

Serializable

public final class Subject implements Serializable { // Public Constructors public Subject(); public Subject(boolean readOnly, java.util.Set principals, java.util.Set pubCredentials, java.util.Set privCredentials); // Public Class Methods public static Object doAs(Subject subject, java.security.PrivilegedExceptionAction action) throws java.security.PrivilegedActionException; public static Object doAs(Subject subject, java.security.PrivilegedAction action); public static Object doAsPrivileged(Subject subject, java.security.PrivilegedExceptionAction action, java.security.AccessControlContext acc) throws java.security.PrivilegedActionException; public static Object doAsPrivileged(Subject subject, java.security.PrivilegedAction action, java.security.AccessControlContext acc); public static Subject getSubject(java.security.AccessControlContext acc); // Property Accessor Methods (by property name) public java.util.Set getPrincipals(); public java.util.Set getPrincipals(Class c); public java.util.Set getPrivateCredentials(); public java.util.Set getPrivateCredentials(Class c); public java.util.Set getPublicCredentials(); public java.util.Set getPublicCredentials(Class c); public boolean isReadOnly(); default:false // Public Instance Methods public void setReadOnly(); // Public Methods Overriding Object public boolean equals(Object o); public int hashCode(); public String toString(); } Passed To: javax.security.auth.Policy.getPermissions(), Subject.{doAs(), doAsPrivileged()}, SubjectDomainCombiner.SubjectDomainCombiner(), javax.security.auth.login.LoginContext.LoginContext(), javax.security.auth.spi.LoginModule.initialize() Returned By: Subject.getSubject(), SubjectDomainCombiner.getSubject(), javax.security.auth.login.LoginContext.getSubject()

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

787

SubjectDomainCombiner

SubjectDomainCombiner

Java 1.4

javax.security.auth This class implements the DomainCombiner interface. It is used to merge permissions based on code source and code signers with permissions granted to the specified Subject. A SubjectDomainCombiner is created by the Subject.doAs() and Subject.doAsPrivileged() methods for use in by the AccessControlContext. Object

SubjectDomainCombiner

DomainCombiner

public class SubjectDomainCombiner implements java.security.DomainCombiner { // Public Constructors public SubjectDomainCombiner(Subject subject); // Public Instance Methods public Subject getSubject(); // Methods Implementing DomainCombiner public java.security.ProtectionDomain[ ] combine(java.security.ProtectionDomain[ ] currentDomains, java.security.ProtectionDomain[ ] assignedDomains); }

Package javax.security.auth.callback

Java 1.4

This package defines a mechanism that allows the low-level code of a javax.security.auth.spi.LoginModule to interact with the end user of an application to obtain a username, password, or other authentication-related information. The LoginModule sends messages and requests for information in the form of objects that implement the Callback interface. An application that wants to authenticate a user provides (via a javax.security.auth.login.LoginContext) a CallbackHandler object to convert these Callback objects into text or GUI-based interactions with the user. An application that want to provide a customized login interface must implement its own CallbackHandler. The CallbackHandler API consists of only a single method, but the implementation of that method can require a substantial amount of code. See the various Callback classes for directions on how a CallbackHandler should handle them. Sun’s J2SE SDK for Java 1.4 ships with two implementations of CallbackHandler, both in the package com.sun.security.auth.callback. Although these classes are not guaranteed to exist in all distributions, text-based applications may use the TextCallbackHandler, and GUI-based applications may use the DialogCallbackHandler. Programmers wanting to write a custom CallbackHandler may also find it useful to study the source code of these two existing handlers. Interfaces: public interface Callback; public interface CallbackHandler; Classes: public class ChoiceCallback implements Callback, Serializable; public class ConfirmationCallback implements Callback, Serializable; public class LanguageCallback implements Callback, Serializable; public class NameCallback implements Callback, Serializable; public class PasswordCallback implements Callback, Serializable; public class TextInputCallback implements Callback, Serializable; public class TextOutputCallback implements Callback, Serializable;

788

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

CallbackHandler Exception: public class UnsupportedCallbackException extends Exception;

Callback

Java 1.4

javax.security.auth.callback This interface defines no methods but serves as a “marker interface” to identify the type of objects that can be passed to the handle() method of a CallbackHandler. All of the classes in this package, with the exception of UnsupportedCallbackException implement this interface. public interface Callback { } Implementations: ChoiceCallback, ConfirmationCallback, LanguageCallback, NameCallback, PasswordCallback, TextInputCallback, TextOutputCallback Passed To: CallbackHandler.handle(), UnsupportedCallbackException.UnsupportedCallbackException() Returned By: UnsupportedCallbackException.getCallback()

CallbackHandler

Java 1.4

javax.security.auth.callback A CallbackHandler is responsible for communication between the end-user of an application and the javax.security.auth.spi.LoginModule that is performing authentication of that user on behalf of the javax.security.auth.login.LoginContext instantiated by the application. When an application needs to authenticate a user, it creates a LoginContext and specifies a CallbackHandler object for that context. The underlying LoginModule uses the CallbackHandler to communicate with the end user—for example, prompting them to enter a name and password. The LoginModule passes an array of objects that implement the Callback interface to the handle() method of CallbackHandler. The handle() method must determine the type of Callback object, and display the information and/or prompt for the input it represents. Different Callback classes have different purposes and must be handled differently. NameCallback and PasswordCallback are two of the most commonly used: they represent requests for the user’s name and password. TextOutputCallback is also common: it represents a request to display a message (such as “Authentication Failed”) to the user. See the descriptions of the individual Callback classes for information on how a CallbackHandler should handle them. CallbackHandler implementations are not required to support every type of Callback and my throw an UnsupportedCallbackException if passed a Callback object of a type they do not recognize or do not support. The handle() method is passed an array of Callback objects. A CallbackHandler (such as a typical console-based handler) may choose to handle the Callback objects one at a time, prompting for and returning the user’s input before moving on to the next. Or (for example in GUI-based handlers) it may choose to present all of the callbacks in a single unified “login dialog box”. LoginModule implementations may, of course, call the handle() method more than once. Note, finally, that if a CallbackHandler implementation has knowledge of the user from some other source, it is allowed to handle certain callbacks automatically, such as automatically providing the user’s name for a NameCallback. Java installations may have a default CallbackHandler registered by setting the auth.login.defaultCallbackHandler security property to the name of the implementing class.

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

789

CallbackHandler No such default is defined by the default security policy that ships with Sun’s distribution of Java 1.4. Sun’s Java 1.4 SDK does include CallbackHandler implementations to perform text-based and GUI-based communication in the classes TextCallbackHandler and DialogCallbackHandler in the com.sun.security.auth.callback package. Note that these are part of Sun’s implementation, and are not part of the specification; they are not guaranteed to exist in all releases. public interface CallbackHandler { // Public Instance Methods public abstract void handle(Callback[ ] callbacks) throws java.io.IOException, UnsupportedCallbackException; } Passed To: javax.security.auth.login.LoginContext.LoginContext(), javax.security.auth.spi.LoginModule.initialize()

ChoiceCallback javax.security.auth.callback

Java 1.4 serializable

A Callback of this type represents a request to display set of text choices and allow the user to select one or more of them. A CallbackHandler, should display the prompt returned by getPrompt() and also the strings returned by getChoices(). If allowMultipleSelections() is true, then it should allow the user to select zero or more; otherwise, it should only allow the user to select a single one. In either case, the CallbackHandler should also call getDefaultChoice() and make the choice at the returned index the default choice. When the user has made her selection, the CallbackHandler should pass the index of a single selection to setSelectedIndex(), or the indexes of multiple selections to setSelectedIndexes(). Object

ChoiceCallback

Callback

Serializable

public class ChoiceCallback implements Callback, Serializable { // Public Constructors public ChoiceCallback(String prompt, String[ ] choices, int defaultChoice, boolean multipleSelectionsAllowed); // Property Accessor Methods (by property name) public String[ ] getChoices(); public int getDefaultChoice(); public String getPrompt(); public int[ ] getSelectedIndexes(); public void setSelectedIndexes(int[ ] selections); // Public Instance Methods public boolean allowMultipleSelections(); public void setSelectedIndex(int selection); }

ConfirmationCallback javax.security.auth.callback

Java 1.4 serializable

A Callback of this type represents a request to ask the user a yes/no or multiple-choice question. A CallbackHandler should first call getPrompt() to obtain the text of the question. It should also call getMessageType() to determine the message type (INFORMATION, WARNING, or ERROR) and present the question to the user in a suitable manner based on that type.

790

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

ConfirmationCallback Next, the CallbackHandler must determine the appropriate set of responses to the question. It does this by calling getOptionType(). The return values have the following meanings: YES_NO_OPTION The CallbackHandler should allow the user to respond to the question with a “yes” or a “no” (or their localized equivalents). YES_NO_CANCEL_OPTION The CallbackHandler should allow “yes”, “no”, and “cancel” (or their localized equivalents) responses. OK_CANCEL_OPTION The CallbackHandler should allow “ok” and “cancel” (or their localized equivalents) responses. UNSPECIFIED_OPTION The CallbackHandler should call getOptions() and use present all strings it returns as possible responses. In each of these cases, the CallbackHandler should also call getDefaultOption() to determine which response should be presented as the default response. If getOptionType() returned UNSPECIFIED_OPTION, then getDefaultOption() returns an index into the array of options returned by getOptions(). Otherwise getDefaultOption() returns one of the constants YES, NO, OK, or CANCEL. When the user has selected a response to the callback, the CallbackHandler should pass that response to setSelectedIndex(). The response value should be one of the constants YES, NO, OK, or CANCEL, or an index into the array of options returned by getOptions(). Object

ConfirmationCallback

Callback

Serializable

public class ConfirmationCallback implements Callback, Serializable { // Public Constructors public ConfirmationCallback(int messageType, String[ ] options, int defaultOption); public ConfirmationCallback(int messageType, int optionType, int defaultOption); public ConfirmationCallback(String prompt, int messageType, String[ ] options, int defaultOption); public ConfirmationCallback(String prompt, int messageType, int optionType, int defaultOption); // Public Constants public static final int CANCEL; public static final int ERROR; public static final int INFORMATION; public static final int NO; public static final int OK; public static final int OK_CANCEL_OPTION; public static final int UNSPECIFIED_OPTION; public static final int WARNING; public static final int YES; public static final int YES_NO_CANCEL_OPTION; public static final int YES_NO_OPTION; // Property Accessor Methods (by property name) public int getDefaultOption(); public int getMessageType(); public String[ ] getOptions(); public int getOptionType(); public String getPrompt();

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

=2 =2 =0 =1 =3 =2 =-1 =1 =0 =1 =0

791

ConfirmationCallback

public int getSelectedIndex(); public void setSelectedIndex(int selection); }

LanguageCallback javax.security.auth.callback

Java 1.4 serializable

This Callback class represents a request for the user’s preferred language (as represented by a Locale object), which a LoginModule can use to localize things such as prompts and error messages in subsequent Callback objects. If a CallbackHandler already has knowledge of the user’s preferred langauge, it is not required to prompt the user for this information and can simply pass an appropriate Locale object to setLocale(). Object

LanguageCallback

Callback

Serializable

public class LanguageCallback implements Callback, Serializable { // Public Constructors public LanguageCallback(); // Public Instance Methods public java.util.Locale getLocale(); public void setLocale(java.util.Locale locale); }

NameCallback javax.security.auth.callback

default:null

Java 1.4 serializable

This Callback class represents a request for the username or other text that identifies the user to be authenticated. An interactive CallbackHandler should call getPrompt() and getDefaultName() and should display the returned prompt and optionally, the returned default name to the user. When the user has entered a name (or accepted the default name), the handler should pass the user’s input to setName(). Object

NameCallback

Callback

Serializable

public class NameCallback implements Callback, Serializable { // Public Constructors public NameCallback(String prompt); public NameCallback(String prompt, String defaultName); // Public Instance Methods public String getDefaultName(); public String getName(); public String getPrompt(); public void setName(String name); }

PasswordCallback javax.security.auth.callback

Java 1.4 serializable

This Callback class represents a request for a password. A CallbackHandler should handle it by displaying the prompt returned by getPrompt() and then allowing the user the enter a password. When the user has entered the password, it should pass the entered text to

792

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

TextOutputCallback setPassword(). If isEchoOn() returns true, then the Handler should display the password as the user types it. Object

PasswordCallback

Callback

Serializable

public class PasswordCallback implements Callback, Serializable { // Public Constructors public PasswordCallback(String prompt, boolean echoOn); // Public Instance Methods public void clearPassword(); public char[ ] getPassword(); public String getPrompt(); public boolean isEchoOn(); public void setPassword(char[ ] password); }

TextInputCallback

Java 1.4 serializable

javax.security.auth.callback

A Callback of this type is a request to prompt the user for text input; it is essentially a generic version of NameCallback. A CallbackHandler should call getPrompt() and should display the returned prompt text to the user. It should then allow the user to enter text, and provide the option of selecting the default text returned by getDefaultText(). When the user has entered text (or selected the default text) it should pass the user’s input to setText(). Object

TextInputCallback

Callback

Serializable

public class TextInputCallback implements Callback, Serializable { // Public Constructors public TextInputCallback(String prompt); public TextInputCallback(String prompt, String defaultText); // Public Instance Methods public String getDefaultText(); public String getPrompt(); public String getText(); public void setText(String text); }

TextOutputCallback

Java 1.4 serializable

javax.security.auth.callback

A Callback of this type represents a request to display text to the user. A callback handler should call getMessage() and display the returned string to the user. It should also call getMessageType() and use the returned value (which is one of the constants defined by the class) to indicate the type or severity of the information. Object

TextOutputCallback

Callback

Serializable

public class TextOutputCallback implements Callback, Serializable { // Public Constructors

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

793

TextOutputCallback

public TextOutputCallback(int messageType, String message); // Public Constants public static final int ERROR; public static final int INFORMATION; public static final int WARNING; // Public Instance Methods public String getMessage(); public int getMessageType(); }

UnsupportedCallbackException javax.security.auth.callback

=2 =0 =1

Java 1.4 serializable checked

CallbackHandler implementations may throw exceptions of this type from their handle() method if a Callback object passed to that method is of an unrecognized or unsupported type. Note that the offending Callback object must be passed to the constructor method. Object

Throwable

Exception

UnsupportedCallbackException

Serializable

public class UnsupportedCallbackException extends Exception { // Public Constructors public UnsupportedCallbackException(Callback callback); public UnsupportedCallbackException(Callback callback, String msg); // Public Instance Methods public Callback getCallback(); } Thrown By: CallbackHandler.handle()

Package javax.security.auth.kerberos

Java 1.4

This package defines classes for use with Kerberos: a secure network authentication protocol. They are primarily of interest to system-level programmers writing Kerberosbased javax.security.auth.spi.LoginModule implementations. Developers writing Kerberosenabled applications should use the org.ietf.jgss package. A full description of Kerberos is beyond the scope of this book; it is assumed that the reader is familiar with Kerberos authentication. Classes: public final class DelegationPermission extends java.security.BasicPermission implements Serializable; public class KerberosKey implements javax.security.auth.Destroyable, javax.cr ypto.SecretKey; public final class KerberosPrincipal implements java.security.Principal, Serializable; public class KerberosTicket implements javax.security.auth.Destroyable, javax.security.auth.Refreshable, Serializable; public final class ServicePermission extends java.security.Permission implements Serializable;

DelegationPermission javax.security.auth.kerberos

Java 1.4 serializable permission

This java.security.Permission class governs the delegation of Kerberos tickets from a Kerberos principal to a Kerberos service for use on behalf of the original principal. The tar-

794

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

KerberosKey get name of a DelegationPermission consists of the principal names of two Kerberos services. The first specifies the service that is being delegated to, and the second specifies the service that is to be used by the first on behalf of the original Kerberos principal. Object

Permission

BasicPermission

DelegationPermission

Guard

Serializable

Serializable

Serializable

public final class DelegationPermission extends java.security.BasicPermission implements Serializable { // Public Constructors public DelegationPermission(String principals); public DelegationPermission(String principals, String actions); // Public Methods Overriding BasicPermission public boolean equals(Object obj); public int hashCode(); public boolean implies(java.security.Permission p); public java.security.PermissionCollection newPermissionCollection(); }

KerberosKey

Java 1.4 serializable

javax.security.auth.kerberos

This class is a javax.cr ypto.SecretKey implementation that represents the secret key of a Kerberos principal. A Kerberos-based javax.security.auth.spi.LoginModule implementation instantiates a KerberosKey object and stores it in the private credential set of the authenticated Subject it creates. Object Destroyable

KerberosKey Serializable

Key

SecretKey

public class KerberosKey implements javax.security.auth.Destroyable, javax.crypto.SecretKey { // Public Constructors public KerberosKey(KerberosPrincipal principal, char[ ] password, String algorithm); public KerberosKey(KerberosPrincipal principal, byte[ ] keyBytes, int keyType, int versionNum); // Public Instance Methods public final int getKeyType(); public final KerberosPrincipal getPrincipal(); public final int getVersionNumber(); // Methods Implementing Destroyable public void destroy() throws javax.security.auth.DestroyFailedException; public boolean isDestroyed(); // Methods Implementing Key public final String getAlgorithm(); public final byte[ ] getEncoded(); public final String getFormat(); // Public Methods Overriding Object public String toString(); }

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

795

KerberosPrincipal

KerberosPrincipal javax.security.auth.kerberos

Java 1.4 serializable

This class represents a Kerberos principal, specified as a principal name with an optional realm. If no realm is specified in the name, the default realm (from the krb5.conf configuration file or from the java.security.krb5.realm system property) is used. Object

KerberosPrincipal

Principal

Serializable

public final class KerberosPrincipal implements java.security.Principal, Serializable { // Public Constructors public KerberosPrincipal(String name); public KerberosPrincipal(String name, int nameType); // Public Constants public static final int KRB_NT_PRINCIPAL; public static final int KRB_NT_SRV_HST; public static final int KRB_NT_SRV_INST; public static final int KRB_NT_SRV_XHST; public static final int KRB_NT_UID; public static final int KRB_NT_UNKNOWN; // Public Instance Methods public int getNameType(); public String getRealm(); // Methods Implementing Principal public boolean equals(Object other); public String getName(); public int hashCode(); public String toString(); }

=1 =3 =2 =4 =5 =0

Passed To: KerberosKey.KerberosKey(), KerberosTicket.KerberosTicket() Returned By: KerberosKey.getPrincipal(), KerberosTicket.{getClient(), getSer ver()}

KerberosTicket javax.security.auth.kerberos

Java 1.4 serializable

This class represents a Kerberos ticket: a credential used to authenticate a Kerberos principal to some Kerberos-enabled network service. A Kerberos-based javax.security.auth.spi.LoginModule implementation will instantiate a KerberosTicket object and store it in the private credential set of the authenticated Subject it creates. Object Destroyable

KerberosTicket Refreshable

Serializable

public class KerberosTicket implements javax.security.auth.Destroyable, javax.security.auth.Refreshable, Serializable { // Public Constructors public KerberosTicket(byte[ ] asn1Encoding, KerberosPrincipal client, KerberosPrincipal server, byte[ ] sessionKey, int keyType, boolean[ ] flags, java.util.Date authTime, java.util.Date startTime, java.util.Date endTime, java.util.Date renewTill, java.net.InetAddress[ ] clientAddresses); // Property Accessor Methods (by property name) public final java.util.Date getAuthTime(); public final KerberosPrincipal getClient(); public final java.net.InetAddress[ ] getClientAddresses(); public boolean isCurrent(); Implements:Refreshable

796

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

Package javax.security.auth.login

public boolean isDestroyed(); public final byte[ ] getEncoded(); public final java.util.Date getEndTime(); public final boolean[ ] getFlags(); public final boolean isForwardable(); public final boolean isForwarded(); public final boolean isInitial(); public final boolean isPostdated(); public final boolean isProxiable(); public final boolean isProxy(); public final boolean isRenewable(); public final java.util.Date getRenewTill(); public final KerberosPrincipal getSer ver(); public final javax.crypto.SecretKey getSessionKey(); public final int getSessionKeyType(); public final java.util.Date getStartTime(); // Methods Implementing Destroyable public void destroy() throws javax.security.auth.DestroyFailedException; public boolean isDestroyed(); // Methods Implementing Refreshable public boolean isCurrent(); public void refresh() throws javax.security.auth.RefreshFailedException; // Public Methods Overriding Object public String toString(); }

Ser vicePermission

Implements:Destroyable

Java 1.4 serializable permission

javax.security.auth.kerberos

This java.security.Permission class protects access to the Kerberos tickets used to access a specified service. The target name of of a Ser vicePermission is the Kerberos principal name of the service. The action for the Ser vicePermission is either “initiate” for clients or “accept” for servers. Object

Permission

ServicePermission

Guard

Serializable

Serializable

public final class Ser vicePermission extends java.security.Permission implements Serializable { // Public Constructors public Ser vicePermission(String servicePrinicipal, String action); // Public Methods Overriding Permission public boolean equals(Object obj); public String getActions(); public int hashCode(); public boolean implies(java.security.Permission p); public java.security.PermissionCollection newPermissionCollection(); }

Package javax.security.auth.login

Java 1.4

This package defines the LoginContext class which is one of the primary JAAS classes used by application programmers. To authenticate a user, an application creates a LoginContext object, specifying the application name (used to lookup the type of authentication required for that application in the Configuration) and usually specifying a

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

797

Package javax.security.auth.login javax.security.auth.callback.CallbackHandler for communication between the user and the underlying login modules. Next, the application calls the login() method of the LoginContext to perform the actual login. If this method returns without throwing a LoginException, then the user was successfully authenticated, and the getSubject() method of LoginContext returns a javax.security.auth.Subject representing the user. The code might look like this: import javax.security.auth.*; import javax.security.auth.callback.*; import javax.security.auth.login.*; // Get a default GUI-based CallbackHandler CallbackHandler h = new com.sun.security.auth.callback.DialogCallbackHandler(); // Try to create a LoginContext for use with this application LoginContext context; try { context = new LoginContext("MyAppName", h); } catch(LoginException e) { System.err.println("LoginContext configuration error: " + e.getMessage());

System.exit(-1); } // Now use that context to authenticate the user try { context.login(); } catch(LoginException e) { System.err.println("Authentication failed: " + e.getMessage()); System.exit(-1); // Or we could allow them to try again. } // If we get here, authentication was successful, so get the Subject that represents the authenticated user Subject subject = context.getSubject();

In order to make this kind of authentication work correctly, a fair bit of configuration is required in various files in the jre/lib/security directory of the Java installation and possibly elsewhere. In particular, a login configuration file is required to specify which login modules are required to authenticate users for a particular application (some applications may require more than one). A description of how to do this is beyond the scope of this reference. See the Configuration class for a run-time representation of the login configuration information, however. Classes: public class AppConfigurationEntr y; public static class AppConfigurationEntr y.LoginModuleControlFlag; public abstract class Configuration; public class LoginContext; Exceptions: public class LoginException extends java.security.GeneralSecurityException; public class AccountExpiredException extends LoginException;

798

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

AppConfigurationEntry.LoginModuleControlFlag public class CredentialExpiredException extends LoginException; public class FailedLoginException extends LoginException;

AccountExpiredException

Java 1.4 serializable checked

javax.security.auth.login

This exception signals that login failed because the user’s account has expired. Object

Throwable

Exception

GeneralSecurityException

LoginException

AccountExpiredException

Serializable

public class AccountExpiredException extends LoginException { // Public Constructors public AccountExpiredException(); public AccountExpiredException(String msg); }

AppConfigurationEntr y

Java 1.4

javax.security.auth.login An instance of this class represents a login module to be used for user authentication for a particular application. It encapsulates three pieces of information: the class name of the javax.security.auth.spi.LoginModule implementation that is to be used, a “control flag” that specifies whether authentication by that module is required or optional, and a java.util.Map of arbitrary string name/value pairs of options for the login module. public class AppConfigurationEntr y { // Public Constructors public AppConfigurationEntr y(String loginModuleName, AppConfigurationEntry.LoginModuleControlFlag controlFlag, java.util.Map options); // Inner Classes public static class LoginModuleControlFlag; // Public Instance Methods public AppConfigurationEntry.LoginModuleControlFlag getControlFlag(); public String getLoginModuleName(); public java.util.Map getOptions(); } Returned By: Configuration.getAppConfigurationEntr y()

AppConfigurationEntr y.LoginModuleControlFlag

Java 1.4

javax.security.auth.login This inner class defines a “control flag” type and four specific instances of that type. The following constants defined by this class specify whether a login module is required or optional: REQUIRED Authentication by this module must be successful, or the overall login process will fail. However, even if authentication fails for this module, the LoginContext continues to attempt authentication with any other modules in the list. (This can disguise the source of the authentication failure from an attacker.)

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

799

AppConfigurationEntry.LoginModuleControlFlag REQUISITE Authentication by this module must be successful, or the overall login process will fail. If authentication fails for this module, the LoginContext does not try any further login modules. SUFFICIENT Authentication by this module is not required, and the overall login process can still succeed if all REQUIRED and REQUISITE modules successfully authenticate the user. However, if authentication by this module does succeed, the LoginContext does not try any further login modules, but instead returns immediately. OPTIONAL Authentication by this module is not required. Whether or not it succeeds, the LoginContext continues to with any other modules on the list. public static class AppConfigurationEntr y.LoginModuleControlFlag { // No Constructor // Public Constants public static final AppConfigurationEntry.LoginModuleControlFlag OPTIONAL; public static final AppConfigurationEntry.LoginModuleControlFlag REQUIRED; public static final AppConfigurationEntry.LoginModuleControlFlag REQUISITE; public static final AppConfigurationEntry.LoginModuleControlFlag SUFFICIENT; // Public Methods Overriding Object public String toString(); } Passed To: AppConfigurationEntr y.AppConfigurationEntr y() Returned By: AppConfigurationEntr y.getControlFlag() Type Of: AppConfigurationEntr y.LoginModuleControlFlag.{OPTIONAL, REQUIRED, REQUISITE, SUFFICIENT}

Configuration

Java 1.4

javax.security.auth.login This abstract class is a representation of the system and user login configuration files. The static getConfiguration() method returns the global Configuration object, and the static setConfiguration() allows that global object to be replaced with some other implementation. The instance method refresh() causes a Configuration to re-read the underlying configuration files. getAppConfigurationEntr y() is the key method: it returns an array of AppConfigurationEntr y objects that represent the set of login modules to be used for applications with the specified name. LoginContext uses this class to determine which login modules to use to authenticate a user of the named application. Application programmers do not typically need to use this class themselves. See the documentation for your Java implementation for the syntax of the underlying login configuration files. public abstract class Configuration { // Protected Constructors protected Configuration(); // Public Class Methods public static Configuration getConfiguration(); public static void setConfiguration(Configuration configuration); // Public Instance Methods public abstract AppConfigurationEntry[ ] getAppConfigurationEntr y(String applicationName); public abstract void refresh(); }

800

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

synchronized

LoginContext Passed To: Configuration.setConfiguration() Returned By: Configuration.getConfiguration()

CredentialExpiredException

Java 1.4 serializable checked

javax.security.auth.login

This signals that a login failed because a credential (such as a password) has expired and is no longer valid. Object

Throwable

Exception

GeneralSecurityException

LoginException

CredentialExpiredException

Serializable

public class CredentialExpiredException extends LoginException { // Public Constructors public CredentialExpiredException(); public CredentialExpiredException(String msg); }

FailedLoginException

Java 1.4 serializable checked

javax.security.auth.login

This signals that login failed. Typically this is because an incorrect username, password, or other information was presented. Login modules that throw this exception may provide human-readable details through the getMessage() method. Object

Throwable

Exception

GeneralSecurityException

LoginException

FailedLoginException

Serializable

public class FailedLoginException extends LoginException { // Public Constructors public FailedLoginException(); public FailedLoginException(String msg); }

LoginContext

Java 1.4

javax.security.auth.login This is one of the most important classes in the JAAS API for application programmers: it defines the login() method (and the corresponding logout() method) that allows an application to authenticate a user. Create a LoginContext object using one of the four public constructors. The constructor expects to be passed the name of the application, and, optionally, the javax.security.auth.Subject that is to be authenticated and a javax.security.auth.callback.CallbackHandler that is to be used for communication between the underlying login module (or modules) and the user. If no Subject is specified, then the LoginContext will instantiate a new one to represent the authenticated user. If a Subject is supplied, then the LoginContext adds new entries to its sets of principals and credentials. If no CallbackHandler is specified, then the LoginContext attempts to instantiate one using the class name specified by the auth.login.defaultCallbackHandler property in the system’s security properties file. Once a LoginContext is successfully created, you can authenticate a user simply by calling the login() method, and then calling getSubject() to obtain the Subject object that represents the authenticated user. When this Subject is no longer required, you can log them out by calling the logout() method.

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

801

LoginContext

public class LoginContext { // Public Constructors public LoginContext(String name) throws LoginException; public LoginContext(String name, javax.security.auth.Subject subject) throws LoginException; public LoginContext(String name, javax.security.auth.callback.CallbackHandler callbackHandler) throws LoginException; public LoginContext(String name, javax.security.auth.Subject subject, javax.security.auth.callback.CallbackHandler callbackHandler) throws LoginException; // Public Instance Methods public javax.security.auth.Subject getSubject(); public void login() throws LoginException; public void logout() throws LoginException; }

LoginException

Java 1.4 serializable checked

javax.security.auth.login

This signals that something went wrong while creating a LoginContext or during the login or logout process. The subclasses of this class represent more specific exception types. Object

Throwable

Exception

GeneralSecurityException

LoginException

Serializable

public class LoginException extends java.security.GeneralSecurityException { // Public Constructors public LoginException(); public LoginException(String msg); } Subclasses: AccountExpiredException, CredentialExpiredException, FailedLoginException Thrown By: LoginContext.{login(), LoginContext(), logout()}, javax.security.auth.spi.LoginModule.{abort(), commit(), login(), logout()}

Package javax.security.auth.spi

Java 1.4

This package defines the “service provider interface” for JAAS: it defines a single LoginModule interface that must be implemented by developers of login modules. Interface: public interface LoginModule;

LoginModule

Java 1.4

javax.security.auth.spi Developers of login modules to be used with the JAAS authentication API must implement this interface. Because this interface is not typically used by application developers, its methods are not documented here. public interface LoginModule { // Public Instance Methods public abstract boolean abort() throws javax.security.auth.login.LoginException; public abstract boolean commit() throws javax.security.auth.login.LoginException; public abstract void initialize(javax.security.auth.Subject subject, javax.security.auth.callback.CallbackHandler callbackHandler, java.util.Map sharedState, java.util.Map options);

802

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

X500Principal

public abstract boolean login() throws javax.security.auth.login.LoginException; public abstract boolean logout() throws javax.security.auth.login.LoginException; }

Package javax.security.auth.x500

Java 1.4

This package defines classes for use with authentication schemes for on X.500 principals. Instances of these classes are designed to be stored in the principals and private credentials sets of Subject objects, and although application programmers may occasionally find the X500Principal class useful, they are primarily of interest to system-level programmers writing X.500-based javax.security.auth.spi.LoginModule implementations See also the java.security.cert package which contains a class representing an X.509 certificate. Classes: public final class X500Principal implements java.security.Principal, Serializable; public final class X500PrivateCredential implements javax.security.auth.Destroyable;

X500Principal

Java 1.4 serializable

javax.security.auth.x500

This class implements the java.security.Principal interface for entities represented by X.500 distinguished names (such as “CN=David,O=davidflanagan.com,C=US”). The constructor methods can accept the distinguished name in string form or in binary encoded form. getName() returns the name in string form, using the format defined by one of the three constant values. The no-argument version of getName() (the one defined by the Principal interface) returns the distinguished name formatted as specified by RFC 2253. Finally, getEncoded() returns a binary-encoded form of the name. Object

X500Principal

Principal

Serializable

public final class X500Principal implements java.security.Principal, Serializable { // Public Constructors public X500Principal(java.io.InputStream is); public X500Principal(String name); public X500Principal(byte[ ] name); // Public Constants public static final String CANONICAL; public static final String RFC1779; public static final String RFC2253; // Public Instance Methods public byte[ ] getEncoded(); public String getName(String format); // Methods Implementing Principal public boolean equals(Object o); public String getName(); public int hashCode(); public String toString(); }

= [quot ] CANONICAL [quot ] = [quot ] RFC1779 [quot ] = [quot ] RFC2253 [quot ]

Returned By: java.security.cert.X509Certificate.{getIssuerX500Principal(), getSubjectX500Principal()}, java.security.cert.X509CRL.getIssuerX500Principal()

Chapter 20 – javax.security.auth and Subpackages

7 March 2002 11:39

803

X500PrivateCredential

X500PrivateCredential

Java 1.4

javax.security.auth.x500 This class associates a java.security.cert.X509Certificate with a java.security.PrivateKey for that certificate, and, optionally, the keystore alias used to retrieve the certificate and key from a java.security.KeyStore. The class defines methods to retrieve the certificate, key, and alias, and implements the methods of the javax.security.cert.Destroyable interface. Object

X500PrivateCredential

Destroyable

public final class X500PrivateCredential implements javax.security.auth.Destroyable { // Public Constructors public X500PrivateCredential(java.security.cert.X509Certificate cert, java.security.PrivateKey key); public X500PrivateCredential(java.security.cert.X509Certificate cert, java.security.PrivateKey key, String alias); // Public Instance Methods public String getAlias(); public java.security.cert.X509Certificate getCertificate(); public java.security.PrivateKey getPrivateKey(); // Methods Implementing Destroyable public void destroy(); public boolean isDestroyed(); }

804

7 March 2002 11:39

Chapter 20 – javax.security.auth and Subpackages

CHAPTER 21

javax.xml.parsers, java.xml.transform, and Subpackages

This chapter documents the javax.xml.parsers package and the javax.xml.transform package and its subpackages. These packages comprise the Java API for XML Processing, or JAXP. Before being integrated in Java 1.4, JAXP was available as a standard extension, which explains the “javax” prefix in the package names. The packages in this chapter are: javax.xml.parsers This package defines parser classes that serve as a wrapper around underlying DOM and SAX XML parsers, and also defines factory classes that are used to obtain instances of those parser classes. javax.xml.transform This package defines classes and interfaces for transforming the representation and content of an XML document with XSLT. It defines Source and Result interfaces to represent a source document and a result document. Sub-packages provide implementations of these classes that represent documents in different ways. javax.xml.transform.dom This package implements the Source and Result interfaces that represent documents as DOM document trees. javax.xml.transform.sax This package implements the Source and Result interfaces to represent documents as sequences of SAX parser events. It also defines other SAX-related transformation classes. javax.xml.transform.stream This package implements the Source and Result interfaces that represent documents as streams of text.

Package javax.xml.parsers

Java 1.4

This package defines classes that represent XML parsers and factory classes for obtaining instances of those parser classes. DocumentBuilder is a DOM-based XML parser

805

7 March 2002 11:40

Package javax.xml.parsers created from a DocumentBuilderFactor y. SAXParser is a SAX-based XML parser created from a SAXParserFactor y. Note that this package does not include parser implementations. Instead, it is an implementation-independent layer that supports “pluggable” XML parsers. Furthermore, this package does not define a DOM or SAX API for working with XML documents. The DOM API is defined in org.w3c.dom, and the SAX API is defined in org.xml.sax and its subpackages. Classes: public abstract class DocumentBuilder; public abstract class DocumentBuilderFactor y; public abstract class SAXParser ; public abstract class SAXParserFactor y; Exception: public class ParserConfigurationException extends Exception; Errors: public class Factor yConfigurationError extends Error;

DocumentBuilder

Java 1.4

javax.xml.parsers This class defines a high-level API to an underlying DOM parser implementation. Obtain a DocumentBuilder from a DocumentBuilderFactor y. After obtaining a DocumentBuilder, you can provide org.xml.sax.ErrorHandler and org.xml.sax.EntityResolver objects, if desired. (These classes are defined by the SAX API but are useful for DOM parsers as well.) You may also want to call isNamespaceAware() and isValidating() to ensure that the parser is configured with the features your application requires. Finally, use one of the parse() methods to read an XML document from a stream, file, URL, or org.xml.sax.InputSource object, parse that document, and convert it into a org.w3c.dom.Document tree. Note that DocumentBuilder objects are not typically thread-safe. If you want to obtain an empty Document object (so that you can build the document tree from scratch, for example) call newDocument(). Or use getDOMImplementation() to obtain the org.w3c.dom.DOMImplementation object of the underlying DOM implementation from which you can also create an empty Document. See the org.w3c.dom package for information on what you can do with a Document object once you have used a DocumentBuilder to create it. public abstract class DocumentBuilder { // Protected Constructors protected DocumentBuilder(); // Property Accessor Methods (by property name) public abstract org.w3c.dom.DOMImplementation getDOMImplementation(); public abstract boolean isNamespaceAware(); public abstract boolean isValidating(); // Public Instance Methods public abstract org.w3c.dom.Document newDocument(); public abstract org.w3c.dom.Document parse(org.xml.sax.InputSource is) throws org.xml.sax.SAXException, java.io.IOException; public org.w3c.dom.Document parse(java.io.InputStream is) throws org.xml.sax.SAXException, java.io.IOException; public org.w3c.dom.Document parse(String uri) throws org.xml.sax.SAXException, java.io.IOException; public org.w3c.dom.Document parse(java.io.File f) throws org.xml.sax.SAXException, java.io.IOException; public org.w3c.dom.Document parse(java.io.InputStream is, String systemId) throws org.xml.sax.SAXException, java.io.IOException;

806

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

DocumentBuilderFactory

public abstract void setEntityResolver(org.xml.sax.EntityResolver er); public abstract void setErrorHandler(org.xml.sax.ErrorHandler eh); } Returned By: DocumentBuilderFactor y.newDocumentBuilder()

DocumentBuilderFactor y

Java 1.4

javax.xml.parsers A DocumentBuilderFactor y is a factory class for creating DocumentBuilder objects. You can obtain a DocumentBuilderFactor y by instantiating an implementation-specific subclass provided by a parser vendor, but it is much more common to simply call newInstance() to obtain an instance of the factory that has been configured as the default for the system. Once you have obtained a factory object, you can use the various set methods to configure the properties of the DocumentBuilder objects it will create. These methods allow you to specify whether the parsers created by the factory will: •

Coalesce CDATA sections with adjacent text nodes



Expand entity references or leave them unexpanded in the document tree



Omit XML comments from the document tree



Omit ignorable whitespace from the document tree



Handle XML namespaces correctly



Validate XML documents against a DTD or other schema

In addition to the various implementation-independent set methods, you can also use setAttribute() pass an implementation-dependent named attribute to the underlying parser implementation. Once you have configured the factory object as desired, simply call newDocumentBuilder() to create a DocumentBuilder object with the all of the attributes you have specified. Note that DocumentBuilderFactor y objects are not typically thread-safe. The javax.xml.parsers package allows parser implementations to be “plugged in.” This plugability is provided by the newInstance() method, which follows the following steps to determine which DocumentBuilderFactor y implementation to use: •

If the javax.xml.parsers.DocumentBuilderFactor y system property is defined, then the class specified by that property is used.



Otherwise, if the jr e/lib/jaxp.properties file exists in the Java distribution and contains a definition for the javax.xml.parsers.DocumentBuilderFactor y property, then the class specified by that property is used.



Otherwise, if any of the JAR files on the classpath includes a file named META-INF/ services/javax.xml.parsers.DocumentBuilderFactory, then the class named in that file is used.



Otherwise, a default implementation provided by the Java implementation is used.

public abstract class DocumentBuilderFactor y { // Protected Constructors protected DocumentBuilderFactor y(); // Public Class Methods public static DocumentBuilderFactory newInstance() throws FactoryConfigurationError; // Property Accessor Methods (by property name) public boolean isCoalescing();

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

807

DocumentBuilderFactory

public void setCoalescing(boolean coalescing); public boolean isExpandEntityReferences(); public void setExpandEntityReferences(boolean expandEntityRef); public boolean isIgnoringComments(); public void setIgnoringComments(boolean ignoreComments); public boolean isIgnoringElementContentWhitespace(); public void setIgnoringElementContentWhitespace(boolean whitespace); public boolean isNamespaceAware(); public void setNamespaceAware(boolean awareness); public boolean isValidating(); public void setValidating(boolean validating); // Public Instance Methods public abstract Object getAttribute(String name) throws IllegalArgumentException; public abstract DocumentBuilder newDocumentBuilder() throws ParserConfigurationException; public abstract void setAttribute(String name, Object value) throws IllegalArgumentException; } Returned By: DocumentBuilderFactor y.newInstance()

Factor yConfigurationError javax.xml.parsers

Java 1.4 serializable error

This signals a nonrecoverable problem instantiating a parser factory. This usually means that a pluggable parser implementation has been incorrectly plugged in and the newInstance() method cannot locate the specified factory implementation class. Object

Throwable

Error

FactoryConfigurationError

Serializable

public class Factor yConfigurationError extends Error { // Public Constructors public Factor yConfigurationError(); public Factor yConfigurationError(Exception e); public Factor yConfigurationError(String msg); public Factor yConfigurationError(Exception e, String msg); // Public Instance Methods public Exception getException(); // Public Methods Overriding Throwable public String getMessage(); }

default:null default:null

Thrown By: DocumentBuilderFactor y.newInstance(), SAXParserFactor y.newInstance()

ParserConfigurationException javax.xml.parsers

Java 1.4 serializable checked

This exception signals a parser configuration problem that prevents a parser factory object from creating a parser object. Object

Throwable

Exception

ParserConfigurationException

Serializable

public class ParserConfigurationException extends Exception { // Public Constructors public ParserConfigurationException();

808

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

SAXParser

public ParserConfigurationException(String msg); } Thrown By: DocumentBuilderFactor y.newDocumentBuilder(), SAXParserFactor y.{getFeature(), newSAXParser(), setFeature()}

SAXParser

Java 1.4

javax.xml.parsers The SAXParser class is a wrapper around an org.xml.sax.XMLReader class and is used to parse XML documents using the SAX version 2 API. Obtain a SAXParser from a SAXParserFactor y. Call setProperty() if desired to set a property on the underlying parser. (See http://www.saxproject.org for a description of standard SAX properties and their values.) Finally, call one of the parse() methods to parse an XML document from a stream, file, URL, or org.xml.sax.InputSource. The SAX API is an event-driven one. A SAX parser does not build a document tree to describe an XML document like a DOM parser does. Instead, it describes the XML document to your application by invoking methods on an object the application provides. This is the purpose of the org.xml.sax.helpers.DefaultHandler object that is passed to the parse() method: you subclass this class to implement the methods you care about, and the parser will invoke those methods at appropriate times. For example, when the parser encounters an XML tag in a document, it parses the tag, and calls the startElement() method to tell you about it. And when it finds a run of plain text, it passes that text to the characters() method. Instead of using one of the parse() methods of this class, you can also call getXMLReader() to obtain the underlying XMLReader object and work with it directly to parse the desired document. SAXParser objects are not typically thread-safe. Note that the getParser() method as well as the parse() methods that take an org.xml.sax.HandlerBase object are based on the SAX version 1 API and should be avoided. public abstract class SAXParser { // Protected Constructors protected SAXParser(); // Property Accessor Methods (by property name) public abstract boolean isNamespaceAware(); public abstract org.xml.sax.Parser getParser() throws org.xml.sax.SAXException; public abstract boolean isValidating(); public abstract org.xml.sax.XMLReader getXMLReader() throws org.xml.sax.SAXException; // Public Instance Methods public abstract Object getProperty(String name) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void parse(java.io.File f, org.xml.sax.helpers.DefaultHandler dh) throws org.xml.sax.SAXException, java.io.IOException; public void parse(org.xml.sax.InputSource is, org.xml.sax.HandlerBase hb) throws org.xml.sax.SAXException, java.io.IOException; public void parse(org.xml.sax.InputSource is, org.xml.sax.helpers.DefaultHandler dh) throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.InputStream is, org.xml.sax.helpers.DefaultHandler dh) throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.InputStream is, org.xml.sax.HandlerBase hb) throws org.xml.sax.SAXException, java.io.IOException; public void parse(String uri, org.xml.sax.HandlerBase hb) throws org.xml.sax.SAXException, java.io.IOException; public void parse(String uri, org.xml.sax.helpers.DefaultHandler dh) throws org.xml.sax.SAXException, java.io.IOException;

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

809

SAXParser

public void parse(java.io.File f, org.xml.sax.HandlerBase hb) throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.InputStream is, org.xml.sax.HandlerBase hb, String systemId) throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.InputStream is, org.xml.sax.helpers.DefaultHandler dh, String systemId) throws org.xml.sax.SAXException, java.io.IOException; public abstract void setProperty(String name, Object value) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; } Returned By: SAXParserFactor y.newSAXParser()

SAXParserFactor y

Java 1.4

javax.xml.parsers This class is a factory for SAXParser objects. Obtain a SAXParserFactor y by calling the newInstance() method which instantiates the default SAXParserFactor y subclass provided with your Java implementation, or instantiates some other SAXParserFactor y that has been “plugged in.” Once you have a SAXParserFactor y object, you can use setValidating() and setNamespaceAware() to specify whether the parsers it creates will be validating parsers or not and whether they will know how to handle XML namespaces. You may also call setFeature() to set a feature of the underlying parser implementation. See http://www.saxproject.org for the names of standard parser features that can be enabled and disabled with this method. Once you have created and configured your factory object, simply call newSAXParser() to create a SAXParser object. Note that SAXParserFactor y implementations are not typically thread-safe. The javax.xml.parsers package allows parser implementations to be “plugged in.” This plugability is provided by the newInstance() method, which follows the following steps to determine which SAXParserFactor y subclass to use: •

If the javax.xml.parsers.SAXParserFactor y system property is defined, then the class specified by that property is used.



Otherwise, if the jr e/lib/jaxp.properties file exists in the Java distribution and contains a definition for the javax.xml.parsers.SAXParserFactor y property, then the class specified by that property is used.



Otherwise, if any of the JAR files on the classpath includes a file named META-INF/ services/javax.xml.parsers.SAXParserFactory, then the class named in that file is used.



Otherwise, a default implementation provided by the Java platform is used.

public abstract class SAXParserFactor y { // Protected Constructors protected SAXParserFactor y(); // Public Class Methods public static SAXParserFactory newInstance() throws FactoryConfigurationError; // Public Instance Methods public abstract boolean getFeature(String name) throws ParserConfigurationException, org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public boolean isNamespaceAware(); public boolean isValidating(); public abstract SAXParser newSAXParser() throws ParserConfigurationException, org.xml.sax.SAXException;

810

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

Package javax.xml.transform

public abstract void setFeature(String name, boolean value) throws ParserConfigurationException, org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void setNamespaceAware(boolean awareness); public void setValidating(boolean validating); } Returned By: SAXParserFactor y.newInstance()

Package javax.xml.transform

Java 1.4

This package defines a high-level, implementation-independent API for using an XSLT engine or other document transformation system for transforming XML document content, and also for transforming XML documents from one form (such as a stream of text in a file) to anther form (such as a tree of DOM nodes). The Source interface is a very generic description of a document source. Three concrete implementations that represent documents in text form, as DOM trees, and as sequences of SAX parser events are defined in the three sub-packages of this package. The Result interface is a similarly high-level description of what form the source document should be transformed into. The three sub-packages define three Result implementations that represent XML documents as streams or files, as DOM trees, and as sequences of SAX parser events. The TransformerFactor y class represents the document transformation engine. The implementation provides a default factory that represents an XSLT engine. A TransformerFactor y can be used to produce Templates objects that represent compiled XSL stylesheets (or other implementation-dependent forms of transformation instructions). Documents are actually transformed from Source to Result with a Transformer object, which is obtained from a Templates object, or directly from a TransformerFactor y. Interfaces: public interface ErrorListener; public interface Result; public interface Source; public interface SourceLocator ; public interface Templates; public interface URIResolver; Classes: public class OutputKeys; public abstract class Transformer; public abstract class TransformerFactor y; Exceptions: public class TransformerException extends Exception; public class TransformerConfigurationException extends TransformerException; Errors: public class TransformerFactor yConfigurationError extends Error;

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

811

ErrorListener

ErrorListener

Java 1.4

javax.xml.transform This interface defines methods that Transformer and TransformerFactor y use for reporting warnings, errors, and fatal errors to an application. To use an ErrorListener, an application must implement this interface and pass an implementing object to the setErrorListener() method of Transformer or TransformerFactor y. The argument to each method of this interface is a TransformerException object, and the implementation of these methods can throw that exception if it chooses, or it can simply log the warning or error in some way and return. A Transformer or TransformerFactor y is not required to continue processing after reporting a non-recoverable error with an invocation of the fatalError() method. If you are familiar with the SAX API for parsing XML documents, you’ll recognize that this interface is very similar to org.xml.sax.ErrorHandler. public interface ErrorListener { // Public Instance Methods public abstract void error(TransformerException exception) throws TransformerException; public abstract void fatalError(TransformerException exception) throws TransformerException; public abstract void warning(TransformerException exception) throws TransformerException; } Passed To: Transformer.setErrorListener(), TransformerFactor y.setErrorListener() Returned By: Transformer.getErrorListener(), TransformerFactor y.getErrorListener()

OutputKeys

Java 1.4

javax.xml.transform This class defines string constants that hold the names of the attributes of an tag in an XSLT stylesheet. These are also legal key values for the Properties object returned by Templates.getOutputProperties() and passed to Transformer.setOutputProperties(). public class OutputKeys { // No Constructor // Public Constants public static final String CDATA_SECTION_ELEMENTS; public static final String DOCTYPE_PUBLIC; public static final String DOCTYPE_SYSTEM; public static final String ENCODING; public static final String INDENT; public static final String MEDIA_TYPE; public static final String METHOD; public static final String OMIT_XML_DECLARATION; public static final String STANDALONE; public static final String VERSION; }

Result

= [quot ] cdata-section-elements [quot = [quot ] doctype-public [quot = [quot ] doctype-system [quot = [quot ] encoding [quot = [quot ] indent [quot = [quot ] media-type [quot = [quot ] method [quot = [quot ] omit-xml-declaration [quot = [quot ] standalone [quot = [quot ] version [quot

] ] ] ] ] ] ] ] ] ]

Java 1.4

javax.xml.transform This interface represents, in a very general way, the result of an XML transformation. setSystemId() specifies the system identifier of the result as a URL. This is useful when the result is to be written as a file, but it can also be useful for error reporting and for resolution of relative URLs even when the Result object does not represent a file. All other methods related to the result are the responsibility of the concrete implementation of this interface. See the DOMResult, SAXResult and StreamResult implementations in the three subpackages of this package.

812

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

SourceLocator

public interface Result { // Public Constants public static final String = [quot ] javax.xml.transform.disable-output-escaping [quot ] PI_DISABLE_OUTPUT_ESCAPING; public static final String = [quot ] javax.xml.transform.enable-output-escaping [quot ] PI_ENABLE_OUTPUT_ESCAPING; // Public Instance Methods public abstract String getSystemId(); public abstract void setSystemId(String systemId); } Implementations: javax.xml.transform.dom.DOMResult, javax.xml.transform.sax.SAXResult, javax.xml.transform.stream.StreamResult Passed To: Transformer.transform(), javax.xml.transform.sax.TransformerHandler.setResult()

Source

Java 1.4

javax.xml.transform This interface represents, in a very general way, the source of an XML document. setSystemId() specifies the system identifier of the document in the form of a URL. This is useful for resolving relative URLs and for error reporting even when the document is not read directly from a URL. All other methods related to the document source are the responsibility of the concrete implementation of this interface. See the DOMSource, SAXSource and StreamSource implementations in the three sub-packages of this package. public interface Source { // Public Instance Methods public abstract String getSystemId(); public abstract void setSystemId(String systemId); } Implementations: javax.xml.transform.dom.DOMSource, javax.xml.transform.sax.SAXSource, javax.xml.transform.stream.StreamSource Passed To: Transformer.transform(), TransformerFactor y.{getAssociatedStylesheet(), newTemplates(), newTransformer()}, javax.xml.transform.sax.SAXSource.sourceToInputSource(), javax.xml.transform.sax.SAXTransformerFactor y.{newTransformerHandler(), newXMLFilter()} Returned By: TransformerFactor y.getAssociatedStylesheet(), URIResolver.resolve()

SourceLocator

Java 1.4

javax.xml.transform This interface defines methods that return the system and public identifiers of an XML document, and return a line number and column number within that document. SourceLocator objects are used with TransformerException and TransformerConfigurationException objects to specify the location in an XML file at which the exception occurred. Note, however that system and public identifiers are not always available for a document, and so getSystemId() and getPublicId() may return null. Also, a Transformer is not required to track line and column numbers precisely, or at all, so getLineNumber() and getColumnNumber() may return –1 to indicate that line and column number information is not available. If they return a value other than –1, it should be considered an approximation to the actual value. Note that lines and columns within a document are numbered starting with 1, not with 0. If you are familiar with the SAX API for parsing XML, you’ll recognize this interface as a renamed version of org.xml.sax.Locator.

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

813

SourceLocator

public interface SourceLocator { // Public Instance Methods public abstract int getColumnNumber(); public abstract int getLineNumber(); public abstract String getPublicId(); public abstract String getSystemId(); } Implementations: javax.xml.transform.dom.DOMLocator Passed To: TransformerConfigurationException.TransformerConfigurationException(), TransformerException.{setLocator(), TransformerException()} Returned By: TransformerException.getLocator()

Templates

Java 1.4

javax.xml.transform This interface represents a set of transformation instructions for transforming a Source document into a Result document. The javax.xml.transform package is theoretically independent of type of transformation, but in practice, an object of this type always represents the compiled form of an XSLT stylesheet. Obtain a Templates object from a TransformerFactor y object, or with a javax.xml.transform.sax.TemplatesHandler. Once you have a Templates object, you can use the newTransformer() method to create a Transformer object for applying the templates to a Source to produce a Result document. getOutputProperties() returns a java.util.Properties object that defines name/value pairs specifying details about how a textual version of the Result document should be produced. These properties are specified in an XSLT stylesheet with the element. The constants defined by the OutputKeys are legal output property names. The returned Properties object contains explicitly properties directly, and contains default values in a parent Properties object. This means that if you query a property value with getProperty(), you’ll get an explicitly specified value of a default value. On the other hand, if you query a property with the get() method (inherited by Properties from its superclass) you’ll get a property value if it was explictly specified in the stylesheet, or null if it was not specified. The returned Properties object is a clone of the internal value, so you can modify it (before passing it to the setOutputProperties() method of a Transformer object, for example) without affecting the Templates object. Templates implementations are required to be thread-safe. A Templates object can be used to create any number of Transformer objects. public interface Templates { // Public Instance Methods public abstract java.util.Properties getOutputProperties(); public abstract Transformer newTransformer() throws TransformerConfigurationException; } Passed To: javax.xml.transform.sax.SAXTransformerFactor y.{newTransformerHandler(), newXMLFilter()} Returned By: TransformerFactor y.newTemplates(), javax.xml.transform.sax.TemplatesHandler.getTemplates()

Transformer

Java 1.4

javax.xml.transform Objects of this type are used to transform a Source document into a Result document. Obtain a Transformer object from a TransformerFactor y object, from a Templates object cre-

814

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

TransformerConfigurationException ated by a TransformerFactor y, or from a TransformerHandler object created by a SAXTransformerFactor y (these last two types are from the javax.xml.transform.sax package). Once you have a Transformer object, you may need to configure it before using it to transform documents. setErrorListener() and setURIResolver() allow you to specify ErrorListener and URLResolver object that the Transformer can use. setOutputProperty() and setOutputProperties() allow you to specify name/value pairs that affect the text formatting of the Result document (if that document is written out in text format). OutputKeys defines constants that represent the set of standard output property names. The output properties you specify with these methods override any output properties specified (with an tag) in the Templates object. Use setParameter() to supply values for any toplevel parameters defined (with tags) in the stylesheet. Note that if the name of any such parameter is a qualified name, then it appears in the stylesheet with a namespace prefix. You can’t use the prefix with the setParameter() method, however, and you must instead specify the parameter name using the URI of the namespace within curly braces followed by the local name. If no namespace is involved, then you can just use the simple name of the parameter with no curly braces or URIs. Once you have created and configured a Transformer object, use the transform() method to perform a document transformation. This method transforms the specified Source document and creates the transformed document specified by the Result object. Transformer implementations are not typically thread-safe. You can reuse a Transformer object and call transform() any number of times (just not concurrently). The output properties and parameters you specify are not changed by calling the transform() method and can be reused. public abstract class Transformer { // Protected Constructors protected Transformer(); // Property Accessor Methods (by property name) public abstract ErrorListener getErrorListener(); public abstract void setErrorListener(ErrorListener listener) throws IllegalArgumentException; public abstract java.util.Properties getOutputProperties(); public abstract void setOutputProperties(java.util.Properties oformat) throws IllegalArgumentException; public abstract URIResolver getURIResolver(); public abstract void setURIResolver(URIResolver resolver); // Public Instance Methods public abstract void clearParameters(); public abstract String getOutputProperty(String name) throws IllegalArgumentException; public abstract Object getParameter(String name); public abstract void setOutputProperty(String name, String value) throws IllegalArgumentException; public abstract void setParameter(String name, Object value); public abstract void transform(Source xmlSource, Result outputTarget) throws TransformerException; } Returned By: Templates.newTransformer(), TransformerFactor y.newTransformer(), javax.xml.transform.sax.TransformerHandler.getTransformer()

TransformerConfigurationException javax.xml.transform

Java 1.4 serializable checked

This exception signals a problem creating a Transformer object. This may occur, for example, if there is a syntax error in the XSL stylesheet that contains the transformation

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

815

TransformerConfigurationException instructions. Use the inherited getLocator() method to obtain a SourceLocator that describes the document location at which the exception occurred. Object

Throwable

Exception

TransformerException

TransformerConfigurationException

Serializable

public class TransformerConfigurationException extends TransformerException { // Public Constructors public TransformerConfigurationException(); public TransformerConfigurationException(Throwable e); public TransformerConfigurationException(String msg); public TransformerConfigurationException(String message, SourceLocator locator); public TransformerConfigurationException(String msg, Throwable e); public TransformerConfigurationException(String message, SourceLocator locator, Throwable e); } Thrown By: Templates.newTransformer(), TransformerFactor y.{getAssociatedStylesheet(), newTemplates(), newTransformer()}, javax.xml.transform.sax.SAXTransformerFactor y.{newTemplatesHandler(), newTransformerHandler(), newXMLFilter()}

TransformerException

Java 1.4 serializable checked

javax.xml.transform

This exception signals a problem while reading or transforming a document. Call getLocator() to obtain a SourceLocator object that describes the document location where the exception occurred. Object

Throwable

Exception

TransformerException

Serializable

public class TransformerException extends Exception { // Public Constructors public TransformerException(String message); public TransformerException(Throwable e); public TransformerException(String message, Throwable e); public TransformerException(String message, SourceLocator locator); public TransformerException(String message, SourceLocator locator, Throwable e); // Public Instance Methods public Throwable getException(); public String getLocationAsString(); public SourceLocator getLocator(); public String getMessageAndLocation(); public void setLocator(SourceLocator location); // Public Methods Overriding Throwable public Throwable getCause(); public Throwable initCause(Throwable cause); public void printStackTrace(); public void printStackTrace(java.io.PrintStream s); public void printStackTrace(java.io.PrintWriter s); }

synchronized

Subclasses: TransformerConfigurationException Passed To: ErrorListener.{error(), fatalError(), warning()}

816

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

TransformerFactory Thrown By: ErrorListener.{error(), fatalError(), warning()}, Transformer.transform(), URIResolver.resolve()

TransformerFactor y

Java 1.4

javax.xml.transform An instance of this abstract class represents a document “transformation engine” such as an XSLT processor. A TransformerFactor y is used to create Transformer objects that perform document transformations, and can also be used to process transformation instructions (such as XSLT stylesheets) into compiled Templates objects. Obtain a TransformerFactor y instance by calling the static newInstance() method. newInstance() returns an instance of the default implementation for your Java installation, or, if the system property javax.xml.transform.TransformerFactor y is set, then it returns an instance of the implementation class named by that property. The default TransformerFactor y implementation provided with the Java distribution transforms XML documents using XSL stylesheets. You can configure a TransformerFactor y instance by calling setErrorListener() and setURIResolver() to specify an ErrorListener object and a URIResolver object to be used by the factory when reading and parsing XSL stylesheets. The setAttribute() and getAttribute() methods can be used to set and query implementation-dependent attributes of the transformation engine. The default engine supplied by Sun does not define any attributes. The getFeature() method is used to test whether the factory supports a given feature. For uniqueness, feature names are expressed as URIs, and each of the Source and Result implementations defined in the three subpackages of this package define a FEATURE constant that specifies a URL that you can use to test whether a TransformerFactor y supports that particular Source or Result type. Once you have obtained and configured your TransformerFactor y object, you can use it in several ways. If you call the newTransformer() method that takes no arguments, you’ll obtain a Transformer object that transforms the format or representation of an XML document without transforming its content. For example, you could use a Transformer created in this way to transform a DOM tree (represented by a javax.xml.transform.dom.DOMSource object) to a stream of XML text stored in a file named by a javax.xml.transform.stream.StreamResult. Another way to use a TransformerFactor y is to call the newTemplates() method, passing in a Source object that represents an XSL stylesheet. This produces a Templates object, which you can use to obtain a Transformer object that applies the stylesheet to transform document content. Alternatively, if you do not plan to create more than one Transformer object from the Templates object, you can combine the two steps and simply pass the Source object representing the stylesheet to the one-argument version of newTransformer(). XML documents may include references to XSL stylesheets in the form of an xmlstylesheet processing instruction. The getAssociatedStylesheet() method reads the XML document represented by a Source object and returns a new Source object that represents the stylesheet (or the concatenation of all the stylesheets) contained in that document that match the media, title, and charset constraints defined by the other three parameters (which may be null). If you want to process an XML document using the stylesheet that it defines itself, use this method to obtain a Source object that you can pass to newTransformer() to create the Transformer object that you can use to transform the document. Typically, TransformerFactor y implementations are not thread-safe. public abstract class TransformerFactor y { // Protected Constructors

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

817

TransformerFactory

protected TransformerFactor y(); // Public Class Methods public static TransformerFactory newInstance() throws TransformerFactoryConfigurationError ; // Public Instance Methods public abstract Source getAssociatedStylesheet(Source source, String media, String title, String charset) throws TransformerConfigurationException; public abstract Object getAttribute(String name) throws IllegalArgumentException; public abstract ErrorListener getErrorListener(); public abstract boolean getFeature(String name); public abstract URIResolver getURIResolver(); public abstract Templates newTemplates(Source source) throws TransformerConfigurationException; public abstract Transformer newTransformer() throws TransformerConfigurationException; public abstract Transformer newTransformer(Source source) throws TransformerConfigurationException; public abstract void setAttribute(String name, Object value) throws IllegalArgumentException; public abstract void setErrorListener(ErrorListener listener) throws IllegalArgumentException; public abstract void setURIResolver(URIResolver resolver); } Subclasses: javax.xml.transform.sax.SAXTransformerFactor y Returned By: TransformerFactor y.newInstance()

TransformerFactor yConfigurationError javax.xml.transform

Java 1.4 serializable error

This error class signals a fatal problem while creating a TransformerFactor y. It usually signals a configuration problem, such as the system property javax.xml.transform.TransformerFactor y has a value that is not a valid classname, or that the class path does not contain the specified factory implementation class. Object

Throwable

Error

TransformerFactoryConfigurationError

Serializable

public class TransformerFactor yConfigurationError extends Error { // Public Constructors public TransformerFactor yConfigurationError(); public TransformerFactor yConfigurationError(String msg); public TransformerFactor yConfigurationError(Exception e); public TransformerFactor yConfigurationError(Exception e, String msg); // Public Instance Methods public Exception getException(); // Public Methods Overriding Throwable public String getMessage(); }

default:null default:null

Thrown By: TransformerFactor y.newInstance()

URIResolver

Java 1.4

javax.xml.transform This interface allows an application to tell a Transformer how to resolve the URIs that appear in an XSLT stylesheet. If you pass a URIResolver to the setURIResolver() method of a Transformer or TransformerFactor y, and then the Transformer or TransformerFactor y encounters a URI, it first passes that URI, along with the base URI to the resolve() method of the URIResolver. If resolve() returns a Source object, then the Transformer will use that Source. If a Transformer or TransformerFactor y has no URIResolver registered, or if the resolve() method returns null, then the transformer or factory will attempt to resolve the URI itself.

818

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

DOMResult

public interface URIResolver { // Public Instance Methods public abstract Source resolve(String href, String base) throws TransformerException; } Passed To: Transformer.setURIResolver(), TransformerFactor y.setURIResolver() Returned By: Transformer.getURIResolver(), TransformerFactor y.getURIResolver()

Package javax.xml.transform.dom

Java 1.4

This package contains Source and Result implementations that work with DOM document trees and subtrees. Interfaces: public interface DOMLocator extends javax.xml.transform.SourceLocator; Classes: public class DOMResult implements javax.xml.transform.Result; public class DOMSource implements javax.xml.transform.Source;

DOMLocator

Java 1.4

javax.xml.transform.dom This class extends SourceLocator to define a method for retrieving a DOM Node object, which is typically used to indicate the source of an error in the transformation process. See SourceLocator and TransformerException. SourceLocator

DOMLocator

public interface DOMLocator extends javax.xml.transform.SourceLocator { // Public Instance Methods public abstract org.w3c.dom.Node getOriginatingNode(); }

DOMResult

Java 1.4

javax.xml.transform.dom This class is a Result implementation that writes XML content by generating a DOM tree to represent that content. If you pass an org.w3c.dom.Node to the constructor or to setNode(), the DOMResult will create the result tree as a child of the specified node (which should typically be a Document or Element node). If you do not specify a node, the DOMResult will create a new Document node when it creates the result tree. You can retrieve this Document with getNode(). Object

DOMResult

Result

public class DOMResult implements javax.xml.transform.Result { // Public Constructors public DOMResult(); public DOMResult(org.w3c.dom.Node node); public DOMResult(org.w3c.dom.Node node, String systemID);

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

819

DOMResult

// Public Constants public static final String FEATURE; = [quot ] http://javax.xml.transform.dom.DOMResult/feature [quot ] // Public Instance Methods public org.w3c.dom.Node getNode(); default:null public void setNode(org.w3c.dom.Node node); // Methods Implementing Result public String getSystemId(); default:null public void setSystemId(String systemId); }

DOMSource

Java 1.4

javax.xml.transform.dom This class is a Source implementation that reads an XML document from a DOM document tree or subtree. Pass the org.w3c.dom.Node object that represents the root of the tree or subtree to the constructor or to setNode(). When possible, it is also useful to provide a system id (a filename or URL) for use in error messages and for resolving relative URLs contained in the document. Object

DOMSource

Source

public class DOMSource implements javax.xml.transform.Source { // Public Constructors public DOMSource(); public DOMSource(org.w3c.dom.Node n); public DOMSource(org.w3c.dom.Node node, String systemID); // Public Constants public static final String FEATURE; = [quot ] http://javax.xml.transform.dom.DOMSource/feature [quot ] // Public Instance Methods public org.w3c.dom.Node getNode(); default:null public void setNode(org.w3c.dom.Node node); // Methods Implementing Source public String getSystemId(); default:null public void setSystemId(String baseID); }

Package javax.xml.transform.sax

Java 1.4

This package defines Source and Result implementations that work with SAX events. In addition, it includes an extension to the TransformerFactor y class that has additional methods for returning TemplatesHandler and TransformerHandler objects. These objects implement SAX handler interfaces and are able to work with a SAX parser object to turn a series of SAX parse events into a Templates object or into a Result document. SAXSource and SAXResult adapt the org.xml.sax framework for use in the javax.xml.transform framework. By contrast, SAXTransformerFactor y, TemplatesHandler, and TransformerHandler adapt the javax.xml.transform framework for use within the org.xml.sax parsing framework. Interfaces: public interface TemplatesHandler extends org.xml.sax.ContentHandler; public interface TransformerHandler extends org.xml.sax.ContentHandler, org.xml.sax.DTDHandler, org.xml.sax.ext.LexicalHandler;

820

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

SAXSource Classes: public class SAXResult implements javax.xml.transform.Result; public class SAXSource implements javax.xml.transform.Source; public abstract class SAXTransformerFactor y extends javax.xml.transform.TransformerFactor y;

SAXResult

Java 1.4

javax.xml.transform.sax This class is a Result implementation that describes the content of a transformed document by triggering the methods of the specified ContentHandler. That is, a SAXResult acts like a org.xml.sax.XMLReader object, invoking the methods of the specified org.xml.sax.ContentHandler object as it parses the transformed document. You may also provide a org.xml.sax.ext.LexicalHandler object whose methods will be invoked by the SAXResult by calling setLexicalHandler(), or by supplying a ContentHandler object that also implements the LexicalHandler interface. Object

SAXResult

Result

public class SAXResult implements javax.xml.transform.Result { // Public Constructors public SAXResult(); public SAXResult(org.xml.sax.ContentHandler handler); // Public Constants public static final String FEATURE; = [quot ] http://javax.xml.transform.sax.SAXResult/feature [quot ] // Public Instance Methods public org.xml.sax.ContentHandler getHandler(); default:null public org.xml.sax.ext.LexicalHandler getLexicalHandler(); default:null public void setHandler(org.xml.sax.ContentHandler handler); public void setLexicalHandler(org.xml.sax.ext.LexicalHandler handler); // Methods Implementing Result public String getSystemId(); default:null public void setSystemId(String systemId); }

SAXSource

Java 1.4

javax.xml.transform.sax This class is a Source implementation that describes a document represented as a series of SAX event method calls. A SAXSource requires an org.xml.sax.InputSource object that describes the stream to parse, and may optionally specify the org.xml.sax.XMLReader or org.xml.sax.XMLFilter that generates the SAX events. (If no XMLReader or XMLFilter is specified, then the Transformer object will create a default XMLReader.) Note that since an InputSource is required, a SAXSource does not behave significantly differently than a StreamSource unless an XMLFilter is used. SAXSource also has one static method, sourceToInputSource(), which returns a SAX InputSource method derived from the specified Source object, or null if the specified Source cannot be converted to an InputSource. Object

SAXSource

Source

public class SAXSource implements javax.xml.transform.Source { // Public Constructors public SAXSource(); public SAXSource(org.xml.sax.InputSource inputSource);

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

821

SAXSource

public SAXSource(org.xml.sax.XMLReader reader, org.xml.sax.InputSource inputSource); // Public Constants public static final String FEATURE; = [quot ] http://javax.xml.transform.sax.SAXSource/feature [quot ] // Public Class Methods public static org.xml.sax.InputSource sourceToInputSource(javax.xml.transform.Source source); // Public Instance Methods public org.xml.sax.InputSource getInputSource(); default:null public org.xml.sax.XMLReader getXMLReader(); default:null public void setInputSource(org.xml.sax.InputSource inputSource); public void setXMLReader(org.xml.sax.XMLReader reader); // Methods Implementing Source public String getSystemId(); default:null public void setSystemId(String systemId); }

SAXTransformerFactor y

Java 1.4

javax.xml.transform.sax This class extends TransformerFactor y to define additional factory methods that are useful when working with documents that are represented as sequences of SAX events. Pass the FEATURE constant to the getFeature() method of your TransformerFactor y object to determine whether the newTemplatesHandler() and newTransformerHandler() methods are supported and whether it is safe to cast your TransformerFactor y object to a SAXTransformerFactor y. Use the FEATURE_XMLFILTER constant with getFeature() to determine if the newXMLFilter() methods are also supported. newTemplatesHandler() returns a TemplatesHandler object that you can use as an org.xml.sax.ContentHandler object to receive SAX events generated by a SAX parser and transform those events into a Templates object. The newTransformerHandler() methods are similar: they return a TransformerHandler object that can receive SAX events and representing a source document and transform them into a Result document. The no-argument version of newTransformerHandler() creates a TransformerHandler that simply modifies the form of the document without applying a stylesheet to its content. The other two versions of newTransformerHandler() use a stylesheet specified either as a Source or Templates object. The newXMLFilter() methods, if supported, return an org.xml.sax.XMLFilter object that can acts as both a sink and a source of SAX events and filters those events by applying the transformation instructions specified by the Templates or Source objects. Object

TransformerFactory

SAXTransformerFactory

public abstract class SAXTransformerFactor y extends javax.xml.transform.TransformerFactory { // Protected Constructors protected SAXTransformerFactor y(); // Public Constants public static final String = [quot ] http://javax.xml.transform.sax.SAXTransformerFactory/feature [quot ] FEATURE; public static final String = [quot ] http://javax.xml.transform.sax.SAXTransformerFactory/feature/xmlfilter [quot ] FEATURE_XMLFILTER; // Public Instance Methods public abstract TemplatesHandler newTemplatesHandler() throws javax.xml.transform.TransformerConfigurationException;

822

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

TransformerHandler

public abstract TransformerHandler newTransformerHandler() throws javax.xml.transform.TransformerConfigurationException; public abstract TransformerHandler newTransformerHandler(javax.xml.transform.Source src) throws javax.xml.transform.TransformerConfigurationException; public abstract TransformerHandler newTransformerHandler(javax.xml.transform.Templates templates) throws javax.xml.transform.TransformerConfigurationException; public abstract org.xml.sax.XMLFilter newXMLFilter(javax.xml.transform.Source src) throws javax.xml.transform.TransformerConfigurationException; public abstract org.xml.sax.XMLFilter newXMLFilter(javax.xml.transform.Templates templates) throws javax.xml.transform.TransformerConfigurationException; }

TemplatesHandler

Java 1.4

javax.xml.transform.sax This interface extends org.xml.sax.ContentHandler and adds a getTemplates() method. An object that implements this interface can be used to receive method calls from some source of SAX events and process those events (as an XSL stylesheet) into a Templates object. Obtain a TemplatesHandler from a SAXTransformerFactor y. Register it with the setContentHandler() method of an org.xml.sax.XMLReader and invoke the parse() method of the reader. When parse() returns, call the getTemplates() method to obtain the Templates object. ContentHandler

TemplatesHandler

public interface TemplatesHandler extends org.xml.sax.ContentHandler { // Public Instance Methods public abstract String getSystemId(); public abstract javax.xml.transform.Templates getTemplates(); public abstract void setSystemId(String systemID); } Returned By: SAXTransformerFactor y.newTemplatesHandler()

TransformerHandler

Java 1.4

javax.xml.transform.sax This interface extends org.xml.sax.ContentHandler and related interfaces so that it can consume SAX events generated by a org.xml.sax.SAXReader or org.xml.sax.XMLFilter. Create a TransformerHandler by calling one of the newTransformerHandler() methods of a SAXTransformerFactor y. Next, call the setResult() method to specify a Result object that describes the result document you’d like the transformation to produce. You may also call getTransformer() to get the Transformer object associated with this TransformerHandler if you need to set output properties or parameter values for the transformation. Now, register the TransformerHandler with the XMLReader or XMLFilter object by calling setContentHandler(), setDTDHandler(), and setProperty(). Use the property name “http://www.xml.org/sax/properties/lexical-handler” in the call to setProperties() to register the TransformerHandler as a org.xml.sax.ext.LexicalHandler for the parser or filter. Finally, invoke one of the parse() methods on your XMLReader or XMLFilter object. This will cause the reader or filter to start parsing the source document and translating it into method calls on the TransformerHandler. The TransformerHandler will transform those calls as specified in the Templates or Source object (if any) that was passed to the original call to

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

823

TransformerHandler newTransformerHandler() and generate a result document as directed by the Result object that was passed to setResult(). TransformerHandler ContentHandler

DTDHandler

LexicalHandler

public interface TransformerHandler extends org.xml.sax.ContentHandler, org.xml.sax.DTDHandler, org.xml.sax.ext.LexicalHandler { // Public Instance Methods public abstract String getSystemId(); public abstract javax.xml.transform.Transformer getTransformer(); public abstract void setResult(javax.xml.transform.Result result) throws IllegalArgumentException; public abstract void setSystemId(String systemID); } Returned By: SAXTransformerFactor y.newTransformerHandler()

Package javax.xml.transform.stream

Java 1.4

This package contains Source and Result implementations that work with files and streams. Classes: public class StreamResult implements javax.xml.transform.Result; public class StreamSource implements javax.xml.transform.Source;

StreamResult

Java 1.4

javax.xml.transform.stream This class is a Result implementation that writes a textual representation of a transformed document to stream or file. Because XML documents define their own encoding, it is usually preferable to construct a StreamResult using a File or OutputStream instead of a character-based Writer which may use a different encoding than that specified within the document. Object

StreamResult

Result

public class StreamResult implements javax.xml.transform.Result { // Public Constructors public StreamResult(); public StreamResult(java.io.File f); public StreamResult(String systemId); public StreamResult(java.io.Writer writer); public StreamResult(java.io.OutputStream outputStream); // Public Constants public static final String FEATURE; = [quot ] http://javax.xml.transform.stream.StreamResult/feature [quot ] // Property Accessor Methods (by property name) public java.io.OutputStream getOutputStream(); default:null public void setOutputStream(java.io.OutputStream outputStream); public String getSystemId(); Implements:Result default:null public void setSystemId(java.io.File f); public void setSystemId(String systemId); Implements:Result public java.io.Writer getWriter(); default:null public void setWriter(java.io.Writer writer); // Methods Implementing Result

824

7 March 2002 11:40

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

StreamSource

public String getSystemId(); public void setSystemId(String systemId);

default:null

}

StreamSource

Java 1.4

javax.xml.transform.stream This class is a Source implementation that reads the textual format of an XML document from a file, byte stream, or character stream. Because XML documents declare their own encoding, it is preferable to create a StreamSource object from an InputStream instead of from a Reader, so that the XML processor can correctly handle the declared encoding. When creating a StreamSource from a byte stream or character stream, you should provide the system ID (i.e., the filename or URL) by using one of the two-argument constructors or by scaling setSystemId(). The system ID is required if the XML file to be processed includes relative URLs to be resolved. Object

StreamSource

Source

public class StreamSource implements javax.xml.transform.Source { // Public Constructors public StreamSource(); public StreamSource(java.io.InputStream inputStream); public StreamSource(java.io.Reader reader); public StreamSource(java.io.File f); public StreamSource(String systemId); public StreamSource(java.io.Reader reader, String systemId); public StreamSource(java.io.InputStream inputStream, String systemId); // Public Constants public static final String FEATURE; = [quot ] http://javax.xml.transform.stream.StreamSource/feature [quot ] // Property Accessor Methods (by property name) public java.io.InputStream getInputStream(); default:null public void setInputStream(java.io.InputStream inputStream); public String getPublicId(); default:null public void setPublicId(String publicId); public java.io.Reader getReader(); default:null public void setReader(java.io.Reader reader); public String getSystemId(); Implements:Source default:null public void setSystemId(java.io.File f); public void setSystemId(String systemId); Implements:Source // Methods Implementing Source public String getSystemId(); default:null public void setSystemId(String systemId); }

Chapter 21 – javax.xml.parsers, java.xml.transform, and Subpackages

7 March 2002 11:40

825

CHAPTER 22

org.ietf.jgss

Package org.ietf.jgss

Java 1.4

This package is a Java binding of the Generic Security Services (GSS) API defined by the Internet Engineering Task Force (IETF). GSS is an API that allows two network peers to mutually authenticate each other, and to ensure the integrity and confidentiality of the data they exchange. GSS is a “generic” API in that it is designed to be general enough to work on top of any “security mechanism” that supports authentication, encryption, and data integrity protection. One such mechanism is Kerberos, and Sun’s JGSS implementation currently supports only the Kerberos mechanism. Sun’s implementation is integrated with the JAAS API defined by the javax.security.auth package and its sub-packages. Clients and servers that want to use JGSS must first perform a JAAS login to ensure that the required Kerberos credentials are available to the JGSS implementation. Begin studying this package with GSSManager, which is the central factory class for the API. Understanding and using this package requires substantial knowledge of the GSS API and of Kerberos. Because these topics are well beyond the scope of this reference, no attempt is made to fully document the classes in this package. For more information, please read the relevant RFC documents published by the IETF: •

The GSS API is defined in a language-independent way by RFC 2743: http://www.ietf.org/rfc/r fc2743.txt.



The Java binding of the GSS API is defined by RFC 2853: http://www.ietf.org/rfc/ rfc2853.txt.



The Kerberos Network Authentication Service is defined by RFC 1510: http://www.ietf.org/rfc/r fc1510.txt.



A Kerberos security mechanism http://www.ietf.org/rfc/r fc1964.txt.

for

GSS

is

defined

by

RFC

1964:

In addition to these primary sources, Sun includes JGSS documentation and tutorials in its documentation bundle for Java 1.4. You can find them at: http://java.sun.com/ j2se/1.4/docs/guide/security/jgss/tutorials/index.html.

826

7 March 2002 11:40

GSSContext Interfaces: public interface GSSContext; public interface GSSCredential extends Cloneable; public interface GSSName; Classes: public class ChannelBinding; public abstract class GSSManager ; public class MessageProp; public class Oid; Exception: public class GSSException extends Exception;

ChannelBinding

Java 1.4

org.ietf.jgss A ChannelBinding object is used to provide additional constraints, such as the Internet addresses of the client and server, upon the establishment of a security context. public class ChannelBinding { // Public Constructors public ChannelBinding(byte[ ] appData); public ChannelBinding(java.net.InetAddress initAddr, java.net.InetAddress acceptAddr, byte[ ] appData); // Public Instance Methods public java.net.InetAddress getAcceptorAddress(); public byte[ ] getApplicationData(); public java.net.InetAddress getInitiatorAddress(); // Public Methods Overriding Object public boolean equals(Object obj); public int hashCode(); } Passed To: GSSContext.setChannelBinding()

GSSContext

Java 1.4

org.ietf.jgss This interface represents the “security context” within which authentication, encryption, and data integrity protection take place. A GSSContext object is obtained from a GSSManager factory. Before a GSSContext can be used to exchange data with a network peer, the security context must first be “established” (this typically involves mutual authentication) in a “context establishment loop” in which the client repeatedly calls initSecContext() and the server repeatedly calls acceptSecContext(), until the isEstablished() method returns true. Once a context has been established, you can use wrap() to apply security services (such as encryption) to an array of bytes or to a stream and can use unwrap() to reverse this process. You can also use getMIC() and verifyMIC() to generate and verify a “message integrity code” to protect the integrity of data that is transmitted in the clear. public interface GSSContext { // Public Constants public static final int DEFAULT_LIFETIME; public static final int INDEFINITE_LIFETIME;

=0 =2147483647

Chapter 22 – org.ietf.jgss

7 March 2002 11:40

827

GSSContext

// Property Accessor Methods (by property name) public abstract boolean getAnonymityState(); public abstract boolean getConfState(); public abstract boolean getCredDelegState(); public abstract GSSCredential getDelegCred() throws GSSException; public abstract boolean isEstablished(); public abstract boolean isInitiator() throws GSSException; public abstract boolean getIntegState(); public abstract int getLifetime(); public abstract Oid getMech() throws GSSException; public abstract boolean getMutualAuthState(); public abstract boolean isProtReady(); public abstract boolean getReplayDetState(); public abstract boolean getSequenceDetState(); public abstract GSSName getSrcName() throws GSSException; public abstract GSSName getTargName() throws GSSException; public abstract boolean isTransferable() throws GSSException; // Public Instance Methods public abstract void acceptSecContext(java.io.InputStream inStream, java.io.OutputStream outStream) throws GSSException; public abstract byte[ ] acceptSecContext(byte[ ] inToken, int offset, int len) throws GSSException; public abstract void dispose() throws GSSException; public abstract byte[ ] export() throws GSSException; public abstract void getMIC(java.io.InputStream inStream, java.io.OutputStream outStream, MessageProp msgProp) throws GSSException; public abstract byte[ ] getMIC(byte[ ] inMsg, int offset, int len, MessageProp msgProp) throws GSSException; public abstract int getWrapSizeLimit(int qop, boolean confReq, int maxTokenSize) throws GSSException; public abstract int initSecContext(java.io.InputStream inStream, java.io.OutputStream outStream) throws GSSException; public abstract byte[ ] initSecContext(byte[ ] inputBuf, int offset, int len) throws GSSException; public abstract void requestAnonymity(boolean state) throws GSSException; public abstract void requestConf(boolean state) throws GSSException; public abstract void requestCredDeleg(boolean state) throws GSSException; public abstract void requestInteg(boolean state) throws GSSException; public abstract void requestLifetime(int lifetime) throws GSSException; public abstract void requestMutualAuth(boolean state) throws GSSException; public abstract void requestReplayDet(boolean state) throws GSSException; public abstract void requestSequenceDet(boolean state) throws GSSException; public abstract void setChannelBinding(ChannelBinding cb) throws GSSException; public abstract void unwrap(java.io.InputStream inStream, java.io.OutputStream outStream, MessageProp msgProp) throws GSSException; public abstract byte[ ] unwrap(byte[ ] inBuf, int offset, int len, MessageProp msgProp) throws GSSException; public abstract void verifyMIC(java.io.InputStream tokStream, java.io.InputStream msgStream, MessageProp msgProp) throws GSSException; public abstract void verifyMIC(byte[ ] inToken, int tokOffset, int tokLen, byte[ ] inMsg, int msgOffset, int msgLen, MessageProp msgProp) throws GSSException; public abstract void wrap(java.io.InputStream inStream, java.io.OutputStream outStream, MessageProp msgProp) throws GSSException; public abstract byte[ ] wrap(byte[ ] inBuf, int offset, int len, MessageProp msgProp) throws GSSException; } Returned By: GSSManager.createContext()

828

7 March 2002 11:40

Chapter 22 – org.ietf.jgss

GSSException

GSSCredential

Java 1.4 cloneable

org.ietf.jgss

This interface defines a high-level API to a generic security credential, such as a Kerberos ticket or a Kerberos key. Cloneable

GSSCredential

public interface GSSCredential extends Cloneable { // Public Constants public static final int ACCEPT_ONLY; =2 public static final int DEFAULT_LIFETIME; =0 public static final int INDEFINITE_LIFETIME; =2147483647 public static final int INITIATE_AND_ACCEPT; =0 public static final int INITIATE_ONLY; =1 // Public Instance Methods public abstract void add(GSSName name, int initLifetime, int acceptLifetime, Oid mech, int usage) throws GSSException; public abstract void dispose() throws GSSException; public abstract boolean equals(Object another); public abstract Oid[ ] getMechs() throws GSSException; public abstract GSSName getName() throws GSSException; public abstract GSSName getName(Oid mech) throws GSSException; public abstract int getRemainingAcceptLifetime(Oid mech) throws GSSException; public abstract int getRemainingInitLifetime(Oid mech) throws GSSException; public abstract int getRemainingLifetime() throws GSSException; public abstract int getUsage() throws GSSException; public abstract int getUsage(Oid mech) throws GSSException; public abstract int hashCode(); } Passed To: GSSManager.createContext() Returned By: GSSContext.getDelegCred(), GSSManager.createCredential()

GSSException

Java 1.4 serializable checked

org.ietf.jgss

This exception class is used to signal all exceptions in the org.ietf.jgss package. getMajor() returns a GSS error code, which should be one of the integer constants defined by this class. getMajorString() returns an error message that corresponds to that error code. getMinor() and getMinorString() return an error code and error string that are specific to the underlying security mechanism. Object

Throwable

Exception

GSSException

Serializable

public class GSSException extends Exception { // Public Constructors public GSSException(int majorCode); public GSSException(int majorCode, int minorCode, String minorString); // Public Constants public static final int BAD_BINDINGS; public static final int BAD_MECH; public static final int BAD_MIC; public static final int BAD_NAME; public static final int BAD_NAMETYPE;

Chapter 22 – org.ietf.jgss

7 March 2002 11:40

=1 =2 =6 =3 =4

829

GSSException

public static final int BAD_QOP; public static final int BAD_STATUS; public static final int CONTEXT_EXPIRED; public static final int CREDENTIALS_EXPIRED; public static final int DEFECTIVE_CREDENTIAL; public static final int DEFECTIVE_TOKEN; public static final int DUPLICATE_ELEMENT; public static final int DUPLICATE_TOKEN; public static final int FAILURE; public static final int GAP_TOKEN; public static final int NAME_NOT_MN; public static final int NO_CONTEXT; public static final int NO_CRED; public static final int OLD_TOKEN; public static final int UNAUTHORIZED; public static final int UNAVAILABLE; public static final int UNSEQ_TOKEN; // Public Instance Methods public int getMajor(); public String getMajorString(); public int getMinor(); public String getMinorString(); public void setMinor(int minorCode, String message); // Public Methods Overriding Throwable public String getMessage(); public String toString(); }

=14 =5 =7 =8 =9 =10 =17 =19 =11 =22 =18 =12 =13 =20 =15 =16 =21

Thrown By: Too many methods to list.

GSSManager

Java 1.4

org.ietf.jgss This is the central factory class of the org.ietf.jgss package. Obtain the default GSSManager with the static getInstance() method or by instantiating some vendor-supplied subclass. Call getMechs() to query the security mechanisms supported by the manager. (The default GSSManager supplied by Sun supports only the Kerberos mechanism.) Call createContext() to create a GSSContext. Call createCredential() to create a GSSCredential. Call createName() to create a GSSName. public abstract class GSSManager { // Public Constructors public GSSManager(); // Public Class Methods public static GSSManager getInstance(); // Public Instance Methods public abstract void addProviderAtEnd(java.security.Provider p, Oid mech) throws GSSException; public abstract void addProviderAtFront(java.security.Provider p, Oid mech) throws GSSException; public abstract GSSContext createContext(GSSCredential myCred) throws GSSException; public abstract GSSContext createContext(byte[ ] interProcessToken) throws GSSException; public abstract GSSContext createContext(GSSName peer, Oid mech, GSSCredential myCred, int lifetime) throws GSSException; public abstract GSSCredential createCredential(int usage) throws GSSException; public abstract GSSCredential createCredential(GSSName name, int lifetime, Oid mech, int usage) throws GSSException; public abstract GSSCredential createCredential(GSSName name, int lifetime, Oid[ ] mechs, int usage) throws GSSException;

830

7 March 2002 11:40

Chapter 22 – org.ietf.jgss

MessageProp

public abstract GSSName createName(String nameStr, Oid nameType) throws GSSException; public abstract GSSName createName(byte[ ] name, Oid nameType) throws GSSException; public abstract GSSName createName(String nameStr, Oid nameType, Oid mech) throws GSSException; public abstract GSSName createName(byte[ ] name, Oid nameType, Oid mech) throws GSSException; public abstract Oid[ ] getMechs(); public abstract Oid[ ] getMechsForName(Oid nameType); public abstract Oid[ ] getNamesForMech(Oid mech) throws GSSException; } Returned By: GSSManager.getInstance()

GSSName

Java 1.4

org.ietf.jgss A GSSName represents an entity, such as a user or a network server, that participates in a GSS session. The constants defined by this class represent the allowed set of “name types.” public interface GSSName { // Public Constants public static final Oid NT_ANONYMOUS; public static final Oid NT_EXPORT_NAME; public static final Oid NT_HOSTBASED_SERVICE; public static final Oid NT_MACHINE_UID_NAME; public static final Oid NT_STRING_UID_NAME; public static final Oid NT_USER_NAME; // Public Instance Methods public abstract GSSName canonicalize(Oid mech) throws GSSException; public abstract boolean equals(Object another); public abstract boolean equals(GSSName another) throws GSSException; public abstract byte[ ] export() throws GSSException; public abstract Oid getStringNameType() throws GSSException; public abstract int hashCode(); public abstract boolean isAnonymous(); public abstract boolean isMN(); public abstract String toString(); } Passed To: GSSCredential.add(), GSSManager.{createContext(), createCredential()}, GSSName.equals() Returned By: GSSContext.{getSrcName(), getTargName()}, GSSCredential.getName(), GSSManager.createName(), GSSName.canonicalize()

MessageProp

Java 1.4

org.ietf.jgss This utility class is used with the wrap(), unwrap(), getMIC() and verifyMIC() methods of GSSContext to pass and return properties related to the message or message integrity code. public class MessageProp { // Public Constructors public MessageProp(boolean privState); public MessageProp(int qop, boolean privState); // Property Accessor Methods (by property name) public boolean isDuplicateToken(); public boolean isGapToken();

Chapter 22 – org.ietf.jgss

7 March 2002 11:40

831

MessageProp

public int getMinorStatus(); public String getMinorString(); public boolean isOldToken(); public boolean getPrivacy(); public void setPrivacy(boolean privState); public int getQOP(); public void setQOP(int qop); public boolean isUnseqToken(); // Public Instance Methods public void setSupplementar yStates(boolean duplicate, boolean old, boolean unseq, boolean gap, int minorStatus, String minorString); } Passed To: GSSContext.{getMIC(), unwrap(), verifyMIC(), wrap()}

Oid

Java 1.4

org.ietf.jgss An Oid is a universal “object identifier” based on a hierarchical numbering system. The Oid class is used in this package to uniquely identify security mechanisms and name types. The Oid for the Kerberos security mechanism is 1.2.840.113554.1.2.2. public class Oid { // Public Constructors public Oid(String strOid) throws GSSException; public Oid(java.io.InputStream derOid) throws GSSException; public Oid(byte[ ] data) throws GSSException; // Public Instance Methods public boolean containedIn(Oid[ ] oids); public byte[ ] getDER() throws GSSException; // Public Methods Overriding Object public boolean equals(Object other); public int hashCode(); public String toString(); } Passed To: Too many methods to list. Returned By: GSSContext.getMech(), GSSCredential.getMechs(), GSSManager.{getMechs(), getMechsForName(), getNamesForMech()}, GSSName.getStringNameType() Type Of: GSSName.{NT_ANONYMOUS, NT_EXPORT_NAME, NT_HOSTBASED_SERVICE, NT_MACHINE_UID_NAME, NT_STRING_UID_NAME, NT_USER_NAME}

832

7 March 2002 11:40

Chapter 22 – org.ietf.jgss

CHAPTER 23

org.w3c.dom

Package org.w3c.dom

Java 1.4

This package defines the Java binding to the core and XML modules of the DOM Level 2 API defined by the World Wide Web Consortium (W3C). DOM stands for Document Object Model, and the DOM API defines a way to represent an XML document as a tree of nodes. It includes methods that allow document trees to be traversed, examined, modified, and built from scratch. Node is the central interface of the package. All nodes in a document tree implement this interface, and it defines the basic methods for traversing and modifying the tree of nodes. Most of the other interfaces in the package are extensions of Node that represent specific types of XML content. The most important and commonly used of these sub-interfaces are Document, Element and Text. A Document object serves as the root of the document tree and defines methods for searching the tree for elements with a specified tag name or ID attribute. The Element interface represents an XML element or tag and has methods for manipulating the element’s attributes. The Text interface represents a run of plain text within an Element, and has methods for querying or altering that text. NodeList and DOMImplementation do not extend Node but are also important interfaces. Interfaces: public interface Attr extends Node; public interface CDATASection extends Text; public interface CharacterData extends Node; public interface Comment extends CharacterData; public interface Document extends Node; public interface DocumentFragment extends Node; public interface DocumentType extends Node; public interface DOMImplementation; public interface Element extends Node; public interface Entity extends Node; public interface EntityReference extends Node; public interface NamedNodeMap;

833

7 March 2002 11:40

Package org.w3c.dom public interface Node; public interface NodeList; public interface Notation extends Node; public interface ProcessingInstruction extends Node; public interface Text extends CharacterData; Exception: public class DOMException extends RuntimeException;

Attr

Java 1.4

org.w3c.dom An Attr object represents an attribute of an Element node. Attr objects are associated with Element nodes, but are not directly part of the document tree: the getParentNode() method of an Attr object always returns null. Use getOwnerElement() to determine which Element an Attr is part of. You can obtain an Attr object by calling the getAttributeNode() method of Element, or you can obtain a NamedNodeMap of all Attr objects for an element with the getAttributes() method of Node. getName() returns the name of the attribute. getValue() returns the attribute value as a string. getSpecified() returns true if the attribute was explicitly specified in the source document through a call to setValue(), and returns false if the attribute represents a default obtained from a DTD or other schema. XML allows attributes to contain text and entity references. The getValue() method returns the attribute value as a single string. If you want to know the precise composition of the attribute however, you can examine the children of the Attr node: they may consist of Text and/or EntityReference nodes. In most cases the easiest way to work with attributes is with the getAttribute() and setAttribute() methods of the Element interface. These methods avoid the use of Attr nodes altogether. Node

Attr

public interface Attr extends Node { // Public Instance Methods public abstract String getName(); public abstract org.w3c.dom.Element getOwnerElement(); public abstract boolean getSpecified(); public abstract String getValue(); public abstract void setValue(String value) throws DOMException; } Passed To: javax.imageio.metadata.IIOMetadataNode.{removeAttributeNode(), setAttributeNode(), setAttributeNodeNS()}, org.w3c.dom.Element.{removeAttributeNode(), setAttributeNode(), setAttributeNodeNS()} Returned By: javax.imageio.metadata.IIOMetadataNode.{getAttributeNode(), getAttributeNodeNS(), removeAttributeNode(), setAttributeNode(), setAttributeNodeNS()}, org.w3c.dom.Document.{createAttribute(), createAttributeNS()}, org.w3c.dom.Element.{getAttributeNode(), getAttributeNodeNS(), removeAttributeNode(), setAttributeNode(), setAttributeNodeNS()}

834

7 March 2002 11:40

Chapter 23 – org.w3c.dom

Comment

CDATASection

Java 1.4

org.w3c.dom This interface represents a CDATA section in an XML document. CDATASection is a subinterface of Text and does not define any methods of its own. The content of the CDATA section is available through the getNodeValue() method inherited from Node, or through the getData() method inherited from CharacterData. Although CDATASection nodes can often be treated in the same way as Text nodes, note that the Node.normalize() method does not merge adjacent CDATA sections. Node

CharacterData

Text

CDATASection

public interface CDATASection extends Text { } Returned By: org.w3c.dom.Document.createCDATASection()

CharacterData

Java 1.4

org.w3c.dom This interface is a generic one that is extended by Text, CDATASection (which extends Text) and Comment. Any node in a document tree that implements CharacterData also implements one of these more specific types. This interface exists simply to group the string manipulation methods that these text-related node types all share. The CharacterData interface defines a mutable string. getData() returns the “character data” as a String object, and setData() allows it to be set from a String object. getLength() returns the number of characters of character data, and substringData() returns just the specified portion of the data as a string. The appendData(), deleteData(), insertData(), and replaceData() methods mutate the data by appending a string to the end, deleting region, inserting a string at the specified location, and replacing a region with a specified string. Node

CharacterData

public interface CharacterData extends Node { // Public Instance Methods public abstract void appendData(String arg) throws DOMException; public abstract void deleteData(int offset, int count) throws DOMException; public abstract String getData() throws DOMException; public abstract int getLength(); public abstract void insertData(int offset, String arg) throws DOMException; public abstract void replaceData(int offset, int count, String arg) throws DOMException; public abstract void setData(String data) throws DOMException; public abstract String substringData(int offset, int count) throws DOMException; } Implementations: Comment, Text

Comment

Java 1.4

org.w3c.dom A Comment node represents a comment in an XML document. The content of the comment (i.e., the text between ) is available with the getData() method inher-

Chapter 23 – org.w3c.dom

7 March 2002 11:40

835

Comment ited from CharacterData, or through the getNodeValue() method inherited from Node. This content may be manipulated using the various methods inherited from CharacterData. Node

CharacterData

Comment

public interface Comment extends CharacterData { } Returned By: org.w3c.dom.Document.createComment()

Document

Java 1.4

org.w3c.dom This interface represents a DOM document, and an object that implements this interface serves as the root of a DOM document tree. Most of the methods defined by the Document interface are “factory methods” that are used to create various types of nodes that can be inserted into this document. Note that there are two versions of the methods for creating attributes and elements. The methods with “NS” in their name are namespaceaware and require the attribute or element name to be specified as a combination of a namespace URI and a local name. You’ll notice that throughout the DOM API, methods with “NS” in their names are namespace-aware. Other important methods include the following. getElementsByTagName() and its namespace-aware variant getElementsByTagNameNS() search the document tree for Element nodes that have the specified tag name and return a NodeList containing those matching nodes. The Element interface defines methods by the same names that search only within the sub-tree defined by an Element. getElementById() is a related method that searches the document tree for a single element with the specified unique value for an ID attribute. This is useful when you use an ID attribute to uniquely identify certain tags within an XML document. Note that this method does not search for attributes that are named “id” or “ID”. It searches for attributes whose XML type (as declared in the document’s DTD) is ID. Such attributes are often named “id”, but this is not required. An XML document must have a single root element. getDocumentElement() returns this Element object. Note, however that this does not mean that a Document node has only one child. It must have exactly one child that is an Element, but it can also have other children such as Comment and ProcessingInstruction nodes. The getDoctype() method returns the DocumentType object (or null if there isn’t one) that represents the document’s DTD. getImplementation() returns the the DOMImplementation object that represents the DOM implementation that created this document tree. Node

Document

public interface Document extends Node { // Public Instance Methods public abstract Attr createAttribute(String name) throws DOMException; public abstract Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException; public abstract CDATASection createCDATASection(String data) throws DOMException; public abstract Comment createComment(String data); public abstract DocumentFragment createDocumentFragment(); public abstract org.w3c.dom.Element createElement(String tagName) throws DOMException; public abstract org.w3c.dom.Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException; public abstract EntityReference createEntityReference(String name) throws DOMException; public abstract ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException;

836

7 March 2002 11:40

Chapter 23 – org.w3c.dom

DocumentType

public abstract Text createTextNode(String data); public abstract DocumentType getDoctype(); public abstract org.w3c.dom.Element getDocumentElement(); public abstract org.w3c.dom.Element getElementById(String elementId); public abstract NodeList getElementsByTagName(String tagname); public abstract NodeList getElementsByTagNameNS(String namespaceURI, String localName); public abstract DOMImplementation getImplementation(); public abstract Node importNode(Node importedNode, boolean deep) throws DOMException; } Implementations: org.w3c.dom.html.HTMLDocument Returned By: javax.imageio.metadata.IIOMetadataNode.getOwnerDocument(), javax.xml.parsers.DocumentBuilder.{newDocument(), parse()}, DOMImplementation.createDocument(), Node.getOwnerDocument(), org.w3c.dom.html.HTMLFrameElement.getContentDocument(), org.w3c.dom.html.HTMLIFrameElement.getContentDocument(), org.w3c.dom.html.HTMLObjectElement.getContentDocument()

DocumentFragment

Java 1.4

org.w3c.dom The DocumentFragment interface represents a portion — or fragment — of a document. More specifically, its represents one or more adjacent document nodes, and all of the descendants of each. DocumentFragment nodes are never part of a document tree, and getParentNode() always returns null. Although a DocumentFragment does not have a parent, it can have children, and you can use the inherited Node methods to add child nodes (or delete or replace them) to a DocumentFragment. DocumentFragment nodes exhibit a special behavior that makes them quite useful: when a request is made to insert a DocumentFragment into a document tree, it is not the DocumentFragment node itself that is inserted, but each of the children of the DocumentFragment instead. This makes DocumentFragment useful as a temporary placeholder for a sequence of nodes that you wish to insert, all at once, into a document. You can create a new, empty, DocumentFragment to work with by calling the createDocumentFragment() method of the desired Document. Node

DocumentFragment

public interface DocumentFragment extends Node { } Returned By: org.w3c.dom.Document.createDocumentFragment()

DocumentType

Java 1.4

org.w3c.dom This interface represents the Document Type Declaration (DTD) of a document. Because the DTD is not part of the document itself, a DocumentType object is not part of DOM document tree, even though it extends the Node interface. If a Document has a DTD, then you may obtain the DocumentType object that represents it by calling the getDoctype() method of the Document object. getName(), getPublicId(), getSystemId(), and getInternalSubset() all return strings (or null) that contain the name, public identifier, system identifier, and internal subset of the document type. getEntities() returns a read-only NamedNodeMap that represents the a name-tovalue mapping for all internal and external general entities declared by the DTD. You can use this NamedNodeMap to lookup an Entity object by name. Similarly, getNotations()

Chapter 23 – org.w3c.dom

7 March 2002 11:40

837

DocumentType returns a read-only NamedNodeMap that allows you to look up a Notation object declared in the DTD by name. DocumentType does not provide access to the bulk of a DTD, which usually consists of element and attribute declarations. Future versions of the DOM API may provide more details. Node

DocumentType

public interface DocumentType extends Node { // Property Accessor Methods (by property name) public abstract NamedNodeMap getEntities(); public abstract String getInternalSubset(); public abstract String getName(); public abstract NamedNodeMap getNotations(); public abstract String getPublicId(); public abstract String getSystemId(); } Passed To: DOMImplementation.createDocument() Returned By: org.w3c.dom.Document.getDoctype(), DOMImplementation.createDocumentType()

DOMException org.w3c.dom

Java 1.4 serializable unchecked

An instance of this class is thrown whenever an exception is raised by the DOM API. Unlike many Java APIs, the DOM API does not define specialized subclasses to define different categories of exceptions. Instead, a more specific exception type is specified by the public field code. The value of this field will be one of the constants defined by this class, which have the following meanings: INDEX_SIZE_ERR Indicates an out-of-bounds error for an array or string index. DOMSTRING_SIZE_ERR Indicates that a requested text is too big to fit into a String object. Exceptions of this type are intended for DOM implementations for other languages and should not occur in Java. HIERARCHY_REQUEST_ERR Indicates that an attempt was made to illegally place a node somewhere in the document tree hierarchy. WRONG_DOCUMENT_ERR Indicates that an attempt was made to use a node with a document that is different than the document that created the node. INVALID_CHARACTER_ERR Indicates that an illegal character is used (for example, in an element name). NO_DATA_ALLOWED_ERR Not currently used. NO_MODIFICATION_ALLOWED_ERR Indicates that an attempt was made to modify a node that is read-only and does not allow modifications. Entity, EntityReference, and Notation nodes, and all of their descendants, are read-only.

838

7 March 2002 11:40

Chapter 23 – org.w3c.dom

DOMException NOT_FOUND_ERR Indicates that a node was not found where it was expected to be. NOT_SUPPORTED_ERR Indicates that a method or property is not supported in the current DOM implementation. INUSE_ATTRIBUTE_ERR Indicates that an attempt was made to associate an Attr with an Element when that Attr node was already associated with a different Element node. INVALID_STATE_ERR Indicates that an attempt was made to use an object that is not yet, or is no longer, in a state that allows such use. SYNTAX_ERR Indicates that a specified string contains a syntax error. Exceptions of this type are not raised by the core module of the DOM API described here. INVALID_MODIFICATION_ERR Exceptions of this type are not raised by the core module of the DOM API described here. NAMESPACE_ERR Indicates an error involving element or attribute namespaces. INVALID_ACCESS_ERR Indicates that an attempt was made to access an object in a way that is not supported by the implementation. Object

Throwable

Exception

RuntimeException

DOMException

Serializable

public class DOMException extends RuntimeException { // Public Constructors public DOMException(short code, String message); // Public Constants public static final short DOMSTRING_SIZE_ERR; public static final short HIERARCHY_REQUEST_ERR; public static final short INDEX_SIZE_ERR; public static final short INUSE_ATTRIBUTE_ERR; public static final short INVALID_ACCESS_ERR; public static final short INVALID_CHARACTER_ERR; public static final short INVALID_MODIFICATION_ERR; public static final short INVALID_STATE_ERR; public static final short NAMESPACE_ERR; public static final short NO_DATA_ALLOWED_ERR; public static final short NO_MODIFICATION_ALLOWED_ERR; public static final short NOT_FOUND_ERR; public static final short NOT_SUPPORTED_ERR; public static final short SYNTAX_ERR; public static final short WRONG_DOCUMENT_ERR; // Public Instance Fields public short code; }

=2 =3 =1 =10 =15 =5 =13 =11 =14 =6 =7 =8 =9 =12 =4

Chapter 23 – org.w3c.dom

7 March 2002 11:40

839

DOMException Thrown By: Too many methods to list.

DOMImplementation

Java 1.4

org.w3c.dom This interface defines methods that are global to an implementation of the DOM rather than specific to a particular Document object. Obtain a reference to the DOMImplementation object that represents your implementation by calling the getImplementation() method of any Document object. createDocument() returns a new, empty Document object which you can populate with nodes that you create using the create methods defined by the Document interface. hasFeature() allows you to test whether your DOM implementation supports a specified version of a named feature, or module, of the DOM standard. This method should return true when you pass the feature name “core” and the version “1.0”, or when you pass the feature names “core” or “xml” and the version “2.0”. The DOM standard includes a number of optional modules, but the Java platform has not adopted the subpackages of this package that define the API for those optional modules, and therefore the DOM implementation bundled with a Java implementation is not likely to support those modules. The javax.xml.parsers.DocumentBuilder class provides another way to obtain the DOMImplementation object by calling its getDOMImplementation() object. It also defines a shortcut newDocument() method for creating empty Document objects to populate. public interface DOMImplementation { // Public Instance Methods public abstract org.w3c.dom.Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) throws DOMException; public abstract DocumentType createDocumentType(String qualifiedName, String publicId, String systemId) throws DOMException; public abstract boolean hasFeature(String feature, String version); } Implementations: org.w3c.dom.css.DOMImplementationCSS, org.w3c.dom.html.HTMLDOMImplementation Returned By: javax.xml.parsers.DocumentBuilder.getDOMImplementation(), org.w3c.dom.Document.getImplementation()

Element

Java 1.4

org.w3c.dom This interface represents an element (or tag) in an XML document. getTagName() returns the tagname of the element, including the namespace prefix if there is one. When working with namespaces, you will probably prefer to use the namespace-aware methods defined by the Node interface. Use getNamespaceURI() to get the namespace URI of the element, and use getLocalName() to the local name of the element within that namespace. You can also use getPrefix() to query the namespace prefix, or setPrefix() to change the namespace prefix (this does not change the namespace URI). Element defines a getElementsByTagName() method and a corresponding namespace-aware getElementsByTagNameNS() method, which behave just like the methods of the same names on the Document object, except that they search for named elements only within the subtree rooted at this Element. The remaining methods of the Element interface are for querying and setting attribute values, testing the existence of an attribute, and removing an attribute from the Element. There are a confusing number of methods to perform these four basic attribute

840

7 March 2002 11:40

Chapter 23 – org.w3c.dom

Entity operations. If an attribute-related method has “NS” in its name, then it is namespaceaware. If it has “Node” in its name, then it works with Attr objects rather than with the simpler string representation of the attribute value. Attributes in XML documents may contain entity references. If your document includes entity references in attribute values, then you may need to use the Attr interface because the expansion of such an entity reference can result in a sub-tree of nodes beneath the Attr object. Whenever possible, however, it is much easier to work with the methods that treat attribute values as plain strings. Note also that in addition to the attribute methods defined by the Element interface you can also obtain a NamedNodeMap of Attr objects with the getAttributes() method of the Node interface. Finally, note that getAttribute() and related methods and hasAttribute() and related methods return the value of or test for the existence of both explicitly specified attributes, and also attributes for which a default value is specified in the document DTD. If you need to determine whether an attribute was explicitly specified in the document, obtain its Attr object, and use its getSpecified() method. Node

Element

public interface Element extends Node { // Public Instance Methods public abstract String getAttribute(String name); public abstract Attr getAttributeNode(String name); public abstract Attr getAttributeNodeNS(String namespaceURI, String localName); public abstract String getAttributeNS(String namespaceURI, String localName); public abstract NodeList getElementsByTagName(String name); public abstract NodeList getElementsByTagNameNS(String namespaceURI, String localName); public abstract String getTagName(); public abstract boolean hasAttribute(String name); public abstract boolean hasAttributeNS(String namespaceURI, String localName); public abstract void removeAttribute(String name) throws DOMException; public abstract Attr removeAttributeNode(Attr oldAttr) throws DOMException; public abstract void removeAttributeNS(String namespaceURI, String localName) throws DOMException; public abstract void setAttribute(String name, String value) throws DOMException; public abstract Attr setAttributeNode(Attr newAttr) throws DOMException; public abstract Attr setAttributeNodeNS(Attr newAttr) throws DOMException; public abstract void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException; } Implementations: javax.imageio.metadata.IIOMetadataNode, org.w3c.dom.html.HTMLElement Passed To: org.w3c.dom.css.DocumentCSS.getOverrideStyle(), org.w3c.dom.css.ViewCSS.getComputedStyle() Returned By: Attr.getOwnerElement(), org.w3c.dom.Document.{createElement(), createElementNS(), getDocumentElement(), getElementById()}

Entity

Java 1.4

org.w3c.dom This interface represents an entity defined in an XML DTD. The name of the entity is specified by the getNodeName() method inherited from the Node interface. The entity content is represented by the child nodes of the Entity node. The methods defined by this interface return the public identifier and system identifier for external entities, and the notation name for unparsed entities. Note that Entity nodes and their children are not part of the document tree (and the getParentNode() method of an Entity always returns

Chapter 23 – org.w3c.dom

7 March 2002 11:40

841

Entity null). Instead, a document may contain one or more references to an entity. See the EntityReference interface. Entities are defined in the DTD (document type definition) of a document, either as part of an external DTD file, or as part of an “internal subset” that defines local entities that are specific to the current document. The DocumentType interface has a getEntities() method that returns a NamedNodeMap mapping entity names to Entity nodes. This is the only way to obtain an Entity object; because they are part of the DTD, Entity nodes never appear within the document tree itself. Entity nodes and all descendants of an Entity node are read-only and cannot be edited or modified in any way. Node

Entity

public interface Entity extends Node { // Public Instance Methods public abstract String getNotationName(); public abstract String getPublicId(); public abstract String getSystemId(); }

EntityReference

Java 1.4

org.w3c.dom This interface represents a reference from an XML document to an entity defined in the document’s DTD. Character entities and predefined entities such as < are always expanded in XML documents and do not create EntityReference nodes. Note also that some XML parsers expand all entity references. Documents created by such parsers do not contain EntityReference nodes. This interface defines no methods of its own. The getNodeName() method of the Node interface provides the name of the referenced entity. The getEntities() method of the DocumentType interface provides a way to look up the Entity object associated with that name. Note however, that the DocumentType may not contain an Entity with the specified name (because, for example, nonvalidating XML parsers are not required to parse the external subset of the DTD.) In this case, the EntityReference is a reference to a named entity whose content is not known, and it has no children. On the other hand, if the DocumentType does contain an Entity node with the specified name, then the child nodes of the EntityReference are a copy of the child nodes of the Entity, and represent the expansion of the entity. (The children of an EntityReference may not be an exact copy of the children of an Entity if the entity’s expansion includes namespace prefixes that are not bound to namespace URIs.) Like Entity nodes, EntityReference nodes and their descendants are read-only and cannot be edited or modified. Node

EntityReference

public interface EntityReference extends Node { } Returned By: org.w3c.dom.Document.createEntityReference()

NamedNodeMap

Java 1.4

org.w3c.dom The NamedNodeMap interface defines a collection of nodes that may be looked up by name or by namespace URI and local name. It is unrelated to the java.util.Map interface.

842

7 March 2002 11:40

Chapter 23 – org.w3c.dom

Node Use getNamedItem() to look for and return a node whose getNodeName() method returns the specified value. Use getNamedItemNS() to look for and return a node whose getNamespaceURI() and getLocalName() methods return the specified values. A NamedNodeMap is a mapping from names to nodes, and does not order the nodes in any particular way. Nevertheless, it does impose an arbitrary ordering on the nodes and allow them to be looked up by index. Use getLength() to find out how many nodes are contained in the NamedNodeMap, and use item() to obtain the Node object at a specified index. If a NamedNodeMap is not read-only, you can use removeNamedItem() and removeNamedItemNS() to remove a named node from the map, and you can use setNamedItem() and setNamedItemNS() to add a node to the map, mapping to it from its name or its namespace URI and local name. NamedNodeMap objects are live, which means that they immediately reflect any changes to the document tree. For example, if you obtain a NamedNodeMap that represents the attributes of an element, and then add a new attribute to that element, the new attribute is automatically available through the NamedNodeMap: you do not need to obtain a new NamedNodeMap to get the modified set of attributes. NamedNodeMap is returned only by relatively obscure methods of the DOM API. The most notable use is as the return value of the getAttributes() method of Node. It is usually easier to work with attributes through the methods of the Element interface, however. Two methods of DocumentType also return read-only NamedNodeMap objects. public interface NamedNodeMap { // Public Instance Methods public abstract int getLength(); public abstract Node getNamedItem(String name); public abstract Node getNamedItemNS(String namespaceURI, String localName); public abstract Node item(int index); public abstract Node removeNamedItem(String name) throws DOMException; public abstract Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException; public abstract Node setNamedItem(Node arg) throws DOMException; public abstract Node setNamedItemNS(Node arg) throws DOMException; } Returned By: javax.imageio.metadata.IIOMetadataNode.getAttributes(), DocumentType.{getEntities(), getNotations()}, Node.getAttributes()

Node

Java 1.4

org.w3c.dom All objects in a DOM document tree (including the Document object itself) implement the Node interface, which provides basic methods for traversing and manipulating the tree. getParentNode() and getChildNodes() allow you to traverse up and down the document tree. You can enumerate the children of a given node by looping through the elements of the NodeList returned by getChildNodes(), or by using getFirstChild() and getNextSibling() (or getLastChild() and getPreviousSibling() to loop backwards). It is sometimes useful to call hasChildNodes() to determine whether a node has children or not. getOwnerDocument() returns the Document node of which the node is a descendant or with which it is associated. It provides a quick way to jump to the root of the document tree. Several methods allow you to add children to a tree or alter the list of children. appendChild() adds a new child node at the end of this nodes list of children. insertChild() inserts a node into this nodes list of children, placing it immediately before a specified child node. removeChild() removes the specified node from this node’s list of children. replaceChild() replaces one child node of this node with another node. For all of these

Chapter 23 – org.w3c.dom

7 March 2002 11:40

843

Node methods, if the node to be appended or inserted is already part of the document tree, it is first removed from its current parent. Use cloneNode() to produce a copy of this node. Pass true if you want all descendants of this node to be cloned as well. Every object in a document tree implements the Node interface, but also implements a more specialized subinterface, such as Element or Text. The getNodeType() method provides an easy way to determine which subinterface a node implements: the return value is one of the _NODE constants defined by this class. You might use the return value of getNodeType() in a switch statement, for example, to determine how to process a node of unknown type. getNodeName() and getNodeValue() provide additional information about a node, but the interpretation of the strings they return depends on the node type as shown in the table below. Note that subinterfaces typically define specialized methods (such as the getTagName() method of Element and the getData() method of Text) for obtaining this same information. Note also that unless a node is read-only, you can use setNodeValue() to alter the value associated with the node. Node type

Node name

Node value

ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE CDATA_SECTION_NODE ENTITY_REFERENCE_NODE ENTITY_NODE PROCESSING_INSTRUCTION_NODE

The element’s tag name The attribute name “#text” “#cdata-section” The name of the referenced entity The entity name The target of the PI

COMMENT_NODE

“#comment”

DOCUMENT_NODE DOCUMENT_TYPE_NODE DOCUMENT_FRAGMENT_NODE NOTATION_NODE

“#document” The document type name “#document-fragment” The notation name

null The attribute value The text of the node The text of the node null null The remainder of the PI The text of the comment null null null null

In documents that use namespaces, the getNodeName() method of a Element or Attr node returns the qualified node name, which may include a namespace prefix. In documents that use namespaces, you may prefer to use the namespace-aware methods getNamespaceURI(), getLocalName() and getPrefix(). Element nodes may have a list of attributes, and the Element interface defines a number of methods for working with these attributes. In addition, however, Node defines the hasAttributes() method to determine if a node has any attributes. If it does, they can be retrieved with getAttributes(). Text content in an XML document is represented by Text nodes, which have methods for manipulating that textual content. The Node interface defines a normalize() method which has the specialized purpose of normalizing all descendants of a node by deleting empty Text nodes and coalescing adjacent Text nodes into a single combined node. Document trees usually start off in this normalized form, but modifications to the tree may result in nonnormalized documents. Most of the other interfaces in this package extend Node. Document, Element and Text are the most commonly used.

844

7 March 2002 11:40

Chapter 23 – org.w3c.dom

NodeList

public interface Node { // Public Constants public static final short ATTRIBUTE_NODE; public static final short CDATA_SECTION_NODE; public static final short COMMENT_NODE; public static final short DOCUMENT_FRAGMENT_NODE; public static final short DOCUMENT_NODE; public static final short DOCUMENT_TYPE_NODE; public static final short ELEMENT_NODE; public static final short ENTITY_NODE; public static final short ENTITY_REFERENCE_NODE; public static final short NOTATION_NODE; public static final short PROCESSING_INSTRUCTION_NODE; public static final short TEXT_NODE; // Property Accessor Methods (by property name) public abstract NamedNodeMap getAttributes(); public abstract NodeList getChildNodes(); public abstract Node getFirstChild(); public abstract Node getLastChild(); public abstract String getLocalName(); public abstract String getNamespaceURI(); public abstract Node getNextSibling(); public abstract String getNodeName(); public abstract short getNodeType(); public abstract String getNodeValue() throws DOMException; public abstract void setNodeValue(String nodeValue) throws DOMException; public abstract org.w3c.dom.Document getOwnerDocument(); public abstract Node getParentNode(); public abstract String getPrefix(); public abstract void setPrefix(String prefix) throws DOMException; public abstract Node getPreviousSibling(); // Public Instance Methods public abstract Node appendChild(Node newChild) throws DOMException; public abstract Node cloneNode(boolean deep); public abstract boolean hasAttributes(); public abstract boolean hasChildNodes(); public abstract Node insertBefore(Node newChild, Node refChild) throws DOMException; public abstract boolean isSupported(String feature, String version); public abstract void normalize(); public abstract Node removeChild(Node oldChild) throws DOMException; public abstract Node replaceChild(Node newChild, Node oldChild) throws DOMException; }

=2 =4 =8 =11 =9 =10 =1 =6 =5 =12 =7 =3

Implementations: Attr, CharacterData, org.w3c.dom.Document, DocumentFragment, DocumentType, org.w3c.dom.Element, org.w3c.dom.Entity, EntityReference, Notation, ProcessingInstruction Passed To: Too many methods to list. Returned By: Too many methods to list. Type Of: javax.imageio.metadata.IIOInvalidTreeException.offendingNode

NodeList

Java 1.4

org.w3c.dom This interface represents a read-only ordered collection of nodes that can be iterated through. getLength() returns the number of nodes in the list, and item() returns the Node

Chapter 23 – org.w3c.dom

7 March 2002 11:40

845

NodeList at a specified index in the list (the index of the first node is 0). The elements of a NodeList are always valid Node objects: a NodeList never contains null elements. Note that NodeList objects are live — they are not static but immediately reflect changes to the document tree. For example, if you have a NodeList that represents the children of a specific node, and you then delete one of those children, the child will be removed from your NodeList. Be careful when looping through the elements of a NodeList if the body of your loop makes changes to the document tree (such as deleting nodes) that may affect the contents of the NodeList! public interface NodeList { // Public Instance Methods public abstract int getLength(); public abstract Node item(int index); } Implementations: javax.imageio.metadata.IIOMetadataNode Returned By: javax.imageio.metadata.IIOMetadataNode.{getChildNodes(), getElementsByTagName(), getElementsByTagNameNS()}, org.w3c.dom.Document.{getElementsByTagName(), getElementsByTagNameNS()}, org.w3c.dom.Element.{getElementsByTagName(), getElementsByTagNameNS()}, Node.getChildNodes(), org.w3c.dom.html.HTMLDocument.getElementsByName()

Notation

Java 1.4

org.w3c.dom This interface represents a notation declared in the DTD of an XML document. In XML notations are used to specify the format of an unparsed entity or to formally declare a processing instruction target. The getNodeName() method of the Node interface returns the name of the notation. getSystemId() and getPublicId() return the system identifier and the public identifier specified in the notation declaration. The getNotations() method of the DocumentType interface returns a NamedNodeMap of Notation objects declared in the DTD and provides a way to look up Notation objects by notation name. Because notations appear in the DTD and not the document itself, Notation nodes are never part of the document tree, and the getParentNode() method always returns null. Similarly, since XML notation declarations never have any content, a Notation node never has children and getChildNodes() always returns null. Notation objects are read-only and cannot be modified in any way. Node

Notation

public interface Notation extends Node { // Public Instance Methods public abstract String getPublicId(); public abstract String getSystemId(); }

ProcessingInstruction

Java 1.4

org.w3c.dom This interface represents an XML processing instruction (or PI) which specifies an arbitrary string of data to a named target processor. The getTarget() and getData() methods return the target and data portions of a PI, and these values can also be obtained using the getNodeName() and getNodeValue() methods of the Node interface. You can alter the

846

7 March 2002 11:40

Chapter 23 – org.w3c.dom

Text data portion of a PI with setData() or with the setNodeValue() method of Node. ProcessingInstruction nodes never have children. Node

ProcessingInstruction

public interface ProcessingInstruction extends Node { // Public Instance Methods public abstract String getData(); public abstract String getTarget(); public abstract void setData(String data) throws DOMException; } Returned By: org.w3c.dom.Document.createProcessingInstruction()

Text

Java 1.4

org.w3c.dom A Text node represents a run of plain text that does not contain any XML markup. Plain text appears within XML elements and attributes, and Text nodes typically appear as children of Element and Attr nodes. Text nodes inherit from CharacterData, and the textual content of a Text node is available through the getData() method inherited from CharacterData or through the getNodeValue() method inherited from Node. Text nodes may be manipulated using any of the methods inherited from CharacterData. The Text interface defines one method of its own: splitText() splits a Text node at the specified character position. The method changes the original node so that it contains only the text up to the specified position. Then it creates a new Text node that contains the text from the specified position on and inserts that new node into the document tree immediately after the original one. The Node.normalize() method reverses this process by deleting empty Text nodes and merging adjacent Text nodes into a single node. Text nodes never have children. Node

CharacterData

Text

public interface Text extends CharacterData { // Public Instance Methods public abstract Text splitText(int offset) throws DOMException; } Implementations: CDATASection Returned By: org.w3c.dom.Document.createTextNode(), Text.splitText()

Chapter 23 – org.w3c.dom

7 March 2002 11:40

847

CHAPTER 24

org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

This chapter documents the org.xml.sax package and its subpackages. org.xml.sax defines the Simplified API for XML, or SAX, a de facto standard for parsing XML documents. The org.xml.sax.ext package defines optional extensions to the SAX API, and the org.xml.sax.helpers package defines helper classes that are often useful with SAX. These packages have been incorporated into Java 1.4 but are not defined by Sun, which is why they have an “org.xml” prefix rather than a “java” prefix.

Package org.xml.sax

Java 1.4

This is the core package for SAX parsing of XML documents. SAX is an “event-driven” API: a SAX parser reads an XML document and generates a stream of “SAX events” to describe the content of the document. These “events” are actually method calls made on one or more handler objects that the application has registered with the parser. The XMLReader interface defines the API that must be implemented by a SAX parser. ContentHandler, ErrorHandler, EntityResolver, and DTDHandler are interfaces that define handler objects. An application registers objects that implement one or more of these interfaces with the XMLReader. This package defines both the SAX1 and SAX2 interfaces. The AttributeList, DocumentHandler and Parser interfaces, as well as the HandlerBase class are part of the SAX1 API and are now deprecated in favor of Attributes, ContentHandler, XMLReader and org.xml.sax.helpers.DefaultHandler. Interfaces: public interface AttributeList; public interface Attributes; public interface ContentHandler; public interface DocumentHandler; public interface DTDHandler; public interface EntityResolver; public interface ErrorHandler ;

848

7 March 2002 11:41

Attributes public interface Locator; public interface Parser ; public interface XMLFilter extends XMLReader; public interface XMLReader; Classes: public class HandlerBase implements DocumentHandler, DTDHandler, EntityResolver, ErrorHandler; public class InputSource; Exceptions: public class SAXException extends Exception; public class SAXNotRecognizedException extends SAXException; public class SAXNotSupportedException extends SAXException; public class SAXParseException extends SAXException;

AttributeList

Java 1.4; Deprecated in Java 1.4

org.xml.sax This interface is part of the SAX1 API and has been deprecated in favor of the SAX2 Attributes interface, which supports XML namespaces. public interface AttributeList { // Public Instance Methods public abstract int getLength(); public abstract String getName(int i); public abstract String getType(String name); public abstract String getType(int i); public abstract String getValue(String name); public abstract String getValue(int i); } Implementations: org.xml.sax.helpers.AttributeListImpl Passed To: DocumentHandler.startElement(), HandlerBase.startElement(), org.xml.sax.helpers.AttributeListImpl.{AttributeListImpl(), setAttributeList()}, org.xml.sax.helpers.ParserAdapter.startElement()

Attributes

Java 1.4

org.xml.sax This interface represents a list of attributes of an XML element and includes information about the attribute names, types, and values. If the SAX parser has read a DTD or schema for the document, this list of attributes will include attributes that are not explicitly specified in the document but which have a default value specified in the DTD or schema. The most commonly used method is getValue(), which returns the value of a named attribute (there is also a version of this method that returns the value of a numbered attribute; it is discussed later). If the SAX parser is not processing namespaces, you can use the one-argument version of getValue(). Otherwise, use the two argument version to specify the URI that uniquely identifies the namespace, and the “local name” of the desired attribute within that namespace. The getType() methods are similar, except that they return the type of the named attribute, rather than its value. Note that getType() can only return useful information if the parser has read a DTD or schema for the document and knows the type of each attribute.

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

849

Attributes In XML documents the attributes of a tag can appear in any order. Attributes objects make no attempt to preserve the document source order of the tags. Nevertheless, it does impose an ordering on the attributes so that you can loop through them. getLength() returns the number of elements in the list. There are versions of getValue() and getType() that return the value and type of the attribute at a specified position in the list. You can also query the name of the attribute at a specified position, although the way you do this depends on whether the parser handles namespaces or not. If it does not process namespaces, use getQName() to get the name at a specified position. Otherwise, use getURI() and getLocalName() to obtain the URI and local name pair for the numbered attribute. Note that getQName() may return the empty string when namespace processing is on, and getLocalName() may return the empty string if namespace processing is off. public interface Attributes { // Public Instance Methods public abstract int getIndex(String qName); public abstract int getIndex(String uri, String localPart); public abstract int getLength(); public abstract String getLocalName(int index); public abstract String getQName(int index); public abstract String getType(String qName); public abstract String getType(int index); public abstract String getType(String uri, String localName); public abstract String getURI(int index); public abstract String getValue(String qName); public abstract String getValue(int index); public abstract String getValue(String uri, String localName); } Implementations: org.xml.sax.helpers.AttributesImpl Passed To: org.xml.sax.ContentHandler.startElement(), org.xml.sax.helpers.AttributesImpl.{AttributesImpl(), setAttributes()}, org.xml.sax.helpers.DefaultHandler.startElement(), org.xml.sax.helpers.XMLFilterImpl.startElement(), org.xml.sax.helpers.XMLReaderAdapter.startElement()

ContentHandler

Java 1.4

org.xml.sax This interface is the key one for XML parsing with the SAX API. An XMLReader tells your application about the content of the XML document it is parsing by invoking the various methods of the ContentHandler interface. In order to parse documents with SAX, you must implement this interface to define methods that take whatever actions are necessary when they are invoked by the parser. Because this interface is so critical to the SAX API, the methods are explained individually: setDocumentLocator() The parser usually calls this method (but is not required to do so) before calling any others to pass a Locator object to the ContentHandler. Locator defines methods that return the current line and column number of the document being parsed, and if the parser supplies a Locator object, it guarantees that its methods will return valid values during any other ContentHandler invocations that follow. A ContentHandler can call the methods of this object when printing error messages, for example. startDocument(), endDocument() The parser calls these methods once, at the beginning and end of parsing. startDocument() is the first method called except for the optional setDocumentLocator() call, and endDocument() is always the last method call on a ContentHandler.

850

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

ContentHandler startElement(), endElement() The parser calls these methods for each start tag and end tag it encounters. Both are passed three arguments describing the name of the tag: if the parser is doing namespace processing, then the first two arguments of both methods return the URI that uniquely identifies the namespace, and the local name of the tag within that namespace. If the parser is not doing namespace parsing, then the third argument provides the full name of the tag. In addition to these tag name arguments, startElement() is also passed an Attributes object that describes the attributes of the tag. characters() This method is invoked to tell the application that the parser has found a string of text in the XML document. The text is contained within the specified character array, at the specified start position, and continuing for the specified number of characters. ignorableWhitespace() This method is like characters(), but parsers may use it to tell the application about “ignorable whitespace” in XML element content. processingInstruction() The parser calls this method to tell the application that it has encountered an XML Processing Instruction (or PI) with the specified target and data strings. skippedEntity() If the XML parser does encounters an entity in the document, but does not expand and parse its content, then it tells the application about it by passing the name of the entity to this method. startPrefixMapping(), endPrefixMapping() These methods to tell the application about a namespace mapping from the specified prefix to the specified namespace URI. DTDHandler is another interface like ContentHandler. An application can implement this interface to receive notification of DTD-related events from the parser. Similarly, the org.xml.sax.ext package defines two “extension” interfaces that can be used (if the parser supports these extensions) to obtain even more information about the document (such as comments and CDATA sections) and about the DTD (including the full set of element, attribute and entity declarations). The org.xml.sax.helpers.DefaultHandler class is a useful one. It implements ContentHandler and three other interfaces that are commonly used with the XMLReader class and provides empty implementations of all their methods. Applications can subclass DefaultHandler only need to override the methods they care about. This is usually more convenient that implementing the interfaces directly. public interface ContentHandler { // Public Instance Methods public abstract void characters(char[ ] ch, int start, int length) throws SAXException; public abstract void endDocument() throws SAXException; public abstract void endElement(String namespaceURI, String localName, String qName) throws SAXException; public abstract void endPrefixMapping(String prefix) throws SAXException; public abstract void ignorableWhitespace(char[ ] ch, int start, int length) throws SAXException; public abstract void processingInstruction(String target, String data) throws SAXException; public abstract void setDocumentLocator(Locator locator); public abstract void skippedEntity(String name) throws SAXException; public abstract void startDocument() throws SAXException; public abstract void startElement(String namespaceURI, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException;

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

851

ContentHandler

public abstract void startPrefixMapping(String prefix, String uri) throws SAXException; } Implementations: javax.xml.transform.sax.TemplatesHandler, javax.xml.transform.sax.TransformerHandler, org.xml.sax.helpers.DefaultHandler, org.xml.sax.helpers.XMLFilterImpl, org.xml.sax.helpers.XMLReaderAdapter Passed To: javax.xml.transform.sax.SAXResult.{SAXResult(), setHandler()}, XMLReader.setContentHandler(), org.xml.sax.helpers.ParserAdapter.setContentHandler(), org.xml.sax.helpers.XMLFilterImpl.setContentHandler() Returned By: javax.xml.transform.sax.SAXResult.getHandler(), XMLReader.getContentHandler(), org.xml.sax.helpers.ParserAdapter.getContentHandler(), org.xml.sax.helpers.XMLFilterImpl.getContentHandler()

DocumentHandler

Java 1.4; Deprecated in Java 1.4

org.xml.sax This interface is part of the SAX1 API and has been deprecated in favor of the SAX2 ContentHandler interface, which supports XML namespaces. public interface DocumentHandler { // Public Instance Methods public abstract void characters(char[ ] ch, int start, int length) throws SAXException; public abstract void endDocument() throws SAXException; public abstract void endElement(String name) throws SAXException; public abstract void ignorableWhitespace(char[ ] ch, int start, int length) throws SAXException; public abstract void processingInstruction(String target, String data) throws SAXException; public abstract void setDocumentLocator(Locator locator); public abstract void startDocument() throws SAXException; public abstract void startElement(String name, org.xml.sax.AttributeList atts) throws SAXException; } Implementations: HandlerBase, org.xml.sax.helpers.ParserAdapter Passed To: org.xml.sax.Parser.setDocumentHandler(), org.xml.sax.helpers.XMLReaderAdapter.setDocumentHandler()

DTDHandler

Java 1.4

org.xml.sax This interface defines methods that an application can implement in order to receive notification from a XMLReader about notation and unparsed entity declarations in the DTD of an XML document. Notations and unparsed entities are two of the most obscure features of XML, and they (and this interface) are not frequently used. To use a DTDHandler, define a class that implements the interface, (or simply subclass the helper class org.xml.sax.helpers.DefaultHandler) and pass an instance of that class to the setDTDHandler() method of an XMLReader. Then, if the parser encounters any notation or unparsed entity declarations in the DTD of the document, it will invoke the notationDecl() or unparsedEntityDecl() method that you have supplied. Unparsed entities can appear later in a document as the value of an attribute, so if your application cares about them, it should somehow make a note of the entity name and system ID for later use. public interface DTDHandler { // Public Instance Methods public abstract void notationDecl(String name, String publicId, String systemId) throws SAXException;

852

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

ErrorHandler

public abstract void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException; } Implementations: javax.xml.transform.sax.TransformerHandler, HandlerBase, org.xml.sax.helpers.DefaultHandler, org.xml.sax.helpers.XMLFilterImpl Passed To: org.xml.sax.Parser.setDTDHandler(), XMLReader.setDTDHandler(), org.xml.sax.helpers.ParserAdapter.setDTDHandler(), org.xml.sax.helpers.XMLFilterImpl.setDTDHandler(), org.xml.sax.helpers.XMLReaderAdapter.setDTDHandler() Returned By: XMLReader.getDTDHandler(), org.xml.sax.helpers.ParserAdapter.getDTDHandler(), org.xml.sax.helpers.XMLFilterImpl.getDTDHandler()

EntityResolver

Java 1.4

org.xml.sax An application can implement this interface to help the parser resolve external entities, if required. If you pass an EntityResolver instance to the setEntityResolver() method of an XMLReader, then the parser will call the resolveEntity() method whenever it needs to read an external entity. This method should use the public identifier or system identifier to return an InputSource that the parser can use to read the content of the external entity. If the external entity includes a valid system identifier, then the parser can read it directly without the need for an EntityResolver, but this interface is still useful for mapping network URLs to locally cached copies, or for mapping public identifiers to local files, for example. The helper class org.xml.sax.helpers.DefaultHandler includes a stub implementation of this interface, so if you subclass DefaultHandler you can override its resolveEntity() method. public interface EntityResolver { // Public Instance Methods public abstract InputSource resolveEntity(String publicId, String systemId) throws SAXException, java.io.IOException; } Implementations: HandlerBase, org.xml.sax.helpers.DefaultHandler, org.xml.sax.helpers.XMLFilterImpl Passed To: javax.xml.parsers.DocumentBuilder.setEntityResolver(), org.xml.sax.Parser.setEntityResolver(), XMLReader.setEntityResolver(), org.xml.sax.helpers.ParserAdapter.setEntityResolver(), org.xml.sax.helpers.XMLFilterImpl.setEntityResolver(), org.xml.sax.helpers.XMLReaderAdapter.setEntityResolver() Returned By: XMLReader.getEntityResolver(), org.xml.sax.helpers.ParserAdapter.getEntityResolver(), org.xml.sax.helpers.XMLFilterImpl.getEntityResolver()

ErrorHandler

Java 1.4

org.xml.sax Before parsing an XML document, an application should provide an implementation of this interface to the XMLReader by calling the setErrorHandler() method of the XMLReader. If the reader needs to issue a warning or report an error or fatal error, it will call the appropriate method of the ErrorHandler object you supplied. The error() method is used to report recoverable errors, such as document validity problems. The parser continues parsing after calling error(). The fatalError() method is used to report nonrecoverable errors, such as well-formedness problems. The parser may not continue parsing after

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

853

ErrorHandler calling fatalError(). An ErrorHandler object may respond to warnings, errors, and fatal errors however it likes, and may throw exceptions from these methods. Instead of implementing this interface directly, you may also subclass the helper class org.xml.sax.helpers.DefaultHandler and override the error reporting methods it provides. The warning() and error() methods of a DefaultHandler do nothing, and the fatalError() method throws the SAXParseException object that was passed to it. public interface ErrorHandler { // Public Instance Methods public abstract void error(SAXParseException exception) throws SAXException; public abstract void fatalError(SAXParseException exception) throws SAXException; public abstract void warning(SAXParseException exception) throws SAXException; } Implementations: HandlerBase, org.xml.sax.helpers.DefaultHandler, org.xml.sax.helpers.XMLFilterImpl Passed To: javax.xml.parsers.DocumentBuilder.setErrorHandler(), org.xml.sax.Parser.setErrorHandler(), XMLReader.setErrorHandler(), org.xml.sax.helpers.ParserAdapter.setErrorHandler(), org.xml.sax.helpers.XMLFilterImpl.setErrorHandler(), org.xml.sax.helpers.XMLReaderAdapter.setErrorHandler() Returned By: XMLReader.getErrorHandler(), org.xml.sax.helpers.ParserAdapter.getErrorHandler(), org.xml.sax.helpers.XMLFilterImpl.getErrorHandler()

HandlerBase

Java 1.4; Deprecated in Java 1.4

org.xml.sax This class is part of the SAX1 API and has been deprecated in favor of the SAX2 org.xml.sax.helpers.DefaultHandler class. Object DTDHandler

HandlerBase DocumentHandler

EntityResolver

ErrorHandler

public class HandlerBase implements DocumentHandler, DTDHandler, EntityResolver, ErrorHandler { // Public Constructors public HandlerBase(); // Methods Implementing DocumentHandler public void characters(char[ ] ch, int start, int length) throws SAXException; public void endDocument() throws SAXException; public void endElement(String name) throws SAXException; public void ignorableWhitespace(char[ ] ch, int start, int length) throws SAXException; public void processingInstruction(String target, String data) throws SAXException; public void setDocumentLocator(Locator locator); public void startDocument() throws SAXException; public void startElement(String name, org.xml.sax.AttributeList attributes) throws SAXException; // Methods Implementing DTDHandler public void notationDecl(String name, String publicId, String systemId); public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName); // Methods Implementing EntityResolver public InputSource resolveEntity(String publicId, String systemId) throws SAXException; // Methods Implementing ErrorHandler public void error(SAXParseException e) throws SAXException; public void fatalError(SAXParseException e) throws SAXException; public void warning(SAXParseException e) throws SAXException; }

854

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

empty empty empty empty empty empty empty empty empty empty constant empty empty

InputSource Passed To: javax.xml.parsers.SAXParser.parse()

InputSource

Java 1.4

org.xml.sax This simple class describes a source of input for an XMLReader. An InputSource object can be passed to the parse() method of XMLReader, and is also the return value of the EntityResolver.resolveEntity() method. Create an InputSource() with one of the constructor methods, specifying the system identifier (a URL) of the file to be parsed, or specifying a byte or character stream that the parser should read the document from. In addition to calling the constructor, you may also want to call setSystemId() to specify and/or setPublicId() to provide identifiers for the document being parsed. Having a filename or URL is useful if an error arises, and your ErrorHandler object needs to print an error message, for example. If you specify the document to parse as a URL or as a byte stream, you can also call setEncoding() to specify the character encoding of the document. The parser will use this encoding value if you supply it, but XML documents are supposed to describe their own encoding in the declaration, so the parser ought to be able to determine the encoding of the document even if you do not call setEncoding(). This class allows you to specify more than one input source. The XMLReader will first call getCharacterStream() and use the returned Reader if there is one. If that method returns false, then it calls getByteStream() and uses the InputStream it returns. Finally, if no character or byte stream is found, then the parser will call getSystemId() and will attempt to read an XML document from the returned URL. An XMLReader will never use any of the set() methods to modify the state of an InputSource object. public class InputSource { // Public Constructors public InputSource(); public InputSource(java.io.Reader characterStream); public InputSource(java.io.InputStream byteStream); public InputSource(String systemId); // Property Accessor Methods (by property name) public java.io.InputStream getByteStream(); public void setByteStream(java.io.InputStream byteStream); public java.io.Reader getCharacterStream(); public void setCharacterStream(java.io.Reader characterStream); public String getEncoding(); public void setEncoding(String encoding); public String getPublicId(); public void setPublicId(String publicId); public String getSystemId(); public void setSystemId(String systemId); }

default:null default:null default:null default:null default:null

Passed To: javax.xml.parsers.DocumentBuilder.parse(), javax.xml.parsers.SAXParser.parse(), javax.xml.transform.sax.SAXSource.{SAXSource(), setInputSource()}, org.xml.sax.Parser.parse(), XMLReader.parse(), org.xml.sax.helpers.ParserAdapter.parse(), org.xml.sax.helpers.XMLFilterImpl.parse(), org.xml.sax.helpers.XMLReaderAdapter.parse() Returned By: javax.xml.transform.sax.SAXSource.{getInputSource(), sourceToInputSource()}, EntityResolver.resolveEntity(), HandlerBase.resolveEntity(), org.xml.sax.helpers.DefaultHandler.resolveEntity(), org.xml.sax.helpers.XMLFilterImpl.resolveEntity()

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

855

Locator

Locator

Java 1.4

org.xml.sax An XMLReader may pass an object that implements this interface to the application by calling the setDocumentLocator() method of the application’s ContentHandler object before it invokes any other methods of that ContentHandler. The ContentHandler can use methods of this Locator object from within any of the other methods called by the parser in order to determine what document the parser is parsing and what line number and column number it is parsing at. This information is particularly useful when displaying error or warning messages, for example. getSystemId() and getPublicId() return the system and public identifiers of the document being parsed, if this information is available to the parser, and otherwise return null. getLineNumber() and getColumnNumber() return the line number and column number of the next character that the parser will read (line and column numbers are numbered starting at 1, not at 0). The parser is allowed to return an approximate value from these methods, or to return –1 if it does not track line and column numbers. public interface Locator { // Public Instance Methods public abstract int getColumnNumber(); public abstract int getLineNumber(); public abstract String getPublicId(); public abstract String getSystemId(); } Implementations: org.xml.sax.helpers.LocatorImpl Passed To: org.xml.sax.ContentHandler.setDocumentLocator(), DocumentHandler.setDocumentLocator(), HandlerBase.setDocumentLocator(), SAXParseException.SAXParseException(), org.xml.sax.helpers.DefaultHandler.setDocumentLocator(), org.xml.sax.helpers.LocatorImpl.LocatorImpl(), org.xml.sax.helpers.ParserAdapter.setDocumentLocator(), org.xml.sax.helpers.XMLFilterImpl.setDocumentLocator(), org.xml.sax.helpers.XMLReaderAdapter.setDocumentLocator()

Parser

Java 1.4; Deprecated in Java 1.4

org.xml.sax This interface is part of the SAX1 API and has been deprecated in favor of the SAX2 XMLReader interface, which supports XML namespaces. public interface Parser { // Public Instance Methods public abstract void parse(InputSource source) throws SAXException, java.io.IOException; public abstract void parse(String systemId) throws SAXException, java.io.IOException; public abstract void setDocumentHandler(DocumentHandler handler); public abstract void setDTDHandler(DTDHandler handler); public abstract void setEntityResolver(EntityResolver resolver); public abstract void setErrorHandler(ErrorHandler handler); public abstract void setLocale(java.util.Locale locale) throws SAXException; } Implementations: org.xml.sax.helpers.XMLReaderAdapter Passed To: org.xml.sax.helpers.ParserAdapter.ParserAdapter() Returned By: javax.xml.parsers.SAXParser.getParser(), org.xml.sax.helpers.ParserFactor y.makeParser()

856

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

SAXNotSupportedException

SAXException

Java 1.4 serializable checked

org.xml.sax

This signals a problem while parsing an XML document. This class serves as the general superclass for more specific types of SAX exceptions. The parse() method of an XMLReader can throw an exception of this type. The application can also throw a SAXException from any of the handler methods (of ContentHandler and ErrorHandler, for example) invoked by the parser. Object

Throwable

Exception

SAXException

Serializable

public class SAXException extends Exception { // Public Constructors public SAXException(String message); public SAXException(Exception e); public SAXException(String message, Exception e); // Public Instance Methods public Exception getException(); // Public Methods Overriding Throwable public String getMessage(); public String toString(); } Subclasses: SAXNotRecognizedException, SAXNotSupportedException, SAXParseException Thrown By: Too many methods to list.

SAXNotRecognizedException

Java 1.4 serializable checked

org.xml.sax

This signals that the parser does not recognize a feature or property name. See the setFeature() and setProperty() methods of XMLReader. Object

Throwable

Exception

SAXException

SAXNotRecognizedException

Serializable

public class SAXNotRecognizedException extends SAXException { // Public Constructors public SAXNotRecognizedException(String message); } Thrown By: Too many methods to list.

SAXNotSupportedException

Java 1.4 serializable checked

org.xml.sax

This signals that the parser recognizes, but does not support, a named feature or property. The property or feature may be entirely unsupported, or it may be read-only, in which case this exception will be thrown by the setFeature() or setProperty() method, but not by the corresponding getFeature() or getProperty() method of XMLReader. Object

Throwable

Exception

SAXException

SAXNotSupportedException

Serializable

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

857

SAXNotSupportedException

public class SAXNotSupportedException extends SAXException { // Public Constructors public SAXNotSupportedException(String message); } Thrown By: Too many methods to list.

SAXParseException

Java 1.4 serializable checked

org.xml.sax

An exception of this type signals an XML parsing error or warning. SAXParseException includes methods to return the system and public identifiers of the document in which the error or warning occurred, as well as methods to return the approximate line number and column number at which it occurred. A parser is not required to obtain or track all of this information, and the methods may return null or –1 if the information is not available. (See Locator for more information.) Exceptions of this type are usually thrown by the application from the methods of the ErrorHandler interface. The parser never throws a SAXParseException itself, but does pass an appropriately initialized instance of this class to each of the ErrorHandler methods. It is up to the application’s ErrorHandler object to decide whether to actually throw the exception, however. Object

Throwable

Exception

SAXException

SAXParseException

Serializable

public class SAXParseException extends SAXException { // Public Constructors public SAXParseException(String message, Locator locator); public SAXParseException(String message, Locator locator, Exception e); public SAXParseException(String message, String publicId, String systemId, int lineNumber, int columnNumber); public SAXParseException(String message, String publicId, String systemId, int lineNumber, int columnNumber, Exception e); // Public Instance Methods public int getColumnNumber(); public int getLineNumber(); public String getPublicId(); public String getSystemId(); } Passed To: ErrorHandler.{error(), fatalError(), warning()}, HandlerBase.{error(), fatalError(), warning()}, org.xml.sax.helpers.DefaultHandler.{error(), fatalError(), warning()}, org.xml.sax.helpers.XMLFilterImpl.{error(), fatalError(), warning()}

XMLFilter

Java 1.4

org.xml.sax An XMLFilter extends XMLReader and behaves like an XMLReader except that instead of parsing a document itself, it filters the SAX events provided by a “parent” XMLReader object. Use the setParent() method to link an XMLFilter object to the XMLReader that it is to serve as a filter for. An XMLFilter serves as both a source of SAX events, and also as a recipient of those events, so an implementation must implement ContentHandler and related interfaces so that it can obtain events from the parent object, filter them, and then pass the filtered events on to the ContentHandler object that was registered on the filter. See the helper class org.xml.sax.helpers.XMLFilterImpl for a bare-bones implementation of an XMLFilter that

858

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

XMLReader implements the XMLReader interface and the ContentHandler and related handler interfaces. XMLFilterImpl does no filtering—it simply passes passes all of its method invocations through. You can subclass it and override only the methods that need filtering. XMLReader

XMLFilter

public interface XMLFilter extends XMLReader { // Public Instance Methods public abstract XMLReader getParent(); public abstract void setParent(XMLReader parent); } Implementations: org.xml.sax.helpers.XMLFilterImpl Returned By: javax.xml.transform.sax.SAXTransformerFactor y.newXMLFilter()

XMLReader

Java 1.4

org.xml.sax This interface defines the methods that must be implemented by a SAX2 XML parser. Since it is an interface, XMLReader cannot define a constructor for creating an XMLReader. To obtain an XMLReader, object, you can instantiate some implementation-specific class that implements this interface. Alternatively, you can keep your code independent of any specific parser implementation by using the SAXParserFactor y and SAXParser classes of the javax.xml.parsers package. See those classes for more details. Note that the XMLReader interface has no relationship to the java.io.Reader class or any other character stream classes. Once you have obtained an XMLReader instance, you must register handler objects on it, so that it can invoke methods on those handlers to notify your application of the results of its parsing. All applications should register a ContentHandler and an ErrorHandler with setContentHandler() and setErrorHandler(). Some applications may also want to register an EntityResolver and/or a DTDHandler. Applications can also register DeclHandler and LexicalHandler objects from the org.xml.sax.ext package, if the parser implementation supports these extension handler interfaces. DeclHandler and LexicalHandler objects are registered with setProperty(), as explained below. In addition to registering handler objects for an XMLReader, you may also want to configure the behavior of the parser using setFeature() and setProperty(). Features and properties are both name/value pairs. For uniqueness, the names of features and properties are expressed as URLs (the URLs usually do not have any web content associated with them: they are merely unique identifiers). Features have boolean values, and properties have arbitrary object values. Features and properties are an extension mechanism, allowing an application to specify implementation-specific details about how the parser should behave. But there are also several “standard” features and properties that are supported by many (or all) SAX parsers. They are listed below. If a parser does not recognize the name of a feature or property, the setFeature() and setProperty() methods (as well as the corresponding getFeature() and getProperty() query methods) throw a SAXNotRecognizedException. If the parser recognizes the name of a feature or property, but does not support the feature or property, the methods instead throw a SAXNotSupportedException. This exception is also thrown by the set methods when the parser allows the feature or property to be queried but not set. The standard features are the following. Their names are all URLs that begin with the prefix “http://www.xml.org/sax/features/”. For brevity, this prefix has been omitted

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

859

XMLReader below. Note that only two of these features must be supported by all parsers. The others may or may not be supported in any given implementation: namespaces If true (the default), the parser supports namespaces and provides the namespace URI and localname for element and attribute names. Support for this feature is required in all parser implementations. namespace-prefixes If true, the parser provides the qualified name (or “qName”) that for element and attribute names. A qName consists of a namespace prefix, a colon, and the local name. The default value of this feature is false, and support for the feature is required in all parser implementations. validation If true, the parser will validate XML documents, and will read all external entities. external-general-entities If true, the parser handles external general entities. This is always true if the validation feature is true. external-parameter-entities If true, the parser handles external parameter entities. This is always true if the validation feature is true. lexical-handler/parameter-entities If true, the parser will report the beginning and end of parameter entities to the LexicalHandler extension interface. string-interning If true, the parser will use the String.intern() method for all strings (element, attribute, entity and notation names, and namespace prefixes and URIs) it returns. If the application does the same, it can use == equality testing for these strings rather than using the more expensive equals() method. The standard properties are the following. Like the features, their names are all URLs that begin with the prefix “http://www.xml.org/sax/properties/” (omitted in the following list). Note that support for all of these properties is optional. declaration-handler An org.xml.sax.ext.DeclHandler object to which the parser will report the contents of the DTD. lexical-handler An org.xml.sax.ext.LexicalHandler object on which the parser will make method calls to describe the lexical structure (such as comments and CDATA sections) of the XML document. xml-string This is a read-only property that can be queried only from within a handler method invoked by the parser. The value of this property is a String that contains the document content that triggered the current handler invocation. dom-node An XMLReader that “parses” a DOM tree rather than the textual form of an XML document uses the value of this property as the org.w3c.dom.Node object at which it should begin parsing.

860

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

Package org.xml.sax.ext Finally, after you have obtained an XMLReader object, have queried and configured its features and properties, and have set a ContentHandler, ErrorHandler, and any other required handler objects, you are ready to parse an XML document. Do this by calling one of the parse() methods, specifying the document to parse either as a system identifier (a URL) or as an InputSource object (which also allows the use of streams). public interface XMLReader { // Public Instance Methods public abstract org.xml.sax.ContentHandler getContentHandler(); public abstract DTDHandler getDTDHandler(); public abstract EntityResolver getEntityResolver(); public abstract ErrorHandler getErrorHandler(); public abstract boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException; public abstract Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException; public abstract void parse(String systemId) throws java.io.IOException, SAXException; public abstract void parse(InputSource input) throws java.io.IOException, SAXException; public abstract void setContentHandler(org.xml.sax.ContentHandler handler); public abstract void setDTDHandler(DTDHandler handler); public abstract void setEntityResolver(EntityResolver resolver); public abstract void setErrorHandler(ErrorHandler handler); public abstract void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException; public abstract void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException; } Implementations: XMLFilter, org.xml.sax.helpers.ParserAdapter Passed To: javax.xml.transform.sax.SAXSource.{SAXSource(), setXMLReader()}, XMLFilter.setParent(), org.xml.sax.helpers.XMLFilterImpl.{setParent(), XMLFilterImpl()}, org.xml.sax.helpers.XMLReaderAdapter.XMLReaderAdapter() Returned By: javax.xml.parsers.SAXParser.getXMLReader(), javax.xml.transform.sax.SAXSource.getXMLReader(), XMLFilter.getParent(), org.xml.sax.helpers.XMLFilterImpl.getParent(), org.xml.sax.helpers.XMLReaderFactor y.createXMLReader()

Package org.xml.sax.ext

Java 1.4

This package defines extensions to the basic SAX2 API. Neither SAX parsers nor SAX applications are required to support these extensions, but when they do, the interfaces defined here provide a standard way for the parser to provide additional information about an XML document to the application. DeclHandler defines methods for reporting the content of a DTD, and LexicalHandler defines methods for reporting the lexical structure of an XML document. At the time of this writing, a “SAX2 Extensions 1.1” release is in preparation. The current beta version adds three new interfaces to this package: Attributes2, EntityResolver2, and Locator2. Because these new extensions are not yet released, they are not documented here. See http://www.saxproject.org for details. Interfaces: public interface DeclHandler; public interface LexicalHandler;

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

861

DeclHandler

DeclHandler

Java 1.4

org.xml.sax.ext This extension interface defines methods that a SAX parser can call to notify an application about element, attribute, and entity declarations in a DTD. If your application requires this information about a DTD, then pass an object that implements this interface to the setProperty() method of an XMLReader, using the property name “http://www.xml.org/sax/properties/declaration-handler”. Because this is an extension handler, SAX parsers are not required to support it, and may throw a SAXNotRecognizedException or a SAXNotSupportedException when you attempt to register a DeclHandler. public interface DeclHandler { // Public Instance Methods public abstract void attributeDecl(String eName, String aName, String type, String valueDefault, String value) throws org.xml.sax.SAXException; public abstract void elementDecl(String name, String model) throws org.xml.sax.SAXException; public abstract void externalEntityDecl(String name, String publicId, String systemId) throws org.xml.sax.SAXException; public abstract void internalEntityDecl(String name, String value) throws org.xml.sax.SAXException; }

LexicalHandler

Java 1.4

org.xml.sax.ext This extension interface defines methods that a SAX parser can call to notify an application about the lexical structure of an XML document. If your application requires this kind of information (for example if it wants to create a new document that has a similar structure to the one it reads), then pass an object that implements this interface to the setProperty() method of an XMLReader, using the property name “http://www.xml.org/sax/ properties/lexical-handler”. Because this is an extension handler, SAX parsers are not required to support it, and may throw a SAXNotRecognizedException or a SAXNotSupportedException when you attempt to register a DeclHandler. If a LexicalHandler is successfully registered on an XMLReader, then the parser will call startDTD() and endDTD() to report the beginning and end of the document’s DTD. It will call startCDATA() and endCDATA() to report the start and end of a CDATA section. The content of the CDATA section will be reported through the characters() method of the ContentHandler interface. When the parser expands an entity, it first calls startEntity() to specify the name of the entity it is about to expand, and then calls endEntity() when the entity expansion is complete. Finally, whenever the parser encounters an XML comment, it calls the comment() method. public interface LexicalHandler { // Public Instance Methods public abstract void comment(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; public abstract void endCDATA() throws org.xml.sax.SAXException; public abstract void endDTD() throws org.xml.sax.SAXException; public abstract void endEntity(String name) throws org.xml.sax.SAXException; public abstract void startCDATA() throws org.xml.sax.SAXException; public abstract void startDTD(String name, String publicId, String systemId) throws org.xml.sax.SAXException; public abstract void startEntity(String name) throws org.xml.sax.SAXException; } Implementations: javax.xml.transform.sax.TransformerHandler Passed To: javax.xml.transform.sax.SAXResult.setLexicalHandler()

862

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

AttributeListImpl Returned By: javax.xml.transform.sax.SAXResult.getLexicalHandler()

Package org.xml.sax.helpers

Java 1.4

This package contains utility classes that are useful for programmers working with SAX parsers. DefaultHandler is the most commonly used: it is a default implementation of the four standard handler interfaces, suitable for easy subclassing by an application. XMLReaderFactor y provides a layer implementation-independence, allowing an application to use an XMLReader implementation specified in a system property. XMLFilterImpl is a no-op implementation of the XMLFilter interface that also implements the various handler interfaces necessary to connect the filter to its “parent” XMLReader. It does no filtering of its own, but is easy to subclass to add filtering. If you need to work with legacy APIs that expect or return SAX1 Parser objects, you can use ParserAdapter to make a Parser object behave like a SAX2 XMLReader object, or use an XMLReaderAdapter to make an XMLReader behave like a Parser. Classes: public class AttributeListImpl implements org.xml.sax.AttributeList; public class AttributesImpl implements org.xml.sax.Attributes; public class DefaultHandler implements org.xml.sax.ContentHandler, org.xml.sax.DTDHandler, org.xml.sax.EntityResolver, org.xml.sax.ErrorHandler ; public class LocatorImpl implements org.xml.sax.Locator ; public class NamespaceSupport; public class ParserAdapter implements org.xml.sax.DocumentHandler, org.xml.sax.XMLReader; public class ParserFactor y; public class XMLFilterImpl implements org.xml.sax.ContentHandler, org.xml.sax.DTDHandler, org.xml.sax.EntityResolver, org.xml.sax.ErrorHandler, org.xml.sax.XMLFilter ; public class XMLReaderAdapter implements org.xml.sax.ContentHandler, org.xml.sax.Parser ; public final class XMLReaderFactor y;

AttributeListImpl

Java 1.4; Deprecated in Java 1.4

org.xml.sax.helpers This deprecated class is an implementation of the deprecated SAX1 org.xml.sax.AttributeList interface. They have been deprecated in favor of the AttributesImpl implementation of the SAX2 org.xml.sax.Attributes interface. Object

AttributeListImpl

AttributeList

public class AttributeListImpl implements org.xml.sax.AttributeList { // Public Constructors public AttributeListImpl(); public AttributeListImpl(org.xml.sax.AttributeList atts); // Public Instance Methods public void addAttribute(String name, String type, String value); public void clear(); public void removeAttribute(String name); public void setAttributeList(org.xml.sax.AttributeList atts); // Methods Implementing AttributeList public int getLength(); public String getName(int i); public String getType(int i); public String getType(String name); public String getValue(String name);

default:0

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

863

AttributeListImpl

public String getValue(int i); }

AttributesImpl

Java 1.4

org.xml.sax.helpers This utility class is a general-purpose implementation of the Attributes interface. In addition to implementing all the methods of Attributes, it also defines various set methods for setting attribute names, values, and types, an addAttribute() method for adding a new attribute to the end of the list, a removeAttribute() method for removing an attribute from the list, and a clear() method for removing all attributes. Also, there is an AttributesImpl() constructor that initializes the new AttributesImpl object with a copy of a specified Attributes object. This class is useful for XMLFilter implementations that want to filter the attributes of an element, or for ContentHandler implementations that need to make and save a copy of an Attributes object for later use. Object

AttributesImpl

Attributes

public class AttributesImpl implements org.xml.sax.Attributes { // Public Constructors public AttributesImpl(); public AttributesImpl(org.xml.sax.Attributes atts); // Public Instance Methods public void addAttribute(String uri, String localName, String qName, String type, String value); public void clear(); public void removeAttribute(int index); public void setAttribute(int index, String uri, String localName, String qName, String type, String value); public void setAttributes(org.xml.sax.Attributes atts); public void setLocalName(int index, String localName); public void setQName(int index, String qName); public void setType(int index, String type); public void setURI(int index, String uri); public void setValue(int index, String value); // Methods Implementing Attributes public int getIndex(String qName); public int getIndex(String uri, String localName); public int getLength(); default:0 public String getLocalName(int index); public String getQName(int index); public String getType(String qName); public String getType(int index); public String getType(String uri, String localName); public String getURI(int index); public String getValue(int index); public String getValue(String qName); public String getValue(String uri, String localName); }

DefaultHandler

Java 1.4

org.xml.sax.helpers This helper class implements the four commonly-used SAX handler interfaces from the org.xml.sax package and defines stub implementations for all of their methods. It is usually easier to subclass DefaultHandler and override the desired methods than it is to implement all of the interfaces (and all of their methods) from scratch. DefaultHandler

864

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

LocatorImpl implements ContentHandler, ErrorHandler, EntityResolver and DTDHandler, so you can pass an instance of this class, (or of a subclass you define) to the setContentHandler(), setErrorHandler(), setEntityResolver(), and setDTDHandler() methods of an XMLReader. You can also pass an instance of a DefaultHandler subclass directly to one of the parse() methods of a javax.xml.parsers.SAXParser. The SAXParser will take care of calling the four relevant methods of its internal XMLReader. All but two of the methods of DefaultHandler have empty bodies and do nothing. The exceptions are resolveEntity() which simply returns null to tell the parser to resolve the entity itself, and fatalError() which throws the SAXParseException object that is passed to it. Object

DefaultHandler

ContentHandler

DTDHandler

EntityResolver

ErrorHandler

public class DefaultHandler implements org.xml.sax.ContentHandler, org.xml.sax.DTDHandler, org.xml.sax.EntityResolver, org.xml.sax.ErrorHandler { // Public Constructors public DefaultHandler(); // Methods Implementing ContentHandler public void characters(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; empty public void endDocument() throws org.xml.sax.SAXException; empty public void endElement(String uri, String localName, String qName) throws org.xml.sax.SAXException; empty public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException; empty public void ignorableWhitespace(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; empty public void processingInstruction(String target, String data) throws org.xml.sax.SAXException; empty public void setDocumentLocator(org.xml.sax.Locator locator); empty public void skippedEntity(String name) throws org.xml.sax.SAXException; empty public void startDocument() throws org.xml.sax.SAXException; empty public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes attributes) empty throws org.xml.sax.SAXException; public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException; empty // Methods Implementing DTDHandler public void notationDecl(String name, String publicId, String systemId) throws org.xml.sax.SAXException; empty public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) empty throws org.xml.sax.SAXException; // Methods Implementing EntityResolver public org.xml.sax.InputSource resolveEntity(String publicId, String systemId) constant throws org.xml.sax.SAXException; // Methods Implementing ErrorHandler public void error(org.xml.sax.SAXParseException e) throws org.xml.sax.SAXException; empty public void fatalError(org.xml.sax.SAXParseException e) throws org.xml.sax.SAXException; public void warning(org.xml.sax.SAXParseException e) throws org.xml.sax.SAXException; empty } Passed To: javax.xml.parsers.SAXParser.parse()

LocatorImpl

Java 1.4

org.xml.sax.helpers This helper class is a very simple implementation of the Locator interface. It defines a copy constructor that create a new LocatorImpl object that copies the state of a specified Locator object. This constructor is useful because it allows applications to copy the state of a Locator and save it for later use. Object

LocatorImpl

Locator

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

865

LocatorImpl

public class LocatorImpl implements org.xml.sax.Locator { // Public Constructors public LocatorImpl(); public LocatorImpl(org.xml.sax.Locator locator); // Property Accessor Methods (by property name) public int getColumnNumber(); public void setColumnNumber(int columnNumber); public int getLineNumber(); public void setLineNumber(int lineNumber); public String getPublicId(); public void setPublicId(String publicId); public String getSystemId(); public void setSystemId(String systemId); // Methods Implementing Locator public int getColumnNumber(); public int getLineNumber(); public String getPublicId(); public String getSystemId(); }

Implements:Locator default:0 Implements:Locator default:0 Implements:Locator default:null Implements:Locator default:null

NamespaceSupport

default:0 default:0 default:null default:null

Java 1.4

org.xml.sax.helpers This utility class exists to help SAX parser implementors handle XML namespaces. It is not commonly used by SAX applications. public class NamespaceSupport { // Public Constructors public NamespaceSupport(); // Public Constants public static final String XMLNS; = [quot ] http://www.w3.org/XML/1998/namespace [quot ] // Public Instance Methods public boolean declarePrefix(String prefix, String uri); public java.util.Enumeration getDeclaredPrefixes(); public String getPrefix(String uri); public java.util.Enumeration getPrefixes(); public java.util.Enumeration getPrefixes(String uri); public String getURI(String prefix); public void popContext(); public String[ ] processName(String qName, String[ ] parts, boolean isAttribute); public void pushContext(); public void reset(); }

ParserAdapter

Java 1.4

org.xml.sax.helpers This adapter class behaves like a SAX2 XMLReader object, but gets its input from the SAX1 Parser object that is passed to the constructor. In order to make this work, it implements the deprecated SAX1 DocumentHandler interface so that it can receive events from the Parser. ParserAdapter provides its own layer of namespace processing to convert a namespace-unaware Parser into a namespace-aware XMLReader. This class is useful when working you are working with a legacy API that supplies a SAX1 Parser object, but want to work with that parser using the SAX2 XMLReader API: to use it, simply pass the Parser object to the ParserAdapter() constructor and use the resulting object as you would use any other XMLReader object.

866

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

ParserFactory There is not perfect congruence between the SAX1 and SAX2 APIs, and a Parser cannot be perfectly adapted to a XMLReader. In particular, a ParserAdapter will never call the skippedEntity() handler method because the SAX1 Parser API does not provide notification of skipped entities. Also, it does not attempt to determine whether two namespaceprefixed attributes of an element actually resolve to the same attribute. See also XMLReaderAdapter, an adapter that works in the reverse direction to make a SAX2 parser behave like a SAX1 parser. Object

ParserAdapter

DocumentHandler

XMLReader

public class ParserAdapter implements org.xml.sax.DocumentHandler, org.xml.sax.XMLReader { // Public Constructors public ParserAdapter() throws org.xml.sax.SAXException; public ParserAdapter(org.xml.sax.Parser parser); // Methods Implementing DocumentHandler public void characters(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; public void endDocument() throws org.xml.sax.SAXException; public void endElement(String qName) throws org.xml.sax.SAXException; public void ignorableWhitespace(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; public void processingInstruction(String target, String data) throws org.xml.sax.SAXException; public void setDocumentLocator(org.xml.sax.Locator locator); public void startDocument() throws org.xml.sax.SAXException; public void startElement(String qName, org.xml.sax.AttributeList qAtts) throws org.xml.sax.SAXException; // Methods Implementing XMLReader public org.xml.sax.ContentHandler getContentHandler(); public org.xml.sax.DTDHandler getDTDHandler(); public org.xml.sax.EntityResolver getEntityResolver(); public org.xml.sax.ErrorHandler getErrorHandler(); public boolean getFeature(String name) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public Object getProperty(String name) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void parse(String systemId) throws java.io.IOException, org.xml.sax.SAXException; public void parse(org.xml.sax.InputSource input) throws java.io.IOException, org.xml.sax.SAXException; public void setContentHandler(org.xml.sax.ContentHandler handler); public void setDTDHandler(org.xml.sax.DTDHandler handler); public void setEntityResolver(org.xml.sax.EntityResolver resolver); public void setErrorHandler(org.xml.sax.ErrorHandler handler); public void setFeature(String name, boolean state) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void setProperty(String name, Object value) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; }

ParserFactor y

Java 1.4; Deprecated in Java 1.4

org.xml.sax.helpers This deprecated SAX1 class is a factory for deprecated SAX1 Parser objects. New applications should use the SAX2 XMLReaderFactor y as a factory for SAX2 XMLReader objects. public class ParserFactor y { // No Constructor // Public Class Methods public static org.xml.sax.Parser makeParser() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NullPointerException;

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

867

ParserFactory

public static org.xml.sax.Parser makeParser(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ClassCastException; }

XMLFilterImpl

Java 1.4

org.xml.sax.helpers This class is implements an XMLFilter that does no filtering. You can subclass it to override whatever methods are required to perform the type of filtering you desire. XMLFilterImpl implements ContentHandler, ErrorHandler, EntityResolver and DTDHandler so that it can receive SAX events from the “parent” XMLReader object. But it also implements the XMLFilter interface, which is an extension of XMLReader, so that it acts as an XMLReader itself, and can send SAX events to the handler objects that are registered on it. Each of the handler methods of this class simply invoke the corresponding method of the corresponding handler that was registered on the filter. The XMLReader methods for getting and setting features and properties simply invoke the corresponding method of the parent XMLReader object. The parse() methods do the same thing: they pass their argument to the corresponding parse() method of the parent reader to start the parsing process. Object ContentHandler

XMLFilterImpl DTDHandler

EntityResolver

ErrorHandler

XMLReader

XMLFilter

public class XMLFilterImpl implements org.xml.sax.ContentHandler, org.xml.sax.DTDHandler, org.xml.sax.EntityResolver, org.xml.sax.ErrorHandler, org.xml.sax.XMLFilter { // Public Constructors public XMLFilterImpl(); public XMLFilterImpl(org.xml.sax.XMLReader parent); // Methods Implementing ContentHandler public void characters(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; public void endDocument() throws org.xml.sax.SAXException; public void endElement(String uri, String localName, String qName) throws org.xml.sax.SAXException; public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException; public void ignorableWhitespace(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; public void processingInstruction(String target, String data) throws org.xml.sax.SAXException; public void setDocumentLocator(org.xml.sax.Locator locator); public void skippedEntity(String name) throws org.xml.sax.SAXException; public void startDocument() throws org.xml.sax.SAXException; public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws org.xml.sax.SAXException; public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException; // Methods Implementing DTDHandler public void notationDecl(String name, String publicId, String systemId) throws org.xml.sax.SAXException; public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws org.xml.sax.SAXException; // Methods Implementing EntityResolver public org.xml.sax.InputSource resolveEntity(String publicId, String systemId) throws org.xml.sax.SAXException, java.io.IOException; // Methods Implementing ErrorHandler public void error(org.xml.sax.SAXParseException e) throws org.xml.sax.SAXException; public void fatalError(org.xml.sax.SAXParseException e) throws org.xml.sax.SAXException; public void warning(org.xml.sax.SAXParseException e) throws org.xml.sax.SAXException; // Methods Implementing XMLFilter public org.xml.sax.XMLReader getParent(); default:null public void setParent(org.xml.sax.XMLReader parent);

868

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

XMLReaderAdapter

// Methods Implementing XMLReader public org.xml.sax.ContentHandler getContentHandler(); public org.xml.sax.DTDHandler getDTDHandler(); public org.xml.sax.EntityResolver getEntityResolver(); public org.xml.sax.ErrorHandler getErrorHandler(); public boolean getFeature(String name) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public Object getProperty(String name) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void parse(String systemId) throws org.xml.sax.SAXException, java.io.IOException; public void parse(org.xml.sax.InputSource input) throws org.xml.sax.SAXException, java.io.IOException; public void setContentHandler(org.xml.sax.ContentHandler handler); public void setDTDHandler(org.xml.sax.DTDHandler handler); public void setEntityResolver(org.xml.sax.EntityResolver resolver); public void setErrorHandler(org.xml.sax.ErrorHandler handler); public void setFeature(String name, boolean state) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void setProperty(String name, Object value) throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; }

XMLReaderAdapter

default:null default:null default:null default:null

Java 1.4

org.xml.sax.helpers This adapter class wraps a SAX2 XMLReader object and makes it behave like a SAX1 Parser object. It is useful when working with a legacy API that requires a deprecated Parser object. Create an XMLReaderAdapter by passing an XMLReader to the XMLReaderAdapter() constructor. Then use the resulting object exactly as you would use any other SAX1 Parser object. This class implements ContentHandler so that it can receive SAX events from the XMLReader. But it also implements the Parser interface so that it can have a SAX1 DocumentHandler registered on it. The methods of ContentHandler are implemented to invoke the corresponding methods of the registered DocumentHandler. Object

XMLReaderAdapter

ContentHandler

Parser

public class XMLReaderAdapter implements org.xml.sax.ContentHandler, org.xml.sax.Parser { // Public Constructors public XMLReaderAdapter() throws org.xml.sax.SAXException; public XMLReaderAdapter(org.xml.sax.XMLReader xmlReader); // Methods Implementing ContentHandler public void characters(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; public void endDocument() throws org.xml.sax.SAXException; public void endElement(String uri, String localName, String qName) throws org.xml.sax.SAXException; public void endPrefixMapping(String prefix); public void ignorableWhitespace(char[ ] ch, int start, int length) throws org.xml.sax.SAXException; public void processingInstruction(String target, String data) throws org.xml.sax.SAXException; public void setDocumentLocator(org.xml.sax.Locator locator); public void skippedEntity(String name) throws org.xml.sax.SAXException; public void startDocument() throws org.xml.sax.SAXException; public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws org.xml.sax.SAXException; public void startPrefixMapping(String prefix, String uri); // Methods Implementing Parser

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

7 March 2002 11:41

empty

empty

empty

869

XMLReaderAdapter

public void parse(String systemId) throws java.io.IOException, org.xml.sax.SAXException; public void parse(org.xml.sax.InputSource input) throws java.io.IOException, org.xml.sax.SAXException; public void setDocumentHandler(org.xml.sax.DocumentHandler handler); public void setDTDHandler(org.xml.sax.DTDHandler handler); public void setEntityResolver(org.xml.sax.EntityResolver resolver); public void setErrorHandler(org.xml.sax.ErrorHandler handler); public void setLocale(java.util.Locale locale) throws org.xml.sax.SAXException; }

XMLReaderFactor y

Java 1.4

org.xml.sax.helpers This factory class defines two static factory methods for creating XMLReader objects. One method takes the name of a class as its argument. It dynamically loads and instantiates the class, then casts it to an XMLReader object. The second factory method takes no arguments; it reads the system property named “org.xml.sax.driver” and uses the value of that property as the name of the class XMLReader implementation class to load and instantiate. An application that instantiates its SAX parser using the no-argument method of XMLReaderFactor y gains a layer of independence from the underlying parser implementation. The end user or system administrator of the system on which the application is deployed can change the parser implementation simply by setting a system property. Note that the javax.xml.parsers package provides a similar, but somewhat more useful SAXParserFactor y. public final class XMLReaderFactor y { // No Constructor // Public Class Methods public static org.xml.sax.XMLReader createXMLReader() throws org.xml.sax.SAXException; public static org.xml.sax.XMLReader createXMLReader(String className) throws org.xml.sax.SAXException; }

870

7 March 2002 11:41

Chapter 24 – org.xml.sax, org.xml.sax.ext, and org.xml.sax.helpers

Index

Symbols

@ (at sign) in doc comments, 227 filenames beginning with, Java compiler and, 248 \ (backslashes), regular expression character escapes, 149 ! (exclamation point) ! (boolean NOT) operator, 38 !! (jdb shorthand) command, 262 != (not equals) operator, 37 { } (curly braces) in anonymous class formatting, 136 in classes, 11 enclosing body of loop, 16 enclosing statement blocks, 47 inline doc comment tags, 232 method body, enclosing, 13 nested if statements, use with, 47 nesting arrays within arrays, 74 [ ] (brackets), array access operator, 33, 43, 70 ˆ (caret) ˆ= (bitwise XOR assignment operator), 41 bitwise XOR operator, 39 boolean XOR operator, 38 : (colon) in statement labels, 45 in ternary operand, 32

& (ampersand) & (bitwise AND) operator, 39 & (boolean AND) operator, 38 && (conditional AND) operator, 37 &= (bitwise and assignment) operator, 41 < (angle bracket, left) < (less than) operator, 37 > (signed right shift) operator, 40 >>> (unsigned right shift) operator, 40 >>>= (unsigned right-shift assignment) operator, 41 >>= (signed right-shift assignment) operator, 41 >= (greater than or equal) operator, 37 * (asterisk) *= (multiplication assignment) operator, 41 in doc comments, 227 multiplication operator, 34

919

7 March 2002 11:43

, (comma) in numeric values, 152 separating variable names and initializers, 46 $ (dollar sign), in identifiers, 21, 223 . (dot), object member access operator, 42 = (equal sign) = (assignment) operator, 13, 41 combining with arithmetic, bitwise, and shift operators, 41 = = (equal to) operator, 26, 36 comparing hashtable key objects, 156 comparing reference types for equality, 77 - (minus sign) - - (decrement) operator, 36 -= (subtraction assignment) operator, 41 preceding integer literals, 24 subtraction operator, 32, 34 unary negation operator, 32, 35 ( ) (parentheses) in expressions, order of evaluation and, 34 method invocation operator, 33 in method names, 12 in method parameters, 12 operator precedence, overriding with, 31 subexpressions within regular expressions, 149 type conversion or casting operator, 43 % (percent sign) % (modulo) operator, 35 %= (modulo assignment) operator, 41 π (pi), defining constant for, 403 + (plus sign) += (add assignment) operator, 41 concatenating strings with, 35 ++ (increment) operator, 33, 35 addition operator, 34 read access for applets, 236 spaces in URL encoding, 479 string concatenation operator, 35

920

7 March 2002 11:43

Index

? (question mark) ?: (conditional) operator, 41 jdb help command, 262 in ternary operand, 32 “ ” (quotes, double) in strings, 27 surrounding string literals, 67 ‘ ’ (quotes, single), enclosing char literals in Java code, 23, 68 ; (semicolon), 10 for empty statements, 45 ending do loops, 51 ending Java statements, 13, 15 compound statements and, 16 / (slash) / (division) operator, 34 /* */, in multiline comments, 11, 20 /** */, in doc comments, 21, 225 /= (division assignment) operator, 41 //, in single-line comments, 10, 20 ˜ (tilde) bitwise complement operator, 39 bitwise NOT operator, 39 _ (underscore), in identifier names, 21 | (vertical bar) | (bitwise OR) operator, 39 | (boolean OR) operator, 38 || (conditional OR) operator, 38 |= (bitwise or assignment) operator, 41

A absolute filenames, 334 abstract classes, 115−117 concrete subclasses, 116 InstantiationError, 399 InstantiationException, 399 interfaces vs., 118, 120 abstract methods, 115−117 AbstractMethodError, 377 interfaces, 118 abstract modifier, 116, 138 AbstractCollection class, 637 AbstractList class, 638 AbstractMap class, 639 AbstractPreferences class, 711 AbstractSequentialList class, 640

AbstractSet class, 640 accept( ) (ServerSocketChannel), 187 access control, 111−114, 202, 204−207 for class members, 112 for classes, 112 classes implementing, 533 digitally signed classes, 205 inheritance and, 113 java.security package, 196 java.security.acl package, 570 modifiers, 111 for packages, 111 packages for, 143 permissions and policies, 206 the sandbox (Java 1.0), 204 for threads, 426 trusted vs. untrusted code, changes in Java 1.2, 206 access control list (ACL), 570 AccessControlContext class, 536 AccessControlException class, 536 AccessController class, 206, 534, 537 AccessibleObject class, 435 accessor methods for bean properties (see get and set property accessor methods) AccountExpiredException class, 799 ACL (Access Control List), 570 Acl interface, 570 AclEntry interface, 570 AclNotFoundException, 571 action names, permissions, 207, 209 adapter classes, 133 add and remove methods for event listeners, 213 addition (+) operator, 34 additive operators, associativity of, 32 addPreferenceChangeListener(), 178 addPropertyChangeListener (PropertyChangeListener), 216 addShutdownHook( ) (Runtime), 101 addVetoableChangeListener (VetoableChangeListener), 217 Adler32 class, 727 aggregate (reference) types, 29 AlgorithmParameterGenerator class, 537

AlgorithmParameterGeneratorSpi class, 538 AlgorithmParameters class, 538 AlgorithmParameterSpec interface, 603 algorithms, cryptographic digital signature algorithm for certificate, 268 javax.crypto.interfaces package, 754 specifications (javax.crypto.spec package), 756 specifying for keys, 267 supported by SunJCE provider, 740 aliases for certificates and keys, 265 allocating/deallocating memory (see garbage collection; memory) AllPermission class, 540 AlreadyConnectedException class, 497 AND (&&) operator (boolean), 37 AND (&) operator (bitwise), 39 AND (&) operator (boolean), 38 animation, threads for, 161 Annotation class, 610 anonymous arrays, 72 anonymous classes, 123, 133−136 features of, 134 formatting rules for code, 135 implementation of, 137 implementing adapter classes with, 133 new syntax for defining and initiating, 135 restrictions on, 134 when to use, 135 anonymous inner classes, 68 APIs (application programming interfaces), 118 core Java, 3, 14 extension, 3 platforms and operating systems, 4 (see also interfaces) AppConfigurationEntry class, 799 LoginModuleControlFlag class, 799 AppletInitializer interface, 283 applets, 12 java.applet package, 145 security and, 202 security restrictions on, 204, 236

Index

7 March 2002 11:43

921

appletviewer program, 234−238 commands, 235 options, 234 properties, 236 firewall and caching proxy servers , 237 security, 236 application classes, default search path for, 260 application programmers, security for, 207 applications, 12 client, 174 networked, 171 arbitrary-precision integers, package for, 143 arguments, method, 14 IllegalArgumentException, 396 testing for legal values with assert statement, 62 arithmetic date and time, performing with Calendar, 154, 646 integer, in Java, 25 java.math package, 143 arithmetic operators, 34 combining with assignment (=) operator, 41 ArithmeticException class, 377 arraycopy( ) (System), 155 arrays, 14, 29, 69−74, 155 [ ] (array access) operator, 33, 43 Array class, 434 array literals, 71 ArrayIndexOutOfBoundsException, 56, 70, 216, 377 ArrayList class, 156, 641 Arrays class, 155, 642 ArrayStoreException, 378 of bytes, 167 comparing, 77 converting strings to, 417 converting to other reference types, 80 converting to strings, 35 copying, 75, 423 creating, 43, 70

922

7 March 2002 11:43

Index

equivalence, testing for, 78 index of elements, 70 indexed properties, JavaBeans, 216 instanceof operator, using with, 42 length of, 71 locks on, 54 memory allocation and garbage collection for, 79 multidimensional, 73 NegativeArraySizeException, 404 as objects, 156 ObjectStreamField objects, 231 as operand type, 33 rectangular, 74 references to, 75 streaming data to and from, 169 of strings, 12 sorting, 618 ASCII 7-bit character encoding, 20 native2ascii tool, 268 assertions, 60−64 AssertionError class, 378 in classes loaded through ClassLoader, 388 compiling, 60 disabling for Java interpreter, 244 enabling, 61, 245 errors in, 63 javadoc tool, option for, 256 assignment in expression statements, 44 assignment operators, 13, 40 associativity, 32 combining with arithmetic, bitwise, and shift operators, 41 side effects of, 33 associativity, operator, 30, 32 asterisk (*) (see *, under Symbols) AsynchronousCloseException class, 497 AttributedCharacterIterator interface, 610 Attribute class, 611 AttributedString class, 611 Attributes class, 690 Name class, 691

authentication, 204 classes, 196 implementing with, 533 uniting with access control classes, 534 Kerberos protocol, using, 144 LoginModule interface, 144 messages transmitted with secret key, 750 packages for, 143 PasswordAuthentication class, 463 Authenticator class, 450 @author doc comment tag, 228 authorization (see authentication) AuthPermission class, 783 auxiliary classes provided by beans, 219 AWT programming, 211 event model (Java 1.0 and 1.1), changes in, 225 java.awt.peer package, lack of portability, 224

B BackingStoreException class, 712 BadPaddingException, 739 BasicPermission class, 540 BCSChild class, 321 BCSIterator class, 322 BCSSChild class, 318 BCSSProxyServiceProvider class, 318 BCSSServiceProvider class, 319 beanbox tool, 212 bean contexts supplied by vendor, 221 customizing beans with property value settings, 214 interoperability with beans, 214 BeanContext interface, 221, 306 BeanContextChild interface, 221, 308 BeanContextChildComponentProxy interface, 309 BeanContextChildSupport class, 221, 309 BeanContextContainerProxy interface, 311 BeanContextEvent class, 311

BeanContextMembershipEvent class, 311 BeanContextMembershipListener interface, 312 BeanContextProxy interface, 310, 312 BeanContextServiceAvailableEvent class, 313 BeanContextServiceProvider interface, 313 BeanContextServiceProviderBeanInfo interface, 314 BeanContextServiceRevokedEvent class, 314 BeanContextServiceRevokedListener interface, 315 BeanContextServices interface, 221, 315 BeanContextServicesListener interface, 316 BeanContextServicesSupport class, 221, 317 BCSSChild class, 318 BCSSProxyServiceProvider class, 318 BCSSServiceProvider class, 319 BeanContextSupport class, 221, 319 BCSChild class, 321 BCSIterator class, 322 BeanDescriptor class, 284 @beaninfo doc comment tag, 232 BeanInfo interface, 213, 215, 219, 284 beans (see JavaBeans) Beans class, 282, 285 Bidi class, 613 BigDecimal class, 153, 444 BigInteger class, 153, 446 binary (base-2) numbers, 39 binary data in files, reading from arbitrary locations, 166 binary operators, 32, 34 BindException class, 450 BitSet class, 644 bitwise operators, 39 Boolean operators as, 38, 645 combining with assignment operator, 41 blank lines in Java programs, 15 blocking threads, waking, 164

Index

7 March 2002 11:43

923

boolean data type, 16, 23 Boolean class, 378 get methods and, 115 operator return values, 33 return values for equality and relational operators, 36 Boolean operators, 37 | (OR), 39 BitSet class methods, using as, 645 bound properties, 213, 216, 298 GUI component, changes in, 282 break statements, 49, 52 labels, use of, 45 BreakIterator class, 614 breakpoints for jdb debugger, 262, 264 BufferedInputStream class, 324, 326 BufferedOutputStream class, 324, 326 BufferedReader class, 327 BufferedWriter class, 327 buffers Buffer class, 482 BufferOverflowException class, 484 BufferUnderflowException class, 484 ByteBuffer class, 182, 484 channels, using with, 181 CharBuffer class, 147, 182, 488 DoubleBuffer class, 489 existing, encoding/decoding characters into, 182 FloatBuffer class, 490 IntBuffer class, 491 InvalidMarkException class, 492 LongBuffer class, 493 MappedByteBuffer class, 494 New IO API, 179, 481 ReadOnlyBufferException, 494 ShortBuffer class, 494 ShortBufferException, 754 size, setting for sockets, 453, 466 StringBuffer class, 419 StringBufferInputStream class, 370 bugs implementation-specific, portability and, 224 security-related, 7 by reference, 141

924

7 March 2002 11:43

Index

byte code, 8 displaying for methods with javap tool, 259 JIT compilers, 391 verification of, 203 VerifyError class, 430 byte streams, UTF-8, 20 ByteBuffer class, 179, 182 ByteChannel interface, 181, 498 ByteOrder class, 487 bytes buffers of, converting to buffers of characters, 179 Byte class, 25, 151, 379 byte data type, 24 ByteArrayInputStream class, 169, 323, 328 ByteArrayOutputStream class, 169, 323, 328 CharConversionException, 330 converting objects to, 170 streams of, 166 reading, 167 transferring from FileChannel to another channel, 184

C C/C++ languages address-of operator (&), 75 boolean type, Java boolean vs., 23 C language, differences from Java, 85−87 C++, object-oriented programming, Java vs., 88 C++ features not found in Java, 140 dereference operators (* and −>) , 75 finalization methods in Java vs. C++, 100 Java native methods, implementing in C, 257 memory allocation and garbage collection, Java vs., 79 multiple inheritance in C++, 118, 140 performance, Java vs., 8

C/C++ languages (continued) superclass indicating with :, Java keyword extends vs., 102 virtual functions in C++, 109 Java abstract classes vs., 116 CA (certificate authority), 574, 593 caching by proxy servers, 237 URL connections, 477 Calendar class, 154, 646 date arithmetic with, 154 GregorianCalendar class, 658 Callback interface, 789 CallbackHandler class, 789 calling methods, 12 CancelledKeyException class, 498 canonical filenames, 334 capitalization conventions, 222 case labels (switch), 49 case-sensitivity in Java, 10 case, converting in strings, 417 casts, 27 ( ) (type conversion or casting) operator, 43 ClassCastException, 387 converting object to type of subclass, 80 object inheritance and, 103 objects to Object instance, 140 shadowed superclass field, accessing, 106 super, referring to shadowed fields vs. invoking overridden method with super, 109 catch clause, 58 catching errors in assertions, 63 catching exceptions, 55 jdb debugger, 262 try/catch/finally statements, 57−60 ceil( ) (Math), 28 Centered interface (example), 118 certificate authority (CA), 574, 593 Certificate class, 574, 593 Certificate interface (java.security package) vs., 575 CertificateRep class, 575 (see also X509Certificate class)

Certificate interface, 534, 541 Certificate class (java.security.cert) vs., 575 certificate revocation lists (CRLs), 573, 587 CertificateEncodingException, 576 CertificateException class, 576 CertificateExpiredException, 576 CertificateFactory class, 577 CertificateFactorySpi class, 578 CertificateNotYetValidException, 578 CertificateParsingException, 579 certificates, 573 creating self-signed for public key associated with alias, 266 displaying contents with keytool, 266 java.security.cert package, 143 in keystore file, 241 public-key, associated with JAR file, 241 storing in keystore, 265 X.500, 144 distinguished name, 267 X.509 X500PrivateCredential class, 804 X509KeyManager interface, 780 X509TrustManager interface, 780 CertPath class, 579 CertPathRep class, 580 CertPathBuilder class, 580 CertPathBuilderException class, 581 CertPathBuilderResult class, 581 CertPathBuilderSpi class, 582 CertPathParameters interface, 582 CertPathValidator class, 582 CertPathValidatorException class, 583 CertPathValidatorResult interface, 584 CertPathValidatorSpi class, 584 CertSelector interface, 584 CertStore class, 585 CertStoreException class, 586 CertStoreParameters interface, 586 CertStoreSpi class, 586 chaining certificates, 579 constructors, 104

Index

7 March 2002 11:43

925

chaining (continued) exceptions, 439 methods buffers, 180 overridden methods, 110 channels, 143, 179, 465, 467, 495 AsynchronousCloseException, 497 basic operations, 181 ByteChannel interface, 498 DatagramChannel class, 187 FileChannel class, 183−185 interrupted threads and, 164 nonblocking, 187−191 ServerSocketChannel class, 187 SocketChannel class, 186 AlreadyConnectedException class, 497 char data type, 23 char type vs. char values, 66 Character class wrapper for, 380 character encoding appletviewer, specifying for, 235 native2ascii tool, 268 UnsupportedEncodingException, 371 character sets, 20, 522 encoders/decoders to convert Unicode strings to/from bytes, 143 Java platform internationalization features, 8 characters, 23, 145−151 Character class, 24, 147, 380 Subset class, 383 UnicodeBlock class, 383 CharacterIterator interface, 615 CharArrayReader class, 169, 329 CharArrayWriter class, 169, 329 CharConversionException, 330 converting between byte buffers and character buffers, 179 in names, Java conventions for, 223 pattern matching with regular expressions, 148 streams of, 166 string, CharSequence and CharBuffer interfaces, 147 (see also char data type) CharBuffer class, 180, 182, 488 CharSequence interface, 180, 385

926

7 March 2002 11:43

Index

Charset class, 182 CharsetDecoder class, 182 CharsetEncoder class, 182 charsets, encoding and decoding text with, 182 8-bit encoding charset (Latin-1), 183 EUC-JP (for Japanese text), 183 checked exceptions, 56 methods throwing, 65 CheckedInputStream class, 728 CheckedOutputStream class, 728 checkError( ), 362 checkPermission( ) (AccessController), 206 checkRead( ) (SecurityManager), 204, 206 Checksum interface, 729 checksums, 168 Adler32 algorithm, 728 (see also message digests) ChoiceCallback class, 790 ChoiceFormat class, 615 Cipher class, 200, 738, 740 NullCipher class, 752 CipherInputStream class, 200, 743 CipherOutputStream class, 200, 743 CipherSpi class, 743 Circle class (example), 89−93 circular dependency, 387 class fields, 89, 437 default initialization, 96 initializing, 97 static initializers, using, 97 superclass, shadowing, 106 class files, 84 verification of, 203 class hierarchy, 80, 103 containment hierarchy vs., 129 class methods, 89 choosing between class and instance methods, 93 Circle.radiansToDegrees() (example), 90 interfaces and, 118 listing all for specified class with jdb debugger, 263 shadowing by subclass, 107 synchronized, 55

Class objects, obtaining, 158 classes, 4, 7, 20, 29, 66, 142 abstract, 115−117, 138 concrete subclasses, 116 access to, 112 anonymous, 123, 133−136 anonymous inner classes, 68 byte-code verification, failing, 430 capitalization/naming conventions, 222 Class class, 68, 374, 385 dynamic instantiation with newInstance( ) , 67 reflection and dynamic loading, 158 ClassCastException, 80, 387, 652 ClassCircularityError, 387 ClassFormatError, 388 ClassLoader class, 61, 388 ClassNotFoundException, 389 code source, 541 constructors, fields, and methods, 434 converting to strings, 35 core, Java language, 142 defining, 11, 66 restrictions on untrusted applets, 237 definitions of, static initializers in, 97 deprecated (@deprecated doc comment tag), 231 digital signatures for, 205 doc comments in (example), 226 documentation by javadoc, display of, 256 dynamic loading, 159 enabling assertions in, 61 extending, 102 final, 103 garbage collection, disabling for, 247 hiding (and encapsulating) data in, 111 IllegalAccessError, 396 IllegalAccessException, 396 implementing interfaces, 119 importing, 82

IncompatibleClassChangeError, 398 inner, 122 how they work, 136−138 InvalidClassException, 345 Java platform, 3 javap display, including or excluding from, 260 LinkageError, 401 loading with interpreter, 247 with SecureClassLoader, 563 with URLClassLoader, 476 local, 123, 129−133 member, 125−129 members of, 11, 88−94, 439 access control for, 111 class fields, 89 instance methods, 91−94 static and instance, 88 modifiers for, 138−140 names, simple and fully qualified, 81 NoClassDefFoundError, 404 online documentation for, 21 package, specifying for, 82 permission, summary of, 209 public in Java files, 83 preventing insertion of public constructor, 105 references to, in @see doc comment tag, 229 static member, 123 features of, 124 system, 225 tool for, 259 undocumented, conventions/rules for, 224 UnsatisfiedLinkError, 429 UnsupportedClassVersionError, 429 verifying with javap tool, 260 version number, tool for displaying, 270 (see also Java platform; packages) “Classic VM”, 243 specifying for Java interpreter, 244

Index

7 March 2002 11:43

927

CLASSPATH environment variable appletviewer, use of, 236 javac compiler, specifying for, 251 setting for interpreter, 248 classpaths application classes, specifying for javap, 260 java interpreter, specifying for, 244 javadoc tool, 257 javah tool, 258 javap, for classes named on command line, 259 client applications, 174 -client option (HotSpot VM), 243 client-side networking, 186 nonblocking I/O, 190 method, class initialization code in, 97 Clock class, 161 clone( ) (Object), 76 Cloneable interface, 76, 390 as marker interface, 122 CloneNotSupportedException, 77, 390 ClosedByInterruptException class, 164 code critical sections, synchronizing, 54 privileged, 559 code blocks, synchronized, 162 CodeSource class, 534, 541 CollationElementIterator class, 616 CollationKey class, 617 Collator class, 150, 618 RuleBasedCollator class, 632 CollectionCertStoreParameters class, 587 collections, 156−158 AbstractCollection class, 637 classes for, 635 Collection interface, 649 Collections class, 650 Collections class utility methods, 157 converting to and from arrays, 157 Hashtables class, 176 immutable or unmodifiable, error, 430 packages for, 143 Permission objects, 556 RandomAccess interface, 156

928

7 March 2002 11:43

Index

sets, 677 vectors, 686 com.sun.javadoc package, 252 combination assignment operators, 41 command-line tools enabling assertions, 61 Java interpreter, -classpath option, 84 javac compiler, 10 commands appletviewer program, 235 jar tool, options, 239 jdb debugger, 261−265 keytool, 265 options, 267 comments, 11, 20 doc, 225−233 single-line, enclosed with //, 10 compact( ), 182 Comparable interface, 390 Comparator interface, 652 compareTo( ) (String), 150 comparing hashtable key objects, 156 strings, 150 strings and substrings, 416 comparison operators, 36 precedence, boolean vs., 37 compile( ) (Pattern), 149 Compiler class, 391 compilers, Java, javac, 10, 248−251 options, 249−251 compiling assertions, 60 compound (or composite) types, 29 compound statements, 16, 45 compression/decompression of data, 727 Adler32 checksum algorithm, 728 JAR archive files, 240 ZIP archives, 81 concatenating file or directory name to directory name, 225 concatenating strings, 417, 420 + and += operators, 35 string literals, 68 concrete subclasses, 116 ConcurrentModificationException, 653 conditional (?:) operator, 32, 41 conditional AND (&&) operator, 37

conditional OR (||) operator, 38 Configuration class, 800 configuration files logging, 178 Properties class, using for, 176 configuration, security levels and restrictions, 7 ConfirmationCallback class, 790 ConnectException class, 451 connections network, stream-based vs. datagrams, 175 URLConnection class, 477 ConsoleHandler class, 696 constants capitalization/naming conventions, 89, 223 defined by primitive type wrapper classes, 26, 151 in interface definitions, 118 inheritance of, 119 in Java object serialization, 355 static and final in anonymous classes, 134 in local classes, 130 constrained properties, 213, 217, 298 changes, prohibiting, 301 Constructor class, 67, 436 constructors, 65, 94−98 anonymous classes and, 134 chaining, default constructor and, 104 classes, 434 defining, 94 multiple, 95 field initialization code in, 96 interfaces and, 118 invoking from another constructor, 95 local classes, enclosing instance passed to, 131 member classes, 128 naming, declaring, and writing, 95 references to, in @see doc comment tag, 230 subclass, 103 superclass, 103 containers for JavaBeans and bean contexts, 214, 311 BeanContext interface, 307

containing classes associating instance with local class, 130 instance, specifying for member class, 128 containment hierarchy, 129 containment protocol (JavaBeans), 221 ContentHandler class, 192, 451 ContentHandlerFactory interface, 451 context objects for JavaBeans, 142 context, bean, 221 continue statements, 53 labels, use of, 45 control flags, login module, 799 conventions capitalization, 222 documentation, 222−233 for JavaBeans, 214−220 naming, 222 for portability, 223−225 converting data types buffers of bytes to buffers of characters, 179 bytes to strings, 379 casting, 43 char to other types, 28 char values to integral types, 24 collections to/from arrays, 157 files to/from URIs, 334 floating-point to integers, 28 inheritance and, 102 int literals to shorter types, 24 Java source code to ASCII, 268 numbers to/from strings, 151 objects to byte streams, 170 primitive, listing of conversions, 28 reference types, 79 arrays, 80 objects, 80 to strings, 35 strings to integer values, 25 strings to integers, 399 strings to longs, 401 strings to/from shorts, 413 Unicode strings to/from bytes, 143 widening and narrowing conversions, 27 copying files, using FileChannel objects, 183

Index

7 March 2002 11:43

929

core Java APIs, 3, 14 corrupted data streams, 368 counters for loops, incrementing, 36, 50 CRC32 class, 727, 729 CredentialExpiredException class, 801 critical sections, 54 CRL class, 587 CRLException class, 588 CRLSelector interface, 588 cryptographic-strength random numbers, 153 cryptographic-strength checksums (see message digests) cryptography, 199−201, 204 arbitrary-precision integers, using, 444 DSA and RSA public and private keys, 598 encrypted objects, 201 encryption and decryption with Cipher, 200 Java Cryptography Extension (JCE), 534 javax.crypto package, 738 javax.crypto.interfaces package, 754 keytool program, 265−268 principals in cryptographic transactions, 558 public/private key classes for authentication , 534 converting between Key and KeySpec, 548 in digital signatures, 197 packages for, 143 PrivateKey interface, 558 PublicKey interface, 562 resources for further reading, 739 secret key, 199, 752, 760 KerberosKey class, 795 service provider, not available, 555 symmetric-key, 199 Currency class, 653 currency symbols (Unicode), in identifiers, 21 currently running thread, 424 currentTimeMillis( ) (System), 154

930

7 March 2002 11:43

Index

Customizer interface, 214, 220, 286 customizing documentation format with javadoc, 252

D data compressing and writing to file, 168 hiding and encapsulating, 110−115 access control, 111−115 streaming (see input/output, streams) data accessor methods, 114 data types, 13 bean properties, editor for, 219 buffer classes for, 179 classes as, 66 comparing different, 36 conditional operands, 41 converting (see converting data types) declaring for variables, 45 fields, initializing, 96 interfaces as, 120 method returns, 65 operand, 32 primitive, 22−28 boolean, 16, 23, 378 char, 23, 380 conversions between, 27 double, 391 float, 394 floating-point types, 14, 25 int, 399 integer types, 24 long, 401 short, 413 textual representations of, 360 wrapper classes for, 151, 374 reference, 22, 29, 74−81 arrays, 69−74 reflection and dynamic loading, 158 return, for operators, 33 strings, 27, 67, 145 switch statement with case labels, 50

data types (continued) vs. values represented by, 66 void, 431 DataFormatException, 730 DatagramChannel class, 187 DatagramPacket class, 175, 448, 452 DatagramSocket class, 175, 452 DatagramSocketImpl class, 454 DatagramSocketImplFactory interface, 455 DataInput interface, 330 DataInputStream class, 324, 331 DataOutput interface, 332 DataOutputStream class, 324, 333 DateFormat class, 154, 619 Field class, 621 DateFormatSymbols class, 622 dates and times, 636 calculating with Calendar class, 646 classes for, 154 current time in milliseconds, 423 date arithmetic with Calendar class, 154 Date class, 654 DateServer class (example), reporting current time, 187 formatting dates with DateFormat, 154 formatting with SimpleDateFormat class, 632 Locale class and, 668 period of validity (in days) for certificates, 268 SimpleTimeZone class, 678 TimeZone class, 683 deadlock in thread synchronization, 163 debug( ), 178 debugging applets, –debug option, 235 assertions, enabling for, 60 HTTP clients, 174 java interpreter, enabling for, 244 java_g (debugging version of Java interpreter), 243 jdb debugger for Java, 261−265 logging, using for, 178 decimal places, specifying, 444 DecimalFormat class, 622 DecimalFormatSymbols class, 624

declaring class fields, 89 constructors, 95 exceptions, 56 fields, variables vs., 96 methods, public static void declaration, 12 variables, 13 local variable declaration statements, 45 placement of declaration, 16 decoding byte sequences into character strings, 182 decrement (- -) operator, 36 decrement expression statements, 44 decrementing array index variable, 71 decryption (see encryption/decryption of data) default: label, switch statement, 49 DefaultHandler class, 192 DefaultPersistenceDelegate class, 286 defining classes, 11, 66 NoClassDefFoundError, 404 restricting untrusted applets from, 237 simple (Circle class example), 89 static initializers, 97 constructors, 94 multiple, 95 interfaces, 118 Centered interface (example), 118 Java programs, 84 local classes, 129 methods, 12 packages, 82 system classes, portability and, 225 Deflater class, 730 DeflaterOutputStream class, 731 DelegationPermission class, 794 deleting files, permission for, 339 temporary files, 100, 335 Depends-On attribute, JAR file manifest, 220 @deprecated doc comment tags, 231, 233

Index

7 March 2002 11:43

931

deprecated features, ommitting from javadoc documentation, 255 DESedeKeySpec class, 756 deserializing objects, 170 design patterns (see JavaBeans, conventions) Design-Time-Only attribute, JAR file manifest, 220 DesignMode interface, 221, 287 DESKeySpec class, 757 Destroyable class, 784 DestroyFailedException class, 784 destroying objects, 98−101 development tools (see SDK) DHGenParameterSpec class, 757 DHKey interface, 755 DHParameterSpec class, 758 DHPrivateKey interface, 755 DHPrivateKeySpec class, 758 DHPublicKey interface, 755 DHPublicKeySpec class, 758 Dictionary class, 655 Diffie-Hellman key-agreement algorithm, 747 parameters, generating set, 757 public/private key pairs, 754 public/private keys, 756 interfaces representing, 144 three-party agreement, 747 DigestException class, 542 DigestInputStream class, 168, 534, 542 DigestOutputStream class, 534, 542 digital signatures, 197, 205 algorithm that signs a certificate, 268 JAR files, 241 Signature class, 566 SignatureSpi class, 567 SignedObject class, 568 Signer class, 568 wrapping around an object, 198 directories, 165 creating, 335 naming, portability and, 225 read permission for untrusted applets, 236 write permission for untrusted applets, 236 disabling assertions, 61 displaying output, 14

932

7 March 2002 11:43

Index

distinguished name for X.500 certificate, 267 distributed (enterprise) computing, packages for, 145 distributing beans, 220 division (/) operator, 34 do loops, continue statement, starting new iteration, 53 do statements, 51 do/while statements, 51 doc comments, 21, 225−233 in a class (example), 226 images in, 227 in javadoc program output, 252 overview, use by javadoc, 256 for packages, 233 spaces in, 227 structure of, 227 tags, 227−233 inline, within HTML text, 232 doclet API, customizing documentation format with, 252 {@docRoot} doc comment tag, 233 documentation for beans, 220 comments (see doc comments) conventions for, 222−233 inheritance of, in doc comment tags, 233 JavaBeans methods, 219 javadoc tool, 252−257 locale, specifying for country and language, 255 undocumented classes in Java implementations, 224 DOM (Document Object Model), 191 DocumentBuilder class, 806 DocumentBuilderFactory class, 807 interfaces representing XML document as DOM tree (W3C), 145 Java binding to core and XML modules, 833 parser for XML, 144, 193 tree representation of XML documents, 194 XML transformation classes, 144 domain names, using in package naming, 83

DomainCombiner interface, 543 double data type, 14, 16, 25 Double class, 26, 151, 391 DoubleBuffer class, 489 infinity, representing, 26 DSA and RSA public and private keys, 143, 598 representing and encoding, 602 DSA encryption algorithm, 267 DSAKey interface, 599 DSAKeyPairGenerator interface, 599 DSAParameterSpec interface, 603 DSAParams interface, 599 DSAPrivateKey interface, 600 DSAPrivateKeySpec interface, 603 DSAPublicKey interface, 600 DSAPublicKeySpec interface, 604 DTDHandler interface, 192 dynamic class creation, 159 dynamic class instantiation, 67 dynamic class loading, 158 JavaBeans, 213 dynamic method lookup, 108 abstract methods, 117

E Editor class, 219 editors bean properties, 214, 299 manager for, 300 PropertyEditorSupport class, 300 for specific type, 219 text, 10 Element interface, 193 elements, array, 14 [ ] access operator, 43 else clause (if/else statements), 47 else if clause, 48 emacs text editor, 10 empty collections, 650 empty interfaces, 122 empty statements, 45 EmptyStackException, 655 enabling assertions, 61 encapsulation of data, 110−115 access control, 111−115 inheritance and, 113

enclosing classes (see containing classes) encode( ) (CharsetEncoder), 182 EncodedKeySpec interface, 604 Encoder class, 287 –encoding enc option (appletviewer), 235 encoding/decoding data characters, 522 text with charsets, 182 tool for, 268 Unicode strings to/from bytes, 143 URLDecoder class, 479 URLEncoder class, 479 XMLEncoder and XMLDecoder classes, 305 encoding, character, 20 EncryptedPrivateKeyInfo class, 744 encryption/decryption of data, 199−201, 738 with Cipher class, 200 input/output streams, 200 encrypted network communication using SSL, 144 package for, 144 with SealedObject class, 201 secret keys, 199 (see also cryptography) end users, security for, 208 enforcing method preconditions, 62 enterprise computing, packages for, 145 EntityResolver interface, 192 Entry interface (Map), 671 Enumeration interface, 656 enumeration implemented as member class (example), 125 implemented as an anonymous class, 133 Iterator interface vs., 662 Enumerator class, 126 defining as local class, 130 environment variables CLASSPATH, 84 javac compiler, 251 setting for interpreter, 248 use by appletviewer, 236 HOME, Windows platforms, 236 JAVA_COMPILER, for JIT, 243

Index

7 March 2002 11:43

933

EOFException class, 56, 333 equal to (= =) operator, 26, 36, 77, 156 equality, comparing strings for, 418 equals( ) Arrays class, 78, 155 Object class, 78 String class, 150 equivalence, testing objects for, 78 Error class, 56, 375, 393 error messages, 56 ErrorHandler interface, 192 errors, 17 assertion, 60, 378 in assertions, 63 checkError( ) (PrintWriter), 362 ErrorManager class, 696 IllegalAccessError, 396 internal, in Java interpreter, 401 Java Virtual Machine, 430 standard error stream for the system, 423 ThreadDeath, 426 Throwable interface and, 428 UnknownError class, 429 escape sequences for ASCII characters, 23 in char literals, listed, 23 in string and char literals, 68 string literals, 27 for Unicode characters, 20 escapes, character, in regular expressions, 149 EUC-JP charset (Japanese text), 183 evaluating expressions, 29 operator associativity and, 32 order of, 34 event model, AWT (Java 1.0 and 1.1), portability and, 225 events bean context-related, 311 BeanContextMembershipEvent class, 311 BeanContextServiceAvailableEvent class, 313 Event class, 218 EventHandler class, 288 EventListener interface, 212, 218, 656 EventListenerProxy class, 657 EventObject class, 212, 218, 657

934

7 March 2002 11:43

Index

EventSetDescriptor class, 213, 289 JavaBeans model, 212 conventions for, 218 listeners for, registering, 216 PreferenceChangeEvent class, 714 PropertyChangeEvent class, 296 SSLSessionBindingEvent, 775 examples in this book available online, xviii @exception doc comment tag, 229 exceptions, 17 arithmetic, 26 ArithmeticException class, 25 bean property accessor methods, 216 catching and handling with jdb debugger, 262 chaining, 439 classes, 56 Exception class, 56, 375, 393 ExceptionListener interface, 290 handlers for, 55 handling with try/catch/finally statements, 57−60 indexed property accessor methods, 216 RuntimeException class, 410 Throwable interface, 375, 428 throwing, 55−57, 65 exclamation point (see !, under Symbols) exclusive file locks, 185 Exclusive OR (boolean XOR operator), 39 exec( ) (Runtime), conventions/rules for, 224 executable JAR files, running programs from, 242 executing files, permission for, 339 ExemptionMechanism class, 745 ExemptionMechanismException class, 746 ExemptionMechanismSpi class, 746 exponentiation, 25, 403 exponentiation functions, 152 export regulations (cryptographic technology), 738 exportPreferences(), 178 Expression class, 291

expression statements, 44 expressions, 15 anonymous class definitions as, 133 assertion, 60 side effects of, 63 combining, caution with, 35 evaluating in loops, 16, 50 continue statement and, 53 initializing and updating loop variables, 52 operators and, 29−43 ( ) (parentheses), use of, 31 arithmetic operators, 34 assignment operators, 40 associativity of operators, 32 bitwise and shift operators, 39 Boolean operators, 37 comparison operators, 36 conditional operator, 41 instanceof operator, 42 operand number and type, 32 order of evaluation, 34 relational operators, 37 return types, 33 side effects, 33 special (language construct) operators, 42 summary of operators, 30 ternary operator, 32 extcheck utility, 238 extending classes, 102 top-level class extending member class, 128 interfaces, 122 extensions, 3 standard, portability and, 225 external programs (processes), Java program communicating with, 196 Externalizable interface, 232, 334 extracting characters and subsequences from readable character sequences, 147 JAR contents, 239

F factorials, computing (example program), 9−18 FactoryConfigurationError class, 808 FailedLoginException class, 801 FeatureDescriptor class, 213, 282, 291 fields accessible to local classes, 131 capitalization/naming conventions, 223 class, 89 in class serialization, 354 classes, 434 date fields in formatted output, 621 defaults and initializers, 96−98 deprecated (@deprecated doc comment tag), 231 Field class, 437 FieldPosition class, 625 Format.Field class, 626 GetField class, 350 inheritance in subclassing, 102 inherited, initializing, 103 input, output, and error (system), 423 instance, 89, 91 MessageFormat.Field class, 628 NoSuchFieldError, 404 NoSuchFieldException, 404 NumberFormat.Field class, 630 ObjectOutputStream.PutField, 353 references to, in @see doc comment tag, 231 serializing multiple class versions or implementations, 352 static, final, in interfaces, 118 superclass, shadowing, 106 method overriding vs., 107 File class, 165, 323, 334 additional functionality (Java 1.2), 165 listing files in a directory, 133 file pointer, 185 file separators, 234 file structure, 83 file: protocol, 171

Index

7 March 2002 11:43

935

FileChannel class, 183 file locks, exclusive and shared, 185 memory mapping a file, 184 random access to file contents, 185 FilenameFilter interface, 133, 338 filenames, 11 concatenating to directory name, 225 hardcoded, portability and, 225 files, 165 associated with unused objects, closing or deleting, 100 binary, reading, 167 class, 84 FileDescriptor class, 336 FileFilter interface, 337 FileHandler class, 697 FileInputStream class, 165, 323, 337 SecurityManager and, 205 FilenameFilter interface, 323, 338 FileNameMap interface, 455 FileNotFoundException, 56, 338 FileOutputStream class, 323, 338 FilePermission class, 206, 339 FileReader class, 340 FileWriter class, 340 FilterInputStream class, 341 input/output, 183−185 copying file (example code), 183 memory mapping a file with FileChannel, 184 RandomAccessFile class, 323, 364 read permission for untrusted applets, 236 reading binary data from arbitrary locations in, 166 text, reading, 167 write permission for untrusted applets, 236 ZipFile class, 735 fill( ) (Arrays), 155 Filter interface, 699 FilterInputStream class, 323 FilterOutputStream class, 323, 341 FilterReader class, 342 FilterWriter class, 342

936

7 March 2002 11:43

Index

final modifier, 89, 138 classes, 103 abstract methods and, 116 local classes and, 131 in local method definitions, 130 method lookup, 109 in variable declarations, 46 finalize( ), 100 finalizing objects, 98−101, 423 finalizers, 100 chaining and, 105 finally clause, 59 firewalls, appletviewer and, 237 flip( ), 182 float data type, 25 infinity, representing, 26 floating-point data types, 25, 143, 152, 444 % (modulo) operator and, 35 / (division) operator, returning, 34 BigDecimal class, 153 converting to integer types, 28 converting to integers, 28 double, 14 Float and Double wrapper classes, 26 Float class, 151, 394 FloatBuffer class, 490 strictfp modifier, 139 testing for NaN, 36 floor( ) (Math), 28 flow control statements, 15, 43 return statement, 15, 17 for loops array indexing in, 71 continue statement, starting new iteration, 53 empty loop body, 45 initializing, testing, and updating variables, 51 Format class, 625 Field class, 626 Formatter class SimpleFormatter class, 708 XMLFormatter class, 709 formatting anonymous class definitions, 135 dates and times, 619 ftp: protocol, 171

fully qualified class names, 81, 242 references to classes in other packages, 82 functions, 19 mathematical, 152 (see also methods)

G garbage collection, 79, 86, 98, 431 classes, disabling for, 247 forcing to run synchronously, 410 incremental, interpreter option for, 246 jdb debugger command for, 263 OutOfMemoryError, 407 phantom references, 432 printing message upon occurrence, 246 system, 423 weak references, 433 WeakHashMap class, 688 GatheringByteChannel interface, 181 GeneralSecurityException class, 543 generating quick-reference material, xix Generic Security Services (GSS) API, Java binding of, 145, 826 get and set property accessor methods, 212−214 conventions, 215 bound properties, 216 constrained properties, 217 indexed properties, 216 getChannel( ), 183 getCurrencyInstance() (NumberFormat), 152 getenv( ) (System), 224 getFD( ), 336 GetField class, 350 getLogger( ) (Logger), 178 getMessage( ), 56 getProperty() (System), 176 getResource( ), 221 getResourceAsStream( ), 221 getService( ), 221 global variables class fields as, 90 Java, not existing in, 85

graphical user interfaces (see GUIs) graphics, packages for, 145 greater than (>) operator, 16, 37 greater than or equal (>=) operator, 37 GregorianCalendar class, 658 Group interface, 571 Guard interface, 544 GuardedObject class, 534, 544 GUIs (graphical user interfaces) availability of for Java VM, 285 beans as components, 211 beans, specifying need for , 304 changes in bound properties of components, 282 packages for, 145 GZIPInputStream class, 732 GZIPOutputStream class, 732

H halting a system, 409 hand-held devices Java 2 Platform, Micro Edition (J2ME), 6 Java interpreter for, 4 Handler class, 699 handlers for exceptions, 55 try/catch/finally statements, 57−60 HandshakeCompletedEvent class, 765 hardcoded filenames, conventions/ rules for, 225 hashcode, computing for objects, 423 HashMap class, 156, 658 LinkedHashMap class, 663 HashSet class, 659 LinkedHashSet class, 664 Hashtable class, 156, 660 Properties subclass, 176 hashtables, causing memory leaks, 100 hasService( ), 221 help javadoc-generated documentation, 254 javap tool, 260 hexadecimal numbers, 25 hiding data, 110−115 access control, 111−115 inheritance and, 113

Index

7 March 2002 11:43

937

hierarchy, class, 80 containment hierarchy vs., 129 superclasses, Object class and, 103 HOME environment variable Windows platforms, 236 HostnameVerifier interface, 766 hosts interpreter, connecting to jdb debugger, 261 UnknownHostException, 472 HotSpot VM client and server versions, 243 interpreted mode without JIT, 246 HTML tags (hyperlinks) tag, avoiding, 227 for applets, 234 in doc comments, 225, 227
 tag, 227 HTTP server, 174 http: protocol, 171 https: protocol, 171, 764 SSL as basis of, 173 HttpsURLConnection class, 767 HttpURLConnection class, 455 hyperlinks or cross references in doc comments, 227

I identifiers, 21 assert, 60 method names, 65 identity certificates (see certificates) Identity class, 544 IdentityHashMap class, 156, 661 IdentityScope class, 545 if statements, 15 assertions in, 62 if/else statements, 46 else if clause, 48 IllegalAccessError class, 396 IllegalAccessException class, 396 IllegalArgumentException, 396 IllegalBlockSizeException, 746 IllegalMonitorStateException class, 397 IllegalStateException, 397 IllegalThreadStateException class, 397 images in doc comments, 227 immutability of String objects, 145

938

7 March 2002 11:43

Index

implementation of interfaces, 119 local and anonymous class, 137 member class, 137 of methods, 64 of multiple interfaces, 121 portable Java code, conventions/ rules for, 224 static member classes, 136 implements (keyword), 119 implies( ) method, Permission subclasses, 207 importing classes and packages, 82 static member classes, 125 importPreferences(), 178 IncompatibleClassChangeError, 398 increment (++) operator, 33, 35 incrementing array index variable, 71 counter variable for loop, 50 in expression statements, 44 indentation anonymous class definitions and, 135 in doc comments, code examples and, 227 nested statements, 15, 47 index files, javadoc, not generating, 255 indexed properties, 213 conventions for, 216 IndexedPropertyDescriptor class, 292 indexes array, 43, 70 generating multiple index files, javadoc, 256 JAR files, 240 IndexOutOfBoundsException, 398 Inet4Address class, 457 Inet6Address class, 458 InetAddress class, 448, 458 InetSocketAddress class, 186, 459 infinite loops, 50 for(;;), 52 infinity, 26 % (modulo) operator and, 35 Inflater class, 733 InflaterInputStream class, 733

info( ), 178 InheritableThreadLocal class, 398 inheritance, 80 access control and, 113 {@inheritDoc} doc comment tag, 233 interfaces, constants in definitions, 119 method implementations, 140 scope vs., for member classes, 129 subclasses and, 101−110 class hierarchy, 103 constructor chaining and the default constructor, 104 fields and methods, 102 overriding superclass methods, 107−110 shadowing superclass fields, 106 subclass constructors, 103 initialization vectors (Cipher), 741, 759 initializers, 96−98 ExceptionInInitializerError, 394 IllegalAccessException, 396 static, 139 in variable declarations, 46 initializing arrays, 72 multidimensional, 73 fields, inherited, 103 loop variables, 51 objects, 94−98 inline tags (doc comment), 232 inner classes, 122 anonymous, 123 how they work, 136−138 local classes as, 123 member classes, 125−129 input streams BufferedInputStream class, 324, 326 BufferedReader class, 327 ByteArrayInputStream class, 323, 328 CharArrayReader class, 329 CheckedInputStream class, 728 CipherInputStream class, 200, 743 DataInputStream class, 324, 331 DigestInputStream class, 542 FileInputStream class, 165, 323, 337 FilterInputStream class, 323, 341 FilterReader class, 342

GZIPInputStream class, 732 InflaterInputStream class, 733 InputStream class, 323, 343 InputStreamReader class, 344 JarInputStream class, 693 LineNumberInputStream class, 346 LineNumberReader class, 347 ObjectInputStream class, 324, 348 GetField class, 350 PipedInputStream class, 323, 358 PipedReader class, 359 PushbackInputStream class, 363 PushbackReader class, 364 Reader class, 366 SequenceInputStream class, 367 StringBufferInputStream class, 370 StringReader class, 370 ZipInputStream class, 736 input/output, 142 classes for (java.io package), 81, 323 displaying output, 14 input values, checking validity of, 15 InterruptedIOException class, 345 IOException class, 346 JAR files, reading from/writing to standard output, 239 for keytool program, 267 New I/O API, 179−191 buffer operations, 179 channel operations, 181 CharBuffer interface, 147 client-side networking, 186 encoding and decoding text with charsets, 182 files, working with, 183−185 nonblocking I/O, 143, 187−191 NotActive Exception, 347 ObjectInput interface, 348 ObjectInputValidation class, 351 ObjectOutput interface, 351 ObjectStreamClass class, 354 ObjectStreamConstants interface, 355 ObjectStreamException class, 356 OptionalDataException class, 357 profiling output, printing to standard output, 247

Index

7 March 2002 11:43

939

input/output (continued) for Socket objects, 466 StreamCorruptedException, 368 streams, 166−171 arrays and strings, streaming data to/from, 169 compressing data and writing to file, 168 console input, reading, 166 InputStream class, 166 message digests, computing, 168 OutputStream class, 166 piped, thread communication with, 169 printing text to output stream, 167 reading binary file, 167 reading lines from text file, 167 system, 423 thread blocking during, 164 for URL connections, 477, 479 (see also input streams; output streams) installed extensions, checking for, 238 instance fields, 89, 91 default initialization of, 96 interfaces and, 118 superclass, shadowing, 106 instance initializers, 98 substituting for constructors, 134 instance methods, 89, 91−94 choosing between instance and class methods, 93 interfaces, 118 overriding superclass methods, 107−110 synchronized, 55 instanceof operator, 42 marker interfaces, identifying with, 122 instances, class creating, 386, 436 creating dynamically, 67 InstantiationError class, 399 InstantiationException class, 399 integer literals, 25

940

7 March 2002 11:43

Index

integers, 399 % (modulo) operator and, 35 arbitrary precision, package for, 143 arbitrary-precision, math, 444 BigInteger class, 153, 446 int data type, 13, 399 IntBuffer class, 491 Integer class, 13, 25, 151, 399 integer types, 24 array access ([ ]) operator and, 33 in array index values, 70 converting to/from floatingpoint types, 28 wrapper classes for, 25 (see also primitive data types) interfaces, 66, 117−122 abstract classes vs., when to use, 120 abstract modifier in declarations, 138 capitalization/naming conventions, 222 as data types, 120 defining, 118 deprecated (@deprecated doc comment tag), 231 dynamic proxies, implementing with, 159 extending, 122 implementing, 119 multiple, 121 InstantiationError, 399 InstantiationException, 399 local scope and, 130 marker, 122 member classes, inability to define as, 127 modifiers, summary of, 138−140 references to, in @see doc comment tag, 229 as static member classes, 123 features of, 124 restrictions on, 125 InternalError, 401

internationalization, 8 applications, package for, 143 comparing human-readable strings with Collator class, 150 currency formatting, 653 date and time formatting, 154, 619 formatting numbers for different locales, 152, 622, 628 java.text package, 609 Locale class, 668 locale, specifying for documentation, 255 localized resources for, 676 sorting text strings for locales, 618 string case conversions, 417 Internet domain names, using in package naming, 83 interpreted mode, operating HotSpot VM in, 246 interpreter (see Java interpreter; JVM) interrupt( ), 164 interrupted( ) (Thread), 164 InterruptedException class, 164, 401 InterruptedIOException class, 345, 453 InterruptibleChannel class, 164 interrupting threads, 426 introspection (JavaBeans), 213, 216 IntrospectionException class, 293 Introspector class, 213, 282, 284, 293 InvalidAlgorithmParameterException, 546 InvalidClassException class, 345 InvalidKeyException, 546 InvalidKeySpecException, 604 InvalidMarkException class, 492 InvalidObjectException, 345 InvalidParameterException, 547 InvalidParameterSpecException, 605 invisible beans, 212 InvocationHandler interface, 159, 434, 438 InvocationTargetException, 439 invoking methods, 12 ( ) (method invocation) operator, 43 class methods, 90 constructors, from another constructor, 95 in expression statements, 44

instance methods, 92 overridden, 109 IOException class, 346 isBound( ) (PropertyDescriptor), 216 isDesignTime( ), 221 isInterrupted( ), 164 isNaN( ) Double class, 36 Float class, 36 ISO Latin-1 character set, 20 iterations, 17 CharacterIterator interface, 615 CollationElementIterator interface, 616 ListIterator interface, 667 in loops, starting new with continue statement, 53 StringCharacterIterator class, 634 Iterator interface, 156, 662 IvParameterSpec class, 759

J J2EE (Java 2 Platform, Enterprise Edition), 6 JAAS (Java Authentication and Authorization Service), 144 JAR files, 238 classes for reading and writing, 689 digital signatures for, 205 executable, running program in, 242 extension, checking whether installed, 238 JavaBeans, conventions for, 220 manifest, 690, 694 package for, 143 retrieving, 460 running programs by specifying, 85 (see also jar tool; jarsigner tool) jar tool, 238−241 files, 240 options, syntax of, 239 JarEntry class, 689, 691 JarException class, 692 JarFile class, 689, 692 JarInputStream class, 693 JarOutputStream class, 694 jarsigner tool, 241

Index

7 March 2002 11:43

941

JarURLConnection class, 460 Java, 3−8 benefits of, 6−8 case sensitivity, 10 learning, 20 performance, 8 platform, 3 programming language, 3 strong typing in, 13 versions, 5 1.1, security and, 203 1.2, 4 Virtual Machine, 3 Java 2 Platform, 4 Enterprise Edition, 6 Micro Edition, 6 Java API, 14, 202 java command, 84 Java Cryptography Extension (JCE), 204, 534, 738 Java Development Kit (see SDK) Java Documentation Generator (see javadoc program) .java file extension, 83 Java interpreter, 4, 242−248 classpaths, specifying for, 84 evaluating expressions, 16, 29 garbage collection, 99 InternalError, 401 java command-line program, 10 jdb debugger, connection to, 261 just-in-time (JIT) compiler, specifying, 243 loading classes, 247 main( ) method, 12 OutOfMemoryError, 407 running programs, 84 StackOverflowError, 414 threading system, specifying, 244 versions, 243 Java Keystore (JKS) type, 242, 268 Java language, 3 C programming language, differences between, 85−87 java.lang package, 81, 374 modifiers, summary of, 138−140 as pass-by-values language, 79 resources for further information, 19 syntax, 19−87

942

7 March 2002 11:43

Index

Java Native Interface (JNI), 258 Java platform, 3, 142−201 arrays, 155 collections, 156−158 cryptography, 199−201 dates and times, 154 files and directories, 165 input/output streams, 166−171 JAXP (Java API for XML Processing), 191−196 Logging API, 178 Microsoft proprietary extension of, 224 networking, 171−176 JSSE (Java Secure Sockets Extension), 172 New IO API, 179−191 numbers and math, 151−153 packages, 81 key, listing of, 142−145 Preferences API, 177 processes (programs running external to interpreter), 196 security, 196−199 Standard Edition, 6 strings and characters, 145−151 threads, 160−165 “Write once, run anywhere”, 6 Java Plug-in, 6 Java programming commercial products for, 9 conventions for, 222−233 example program, 9−18 Java language (see Java language) network-centric, 7 object-oriented, 88−141 online resources, xvii online tutorial, 17 related books on, xvi Java Runtime Environment (see JRE) Java Secure Sockets Extension (JSSE), 172, 764 java utility, 242−248 versions, 243 java.awt package, 145, 211 java.awt.peer package, conventions/ rules for, 224 java.beans package, 142, 211, 282−306

java.beans.beancontext packages, 142, 211, 214, 221, 306−322 JAVA_COMPILER environment variable, 243 java.io package, 81, 142, 166, 323 RandomAccessFile class, 166 serializing/deserializing objects, 170 stream classes for reading from/ writing to arrays and strings, 169 stream classes, piped, 169 java.lang package, 81, 142, 151, 374 java.lang.ref package, 143, 431 java.lang.reflect package, 143, 158, 434 java.math package, 143, 153, 444 java.net package, 81, 143, 171, 448 java.nio package, 179 java.nio.channels package, 179, 181, 495 server-side networking, 187 java.nio.charset package, 179, 182 java.policy file, 208 java.security package, 143, 196, 533 digital signatures, 205 message digests, 168 java.security.acl package, 143, 570 java.security.auth package, 144 java.security.cert package, 143, 573 java.security.interfaces package, 143, 598 java.security.spec package, 143, 602 java.text package, 143, 609 java.util package, 81, 143, 635 collections, working with, 156 java.util.jar package, 143, 689 java.util.logging package, 143, 178 java.util.prefs package, 143, 177 java.util.zip package, 144, 168, 727 JavaBeans, 142, 211−221, 282−322 bean basics, 212−214 bean context, 214 customizing beans, 214 event model, 212 introspection mechanism, 213 methods, 213 Persistence API, 214 properties, 212 properties, specialized subtypes, 213 @beaninfo doc comment tag, 232

component model, 221 conventions, 214−220 auxiliary classes provided by a bean, 219 bean packaging and distribution, 220 beans, 215 bound properties, 216 constrained properties, 217 events, 218 indexed properties, 216 for methods, 219 properties, 215 customizing, auxiliary classes for, 220 serialization mechanism for components, 170 specification, web site, 212 javac compiler, 10, 248−251 assert statements, handling, 60 character encoding required by, 268 options, 249−251 javadoc program, 21, 252−257 customizing documentation format, 252 HTML documentation, creating, 225 javah program, 257 javakey program, 205 javap class disassembler, 259 javaw interpreter, 243 javaw_g interpreter, 243 javax.crypto package, 144, 199, 204, 738 javax.crypto.interfaces package, 144, 754 javax.crypto.spec package, 144, 756 javax.net package, 144 JSSE (Java Secure Sockets Extension), 172 javax.net.ssl package, 144 JSSE (Java Secure Sockets Extension), 172 javax.security.auth.callback package, 144 javax.security.auth.kerberos package, 144 javax.security.auth.login package, 144 javax.security.auth.spi package, 144

Index

7 March 2002 11:43

943

javax.security.auth.x500 package, 144 javax.swing package, 145, 211 javax.xml.parsers package, 144, 191 javax.xml.transform package, 191, 194 javax.xml.transform.sax package, 144 javax.xml.transform.stream package, 145 JAXP (Java API for XML Processing), 191−196 SAX parser, 192 transforming XML documents, 194 JCE (Java Cryptography Extension), 204, 534, 738 JCEKS keystore, 242 jdb debugger, 261−265 commands, 262−265 options, 261 JDK (Java Development Kit) (see SDK) JIT (just-in-time) compilers, 4, 391 using with frequently used methods, 247 performance improvements with, 8 specifying for Java interpreter, 243 JKS (Java Keystore) type, 242, 268 join( ) (Thread), 162, 164 JRE (Java Runtime Environment), 6 SDK vs., 9 JSSE (Java Secure Sockets Extension), 172, 764 just-in-time compilers (see JIT compilers) JVM (Java Virtual Machine), 3 array initialization, 72 interpreted mode without JIT (HotSpot), 246 jdb debugger, connecting to, 261 performance tuning and optimization, 8 security, 203 UnknownError, 429 versions, 243 VirtualMachineError, 430

944

7 March 2002 11:43

Index

K Kerberos protocol, authentication, 144 KerberosKey class, 795 KerberosPrincipal class, 796 KerberosTicket class, 796 key-agreement algorithms, 747 KeyAgreement class, 747 KeyAgreementSpi class, 748 KeyGenerator class, 749 KeyGeneratorSpi class, 749 KeyManagementException class, 549 KeyManager interface, 767 KeyManagerFactory class, 768 KeyManagerFactorySpi class, 769 KeyPair class, 549 KeyPairGenerator class, 534, 550 KeyPairGeneratorSpi class, 550 keys, cryptographic converting between Key and KeySpec, 548 DES key, 757 DSAKey interface, 599 invalid, 546 Key interface, 547 KeyException class, 547 KeyFactorySpi class, 548 KeySpec interface, 605 password-based, 756 RSA, 600 secret keys (symmetric), generating, 749 SecretKey interface, 752 triple-DES key (DESede), 756 UnrecoverableKeyException, 569 keystore, 265 password, changing, 266 KeyStore class, 534, 551 KeyStoreException class, 552 keystores, 265 –keystore url option, jarsigner, 241 for policy files, 269 type, specifying, 242, 268 (see also keytool program)

KeyStoreSpi class, 552 keytool program, 199, 265−268 commands, 265 options, 267 keywords, 22 abstract, 116 for access control, 111 assert, 60 break, 52 case, 49 extends, 102 final, 46 if, 15 implements, 119 import, 82 interface, 118 lines, 250 listing of, 22 new, 67 null, references, assigning null value, 78 package, 82 private, 105 public, 105 source, 250 static, 91 member classes and, 123 static initializers, 97 summary of, 138−140 super, 103, 109 referring to superclass members of containing class, 127 switch, 49 synchronized, 55 throws, 65 vars, 250 void, 54, 65 (see also modifiers)

L labeled statements, 45 continue statement, 53 language constructs, 42 LanguageCallback class, 792

languages, 78 European, numbers in, 152 international, representing with Unicode, 8 (see also programming languages) last-in-first-out (LIFO) stacks, 680 LastOwnerException class, 572 Latin-1 character set, 20, 182 escape sequences, 24 reading from input channel, converting to UTF-8, and writing to output channel, 185 LDAPCertStoreParameters class, 588 left shift (>) operator, signed , 40 right-to-left associativity, 32 root directories, listing, 334 root directory of generated documentation, 233 round( ) (Math), 28 rounding numbers, 28 functions for, 152

958

7 March 2002 11:43

Index

RowSet class, 211 RSA and DSA public and private keys, 598 representing and encoding, 602 RSAKey interface, 600 RSAKeyGenParameterSpec interface, 606 RSAMultiPrimePrivateCrtKey interface, 600 RSAMultiPrimePrivateCrtKeySpec class, 606 RSAOtherPrimeInfo class, 607 RSAPrivateCrtKey interface, 601 RSAPrivateCrtKeySpec interface, 607 RSAPrivateKey interface, 601 RSAPrivateKeySpec interface, 608 RSAPublicKey interface, 598, 602 RSAPublicKeySpec interface, 608 RuleBasedCollator class, 632 rules, 214 pure Java, 223−225 (see also conventions) run( ), 160 runFinalizersOnExit( ) (Runtime), 101 Runnable interface, 160, 409 running Java programs, 10, 84 Runtime class, 375, 409 exec( ), using on portable code, 224 runtime environment, Java, 3, 6 (see also JRE) RuntimeException class, 56, 410 RuntimePermission class, 206, 411

S sandbox (Java 1.0), access control policies, 204 SAX (Simple API for XML), 848 API, 191 extensions to basic SAX2 API, 861 packages for, 145 parsing XML, 192 representing XML documents as method call sequences, 194 utility classes for SAX parsers, 863 XML transformation classes, 145 SAX parser, 191 SAXParser class, 192, 809

SAXParserFactory class, 810 ScatteringByteChannel interface, 181 scheduling tasks, 681 scientific notation, 25 scope, 14, 46 vs. inheritance for member classes, 129 local classes, 131 local variables, local classes and, 132 SDK (Software Development Kit), 6 appletviewer tool, 234−238 commercial products for different platforms, 9 extcheck tool, 238 jar tool, 238−241 jarsigner utility, 241 java interpreter, 242−248 javac compiler, 10, 248−251 javah tool, 257 javap class disassembler, 259 keytool, 265−268 native2ascii tool, 268 policytool, 269 serialver tool, 270 Sun Microsystems, download site, 9 tools, 234−270 sealed packages, 408 SealedObject class, 201, 752 search and replace operations using regular expressions, 149 in strings, 417 searching arrays, 155 collections elements, 157 SecretKey interface, 199, 752 SecretKeyFactory class, 753 SecretKeyFactorySpi class, 754 SecretKeySpec class, 760 secure hash (see message digests) Secure Hash Algorithm (SHA), 270 SecureClassLoader class, 563 SecureRandom class, 534, 563 SecureRandomSpi class, 564 security, 7, 196−199, 202−210 access control, 204−207 applets, restrictions on, 204 fine-tuning trust levels, policies, and permissions (Java 1.2), 206

java.security.acl package, 570 permissions and policies, 206 the sandbox, 204 appletviewer, 236 network access for untrusted applets, 237 for application programmers, 207 architecture, 203 authentication and authorization packages, 144 authentication and cryptography, 204 certificates (see certificates) digital signatures, 197 digitally signed classes, 205 DSA and RSA public and private key representations, 602 for end users, 208 GeneralSecurityException, 543 interfaces package, 598 Java binding of Generic Security Services API, 145, 826 Java VM access restrictions, 203 byte-code verification, 203 java.security package, 143, 533 java.security.cert package, 143 message digests, 168, 196 packets, sending/receiving, 453 permissions (see permissions) risks, 202 secure HTTP (https: protocol), 171 Secure Sockets Layer (see SSL) SecureRandom class, 153 Security class, 564 SecurityException, 412 SignedObject class, 198 for system administrators, 208 for system programmers, 207 system properties, granting access to, 674 tool for policy configuration files, 269 URLClassLoader class, 476 security policies, 206 default, defined by system administrators, 208 Policy class, 557, 785

Index

7 March 2002 11:43

959

security policies (continued) querying and setting, 565 user-defined, augmenting or replacing system policy, 208 security providers, 561 managing list of installed, 564 NoSuchProviderException, 555 SecurityManager class, 204, 412 default SecurityManager object, defining system property for, 209 delegation of access requests to AccessController, 206 installing, 208 system, 423 use by FileInputStream class, 205 SecurityPermission class, 565 @see doc comment tag, 229 @see tags, 233 seeding pseudo-random number generator, 675 select( ) (Selector), 164 selector interfaces and classes for nonblocking I/O, 143 self-reflection, 158 self-signed certificate authority certificates, 268 semicolon (see ;, under Symbols) separators, file/path, 234 SequenceInputStream class, 367 sequential data (see streams, input/ output) SereverSocketFactory class, 762 @serial doc comment tag, 231 @serialData doc comment tag, 232 @serialField doc comment tag, 231 Serializable interface, 122, 367 SerializablePermission class, 368 serializing objects, 170 JavaBeans components, 170 serializing/deserializing objects (see object serialization) serialPersistentFields, 231 serialver program, 270 server sockets, factory classes for creating, 144 server version of VM (Sun HotSpot), 243 server-side networking, 187

960

7 March 2002 11:43

Index

servers blocking I/O and, 187 communicating directly with, using sockets, 172 NonBlockingServer class (example), 187−190 recognizing and accepting client connection requests, 174 ServerSocket class, 174, 187, 448, 464 service provider interface (see SPI) ServicePermission class, 797 services protocol (JavaBeans), 221 servlets, 12 setBeanContext( ) (BeanContextChild), 221 sets, 156, 650 AbstractSet class, 640 HashSet class, 659 hashtable-based, 156 LinkedHashSet class, 664 Set interface, 677 SortedSet interface, 680 TreeSet class, 685 severe(), 178 severity levels, log messages, 178, 700 shadowing class methods, 110 superclass fields, 106, 127 class fields, 106 method overriding vs., 107 shared file locks, 185 shift operators, 39 combining with assignment (=) operator, 41 Short class, 25, 151, 413 short data type, 24 comparing to float type with = = operator, 36 ShortBuffer class, 494 ShortBufferException, 754 shutdown hooks, adding and removing, 409 side effects expression in assertion expressions, 63 in expression statements, 44 of operators, 33 Signature class, 534, 566 SignatureException class, 567

signatures, method, 64 this keyword and, 92 SignatureSpi class, 567 signed right shift (>>) operator, 40 SignedObject class, 198, 534, 568 Signer class, 568 signer name, 241 simple names, classes, 82 SimpleBeanInfo class, 284, 301 SimpleDateFormat class, 632 SimpleFormatter class, 708 SimpleTimeZone class, 678 @since doc comment tag, 231, 233 javadoc, ignoring in doc comments, 255 single-line comments, 20 sleep( ) (Thread), 161, 164 socket connection, nonblocking, 190 socket( ), 186 sockets BindException, 450 ConnectException, 451 DatagramSocket class, 448, 452 DatagramSocketImpl class, 454 factory classes for creating, 144 InetSocketAddress class, 459 javax.net package, 762 MulticastSocket class, 448, 461 ServerSocket class, 464 ServerSocketFactory class, 762 Socket class, 172, 187, 448, 466 SocketAddress class, 186, 468 SocketChannel class, 186 SocketException, 469 SocketFactory class, 763 SocketHandler class, 708 SocketImpl class, 469 SocketImplFactory interface, 470 SocketOptions interface, 470 SocketPermission class, 206, 471 SocketTimeoutException, 472 SSL (Secure Sockets Layer), 763, 776 (see also SSL) unable to connect to remote host, 463 SoftReference class, 431, 433 software components package for, 142 reusable, 211

Software Development Kit (see SDK) Solaris operating system Java interpreter, 4 SDK, download site (Sun), 9 thread type for Java interpreter and Classic VM, specifying, 244 sort( ) (Arrays), 155, 642 sorted sets and maps, 156 SortedMap interface, 679 SortedSet interface, 680 sorting collections elements, 157 -source 1.4 (javac command-line argument), 60 source code, converting to ASCII, 268 source files for classes being debugged, setting for jdb, 262, 264 path, specifying for javac compiler, 250 search path for (javadoc), 256 Source interface, 194 source keyword, 250 spaces in doc comments, 227 special effects, threads for, 161 SPI (service provider interface) cryptographic-authentication features, 534 javax.crypto package, 738 split( ) Pattern class, 149 String class, 149 SSL (Secure Sockets Layer), 144, 172, 763 handshake completed event, 765 hostname verifier, 766 https: protocol, URL connections using, 767 javax.net.xxl package, 144 key managers, 767 trust managers, 778 X509TrustManager, 780 X509KeyManager interface, 780 SSLContext class, 769 SSLContextSpi class, 770 SSLException class, 770 SSLHandshakeException class, 771 SSLKeyException class, 771 SSLPeerUnverifiedException class, 771 SSLPermission class, 771

Index

7 March 2002 11:43

961

SSLServerSocket class, 772 SSLServerSocketFactory class, 773 SSLSession class, 774 SSLSessionBindingEvent class, 775 SSLSessionBindingListener interface, 775 SSLSessionContext interface, 775 SSLSocket class, 776 SSLSocketFactory class, 777 stack traces displaying for current or specified threads, 265 for exceptions, 56 StackOverflowError, 414 stacks call, encapsulation of state, 536 EmptyStackException, 655 LinkedList, using as, 665 specifying size for a thread, 424 Stack class, 680 StackTraceElement class, 415 standard extensions additional information about, 145 conventions/rules for, 225 standard output (see input/output) start( ) (Thread), 160 state beans, 212 writing persistently into XML file, 214 changes in, notifications of, 672 IllegalStateException, 397 object, writing complete to serialization stream, 232 threads, IllegalThreadStateException, 397 Statement class, 302 statements, 13, 43−64 assert, 60−64 break, 52 compound, 16, 45 continue, 53 do/while, 51 empty, 45 expression, 44 flow-control, 15 return statement, 15 for, 51 if/else, 46 else if clause, 48

962

7 March 2002 11:43

Index

Java, summary of, 44 labeled, 45 local variable declaration, 45 return, 54 switch, 48−50 synchronized, 54 throw, 55−57 try/catch/finally, 57−60 while, 50 static (keyword), 12 static class members, 88 class fields, 89 methods, 90 static initializers, 97 static member classes, 123 features of, 124 implementation, 136 implementation of, 136 importing, 125 restrictions on, 125 static modifier, 139 abstract modifier and, 116 anonymous classes and, 134 local classes and, 130 member classes and, 123 method lookup, 109 stop( ) (Thread), 161, 424 StreamCorruptedException class, 368 StreamHandler class, 709 streams, input/output, 166−171 arrays of bytes or text strings, reading from/writing to, 169 compressed data, writing to file, 168 console input, reading, 166 FileInputStream class, 183 FileOutputStream class, 183 Java program communicating with external process, 196 java.io package, 142 message digests, computing, 168 piped, thread communication with, 169 printing text to output streams, 167 reading lines from text file, 167 reading ZIP files, 168 XML, transformation classes for, 145, 194 StreamTokenizer class, 368

strictfp modifier, 139 StrictMath class, 415 string literals, 67 StringBuffer class, 419 StringReader class, 169 strings, 27, 145−151 arrays of, 12 AttributedString class, 612 basic operations on, 145 comparing, 150 concatenating, 35, 420 converting bytes to, 379 converting numbers to, 615 converting numbers to/from, 151 converting other data types to, 35 converting to arrays, 417 converting to integer values, 25 converting to integers, 399 converting to longs, 401 converting to/from shorts, 413 equivalence, testing for, 78 instanceof operator, using with, 42 manipulation methods, implemented in machine code, 8 parsing errors in, 631 pattern matching with regular expressions, 148 sorting for different locales, 618 streaming data, reading from/writing to, 169 String class, 145, 374, 416 creating instances of, 67 inheritance from Object class, 80 StringBuffer class, 147, 419 StringBufferInputStream class, 370 StringCharacterIterator class, 634 StringIndexOutOfBoundsException, 421 StringReader class, 370 StringTokenizer class, 150, 681 StringWriter class, 169, 370 Unicode, converting to/from bytes, 143 stub files for C language Java native method implementation, 258 subclasses abstract implementing abstract methods, 116 partial implementation of, 121

concrete, 116 constructors, 103 inheritance and, 101−110 constructor chaining and the default constructor, 104 overriding superclass methods, 107−110 shadowing superclass fields, 106 superclasses and Object class, 103 Thread class, 160 subinterfaces, 122 Subject class, 782, 786 SubjectDomainCombiner class, 788 subroutines (see methods) Subset class, 383 UnicodeBlock class, 383 substrings comparing, 416 converting portion of StringBuffer to a String, 420 subtraction (-) operator, 34 Sun Microsystems “100% Pure Java” portability certification program, 225 HotSpot VM, 243 Java packages controlled by, 83 SDK download site, 9 SunJCE cryptographic provider, 738 cryptographic algorithms supported, 740 Diffie-Hellman key-agreement algorithm, 747 key-generation implementations, supporting, 749 message authentication algorithms, 750 padding schemes, 740 RC5 encryption algorithm and, 760 SecretKeyFactory implementations, 753 super (keyword), 103 overridden methods, invoking, 109 super( ), vs. super keyword, 110 superclasses, 103 containing class members, accessing, 127 fields, shadowing in subclasses, 106

Index

7 March 2002 11:43

963

superclasses (continued) inheritance by subclasses of method implementations, 140 methods, overriding, 107−110 Object class as root of hierarchy, 103 Swing programming, 211 switch statements, 48−50 assertions in, 62 case labels, 49 symmetric keys, 199, 753 generating, 749 SyncFailedException class, 371 synchronized methods, 162 Collections class, 650 HashSet class, 659 LinkedList class, 664 TreeMap class and, 685 synchronized modifier, 55, 139 synchronized statements, 54 synchronizing threads, 162, 406 deadlock, avoiding, 163 IllegalMonitorStateException, 397 system administrators, security for, 208 System class, 155, 375, 422 getenv( ), lack of portability, 224 system classes javap tool, specifying search path for, 259 path to search for (javah), 258 portable Java code and, 225 system preferences, 715 java.util.prefs package, 710 package for reading and writing, 143 Preferences class, 177 system programmers, security for, 207 system properties applets, allowing to read, 237 appletviewer, use by, 236 java.security.manager, defining, 209 Properties class, using for, 176 read and write access control, 674 system resources, permissions for, 555 system security policy, replacing with user-defined, 209 systemNodeForPackage( ) (Preferences), 177

964

7 March 2002 11:43

Index

T tabs, 15 taglet classes, classpath for, 257 tags doc comment 227−233 inline, within HTML text, 232 listing of, 227−233 HTML for applets, 234 in doc comments, 227 target names, permissions, 207, 209 targets for permissions, 270 tasks, scheduling, 681 temporary files creating, 335 deleting, 100 terminating lines with platform-specific separators, 225 ternary operator, 32, 41 testing assertions, enabling for, 60 loop variables, 51 method argument values with assert statement, 62 text Arabic and Hebrew, bidirectional algorithm for, 613 attribute keys for multilingual, 611 CharacterIterator interface, 615 displaying, 167 internationalized, package for, 143, 609 line breaks, 614 outputing to file, 167 reading from files, 340 strings of (see strings) text editors, 10 text files input/output channels, reading from and writing to, 185 reading, 167 Text interface, 193 TextInputCallback class, 793 TextOutputCallback class, 793 this (keyword), 92 accessing shadowed field through vs. invoking overridden method with super, 109

this (keyword) (continued) explicit reference to containing instance of this object, 127 invoking one constructor from another, 95 this( ) calling one constructor from another, 96 field initialization code and, 97 thread groups in debugging, 264 threads, 160−165 communicating with piped I/O streams, 169 deadlocked, 163 IllegalThreadStateException, 397 inheritance, 398 InterruptedException, 401 interrupting, 164 jdb commands, specifying for, 261 operating on other threads, 424 priority levels for, 160 safety, 650, 660, 686 sleeping, 161 stack size, setting for interpreter, 247 stack traces for, displaying with jdb, 265 suspending execution with jdb debugger, 264 synchronizing, 54, 162, 406 IllegalMonitorStateException, 397 terminating, 161 Thread class, 160, 375, 423 ThreadDeath error, 426 ThreadGroup class, 426 ThreadLocal class, 427 timers for, 161 type, specifying for Java interpreter and Classic VM, 244 waiting for another to finish, 162 waiting, list of, 163 throw statements, 49, 55−57 declaring exceptions, 56 exception types, 56 Throwable interface, 56, 375, 428 throwing exceptions, 18 throws clause, 65 @throws doc comment tag, 229 timeouts, socket, 466, 472

Timer class, 161, 681 TimerTask class, 161, 682 TimeZone class, 683 SimpleTimeZone class, 678 tokenizing strings, 150, 368, 681 tools, Java development (see SDK) TooManyListenersException class, 213, 684 toString( ), 35 tracing by interpreter, enabling/disabling, 410 transferFrom() (FileChannel), 184 transferTo( ) (FileChannel), 184 Transformer class, 194 TransformerFactory class, 194 transforming XML documents, 144, 191, 194, 811 applying XSLT stylesheet and writing to a stream, 195 from DOM tree into stream of XML text (example), 194 transient fields, object serialization and, 231 transient modifier, 140 tree representation of XML documents, 191, 193 TreeMap class, 684 TreeSet class, 685 trigonometric functions, 152 trimming whitespace from strings, 417 triple-DES key, 756 trust, fine-grained levels in Java 1.2, 206 TrustAnchor class, 593 TrustManager interface, 778 TrustManagerFactory class, 778 TrustManagerFactorySpi class, 779 truth values, 23 try clause, 58 try/catch/finally statements, 57−60 tutorial, Java programming, 17 twos-complement format, representing negative numbers, 39 type conversions, 27, 43 reference types, 79 types (see data types)

Index

7 March 2002 11:43

965

U unary operators ! (boolean NOT) operator, 38 - (negation) operator, 35 ˜ (bitwise complement), 39 associativity of, 32 unchecked exceptions, 56 UndeclaredThrowableException, 442 undecremented values, 36 unicast events, 213 registering listener for, 219 Unicode, 8, 20 applet parameter values, converting to, 235 char data type, 23 characters in Java names, 223 converting strings to/from bytes, 143 currency symbols in identifiers, 21 escape sequences, 24 named subset of, 383 native2ascii tool and, 268 PrintStream class and, 361 UnicodeBlock class, 383 UTF-8 encoding of, 183 UTFDataFormatException, 372 Unix classpath, specifying, 248 emacs text editor, 10 file and path separators, 234 Java interpreter, 4 threads for Java interpreter and Classic VM, 244 UnknownError class, 429 UnknownHostException class, 472 UnknownServiceException class, 472 unmodifiable methods (Collections), 650 unnamed packages, 82 UnrecoverableKeyException class, 569 unreliable datagram packets, 452 UnresolvedPermission class, 569 UnsatisfiedLinkError, 429 unsigned data types, 24 unsigned right-shift (>>>) operator, 40 UnsupportedCallbackException class, 794

966

7 March 2002 11:43

Index

UnsupportedClassVersionError, 429 UnsupportedEncodingException, 371 UnsupportedOperationException, 430, 650, 649 until loops, 16 untrusted code, 202−208 access control, 202 fine-grained levels in Java 1.2, 206 sandbox (Java 1.0), 204 application programming, use in, 208 byte-code verification of class files, 203 updating JAR archive contents, 239 JAR file manifest, 241 loop variables, 51 URIs converting files to/from, 334 URI class, 472 URISyntaxException class, 474 URLClassLoader class, 159 permissions to loaded code, 208 URLs HttpURLConnection class, 455 JAR archive URLs, 460 JavaBeans conventions, 212 javadoc-generated document, specifying for top-level directory, 254 keystore file containing keys and certificates, 241 MalformedURLException, 461 URL class, 171, 448, 474 URLClassLoader class, 476 URLConnection class, 448, 477 URLDecoder class, 479 URLEncoder class, 479 URLStreamHandler class, 479 URLStreamHandlerFactory interface, 480 US-ASCII charset, 182 user interface, low-level login module, 144 user preference files, Properties class and, 176

user preferences, 715 java.util.prefs package, 710 package for reading and writing, 143 Preferences class, 177 username and password, encapsulating, 463 userNodeForPackage( ) (Preferences), 177 users, security for, 208 replacing user policies, 209 UTF-8 encoding of Unicode, 20, 183 converting Latin-1 encoding to and writing to output channel, 185 UTFDataFormatException, 372 utilities, packages for, 143 utilities (java.util package), 81

V validating, certificate chains, 582 validation InvalidObjectException, 345 ObjectInputValidation class, 351 variables, 13, 29, 138 accessible to local classes, 131 assigning values to, 13 declaring Java vs. C language, 86 placement of, 16 fields vs., 89 global, class fields as, 90 IllegalAccessError, 396 incrementing, as side effect of ++ operator, 33 initializing, field declarations vs., 96 local, 45 capitalization/naming conventions, 223 local scope, local classes and, 132 loop, initializing, testing, and updating, 51 scope, 14 scope of, 46 storing objects in, 67 variable type for operands, 33 vars keyword, 250 Vector class, 156, 686

verbose command-line arguments enabling assertions, 61 verifying classes, byte-code verification error, 430 classes with javap tool, 260 hostname for SSL connections, 766 JAR files (jarsigner tool), 242 verifying byte code for untrusted classes, 203 verifying digital signatures, 198 JAR files, 241 @version doc comment tag, 228 versions class, UnsupportedClassVersionError, 429 class or classes, displaying for, 270 Java, 5 1.2, security advances in, 7 running programs, 85 Java interpreter, 243, 245 specifying in @since doc comment tag, 231 VetoableChangeListener class, 213, 302 bean context and, 221 registering and removing listeners, 217 VetoableChangeListenerProxy class, 303 VetoableChangeSupport class, 218, 303 virtual functions (C++), 109, 116 Virtual Machine, Java (see JVM) virtual method invocation, 108 VirtualMachineError class, 430 visibility of beans, 212 class members, 113 local classes, 130 members, working with, 435 Visibility interface, 304 Void class, 431 void keyword, 12, 54, 65 volatile modifier, 140

Index

7 March 2002 11:43

967

W W3C (World Wide Web Consortium) DOM (Document Object Model), 145, 191 org.w3c.dom package, 833 wait( ) (Object), 163 waking threads, 164, 424 warning(), 178 weak references, package for, 143 WeakHashMap class, 688 WeakReference class, 431, 433 while loops, 16, 50 continue statement, starting new iteration, 53 whitespace delimiting tokens, 369 leading and trailing, removing from strings, 417 for readability in programs, 15 widening conversions, 27 among reference types, 79, 117 objects, 80 objects, inheritance through subclassing, 103 Windows platforms, 4 classpath, setting, 248 file and path separators, 234 Java interpreter, 4, 243 Notepad and WordPad text editors, 10 SDK for, 9 SDK, downloading from Sun Microsystems, 9 wizards, 214 WordPad, 10 World Wide Web Consortium (see W3C) WritableByteChannel interface, 181, 183 “Write once, run anywhere”, 6, 223 write permission for files, 339 write( ) FileChannel class, 183 GatheringByteChannel interface, 181 WriteAbortedException class, 372 writeExternal() (Externalizable), 232 writeObject( ), 232 Writer class, 166, 372

968

7 March 2002 11:43

Index

writing byte and character streams, 166 compressed data to file, 168 to files, 364 untrusted applets, 236 serialized objects to streams, 170 streaming data to arrays or strings, 169 text file to output channel, 185

X X.500 certificates, distinguished name, 267 X500Principal class, 803 X500PrivateCredential class, 804 X509Certificate class, 573, 577, 593 (see also Certificate class) X509CertSelector class, 594 X509CRL class, 573, 577, 596 X509CRLEntry class, 597 X509CRLSelector class, 597 X509EncodedKeySpec interface, 608 X509Extension interface, 598 X509KeyManager interface, 780 X509TrustManager interface, 780 XML JAXP (Java API for XML Processing), 191−196 DOM parser, 193 parsing XML with SAX, 192 transforming XML documents, 194 packages for, 144 preference data, errors in, 713 transforming document content, 811 XML files bean state, writing persistently to, 214 preference names and values, exporting as, 178 XML parsers DOM DocumentBuilder class, 806 DocumentBuilderFactory class, 807 FactoryConfigurationError, 808 javax.xml.parsers package, 805

XML parsers (continued) ParserConfigurationException, 808 SAX, 848 SAXParser class, 809 SAXParserFactory class, 810 XMLDecoder class, 170, 214, 305 XMLEncoder class, 170, 214, 305 XMLFormatter class, 709 XMLReader class, 192 XOR (ˆ) operator (bitwise), 39 ˆ= (bitwise XOR assignment) operator, 41 XOR (ˆ) operator (boolean), 38 XSLT java.xml.transform package, 194 stylesheets, applying to XML document and writing to a stream, 195

transformation engine, 144 transforming XML documents, 191

Z zero extension technique, 40 ZIP archives, classes for, 81 ZIP files, JAR files vs., 689 ZIP files, package for, 144 ZipEntry class, 734 ZipException, 735 ZipFile class, 168, 735 ZipInputStream class, 736 ZipOutputStream class, 737

Index

7 March 2002 11:43

969

CHAPTER 27

Test Table

This is a way to fix this table

Table 27−1. Java regular expression quick refer ence Syntax

Matches

Single characters x

The character x, as long as x is not a punctuation character with special meaning in the regular expression syntax.

\p

The punctuation character p.

\\

The backslash character.

\n

Newline character \u000A.

\t

Tab character \u0009.

\r

Carriage return character \u000D.

\f

Form feed character \u000C.

\e

Escape character \u001B.

\a

Bell (alert) character \u0007.

\uxxxx

Unicode character with hexadecimal code xxxx.

\xxx

Character with hexadecimal code xx.

\0n

Character with octal code n.

\0nn

Character with octal code nn.

\0nnn

Character with octal code nnn, in which nnn